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): Phase B — enrich expand contract with canon arrays + plumb canon into arc prompts

[._.]/ Adam Eivy92943f43c2fd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 666a251957..2e9911d0bf 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -13,6 +13,8 @@
- **Universe Builder categories now carry a canon trunk (`kind`)** so each bucket knows whether it belongs under Cast, Places, Objects, or Other. Built-in defaults are pre-tagged (landscapes/environments/structures → Places, vehicles → Objects); custom buckets default to Other until you sort them. The default `characters` category was retired — canon owns characters now, and any pre-existing character variations get folded into universe canon on upgrade. Foundation for the upcoming tabbed-trunk Universe Builder redesign.
- **TUI providers now return clean responses via a per-run output file.** Claude Code TUI / Codex TUI runs are now instructed to write their final response to `data/runs/<runId>/tui-response.txt`, which the runner reads back instead of scraping the PTY screen — no more banner art, "5% cost" meters, or "bypass permissions on" hints leaking into stage outputs. Falls back to the existing screen-scrape cleanup when the file isn't written.
- **"From proof" final renders now work with the Codex (gpt-image-2) backend.** Codex CLI's `-i <file>` flag attaches the proof PNG so gpt-image-2 runs in image-edit mode and preserves composition while upscaling, instead of redrawing from scratch. The pipeline UI's "from proof" toggle on covers, back covers, and pages is no longer disabled when Codex is the selected backend; the dispatcher only strips `initImagePath` for the external SD-API backend (which has no i2i wiring). `initImageStrength` is mapped to a natural-language fidelity phrase in the prompt so low strengths keep the proof's layout intact and high strengths leave room for reinterpretation.
+- **Generate From Idea now seeds named canon (characters/places/objects) alongside category variations.** The expand LLM call returns rich first-class entities — a protagonist gets a `physicalDescription`, a recurring location gets a `slugline` + `palette` — that merge directly into universe canon. Existing canon entries always win on name collision so a re-expand can't clobber hand-authored records.
+- **Arc planning prompts now see universe canon by name.** `pipeline-arc-overview`, `pipeline-arc-verify`, `pipeline-arc-resolve`, and `pipeline-volume-verify` templates gained a "World canon" block so arc planning + continuity findings can ground/flag drift against the actual named cast/places/objects, not just the exploratory category buckets. Unmodified prompts auto-update on launch; customized prompts get a warning + manual-merge instructions naming all four files.
## Fixed
diff --git a/PLAN.md b/PLAN.md
index 89ec8c9c9e..ef2af8fd66 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -36,7 +36,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
- [x] ~~**Retire `universe.categories` on the schema.**~~ **Rejected 2026-05-17** — categories are an active user-facing exploration workflow (custom buckets like `factions`/`colonies`/`raider_clans`, bulk variation generation, batch render). Canon has no equivalent. See "Categories vs canon — decision" below.
- [→] **Drop the default `characters` category.** Folded into Next Up #1 Phase A.
- [→] **Universe expand LLM contract enrichment.** Folded into Next Up #1 Phase B.
-- [ ] **arcPlanner prompt context — include canon characters/places/objects.** `server/services/pipeline/arcPlanner.js:96` only renders `world.categories` into `worldCategoriesText`. With the `characters` default category retired (schema v4), characters now live in `world.characters[]` (canon) and don't surface in arc-planning prompts. Add a sibling `renderCanonForPrompt(world)` helper and a `worldCanonText` context field; update the arc prompt template + tests. Same gap likely exists in other prompt builders that read `world.categories` — sweep with `grep -rn "world\.categories" server/services/pipeline server/services/universeBuilder*.js`.
+- [→] **arcPlanner prompt context — include canon characters/places/objects.** Folded into Next Up #1 Phase B (Phase B PR shipped `renderCanonForPrompt(world)` + `worldCanonText` + migration 019 for the arc-resolve/volume-verify templates). Follow-up: sweep `grep -rn "world\.categories" server/services/pipeline server/services/universeBuilder*.js` for other prompt builders that read categories but not canon.
- [ ] **Settings → Places kind rename.** `BIBLE_KIND.SETTING → BIBLE_KIND.PLACE`, `BIBLE_FIELD[SETTING]: 'settings' → 'places'`. Touches ~20 files. Stick the rename to bible context — app settings stays as "settings".
- [ ] **Use rendered reference images as i2i anchors in downstream comic-page renders for models that support it.** SDXL/Flux pipelines anchor every panel render on the per-character rendered ref.
@@ -81,6 +81,10 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
### Code quality / dedup (from `/simplify` passes)
+- [ ] **Extract `mergeExpandIntoDraft(draft, result)` from `UniverseBuilder.jsx#handleExpand`.** The function is ~150 lines mixing pure-merge logic (categories, sheets, canon, locks) with I/O shell (API call, setDraft, auto-save, toast). Pull the merge into a top-level pure helper so the I/O surface shrinks and the merge is unit-testable. Deferred from Phase B `/simplify` to keep that PR tightly scoped.
+- [x] ~~**Auto-save after expand can clobber concurrent canon edits.**~~ **Fixed in Phase B Copilot iteration 13** — both `handleExpand`'s auto-save and `handleSave`'s manual-save (when `canonDirty`) now refetch the server's canon via `getUniverse(selectedId)` and merge local additions with `mergeCanonByName` before the update payload is sent. Concurrent edits from NounsStage/other tabs are preserved on identity collision.
+- [ ] **Canon-merge can revert concurrent deletions/renames.** `UniverseBuilder.jsx` (handleSave + handleExpand auto-save) currently merges the FULL stale draft canon onto the refetched server canon — which protects against losing local additions but ALSO re-adds entries another tab deleted (because `mergeCanonByName` dedupes by name, the deleted entry is "preserved" from the stale draft). Real fix: track JUST the merged-from-expand additions in a sidecar set, merge only those onto the refetched server canon. Deferred from Phase B Copilot iteration 14 — needs a per-expand additions ledger.
+- [ ] **Extract `useSwipeNav` hook + `lib/clipboard.js`.** `MediaLightbox` swipe nav; clipboard inlined across 8+ call sites. Clipboard can move now.
- [ ] **Route `MediaLightbox` settings drawer through `components/Drawer.jsx`.** Reconcile `Drawer`'s flat Esc handler with the lightbox's layered Escape cascade.
- [ ] **`useAsyncAction` post-unmount setState guard.** Add `mountedRef` to gate `setRunning(false)`. YAGNI today; do at 4th consumer.
- [ ] **Scene-level wardrobe picking.** Per-scene `characterAppearances: [{ characterId, wardrobeId? }]` on storyboard scenes with wardrobe-picker dropdown. Decide first: does the extractor guess or does the user pick? Append wardrobe after physicalDescription vs substitute body fields?
@@ -142,7 +146,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
- [ ] **Comic-book PDF export.** Once `stages.comicPages` carries enough panel data + rendered images, export print-ready PDF.
- [ ] **Voice-controlled stage advancement.** Register pipeline stage navigation actions in `voice/tools.js`.
- [ ] **AI-assisted panel/scene prompt generation.** Reserve `pipeline-comic-panel-image-prompt.md` and `pipeline-storyboard-image-prompt.md` for a future "turn script fragment into N image-gen prompts" button.
-- [ ] **Extract migration scaffolding into `scripts/migrations/_lib.js`.** Migrations 003 and 006 both implement the same hash-driven prompt-replace pattern (~75 lines of boilerplate each). Lift to a shared helper; next migration becomes ~15 lines.
+- [ ] **Extract migration scaffolding into `scripts/migrations/_lib.js`.** Migrations 003, 006, and 019 all implement the same hash-driven prompt-replace pattern (~75 lines of boilerplate each). Lift to a shared helper; next migration becomes ~15 lines.
- [ ] **Shots-aware scene-output-contract partial.** Split into `_partials/scene-fields-core.md` + `_partials/scene-fields-shots.md` when a third shots-using stage appears.
- [ ] **Per-panel/scene image progress in the Pipeline UI.** ComicPages and Storyboards record `jobId` but don't subscribe to the media-job SSE for live preview.
diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsx
index ca2d11c702..06506295f2 100644
--- a/client/src/pages/UniverseBuilder.jsx
+++ b/client/src/pages/UniverseBuilder.jsx
@@ -71,9 +71,48 @@ const mergeVariations = (existing, fresh) => {
return merged;
};
+// Merge LLM-expanded canon entries into the draft's existing canon array.
+// Existing entries always win on collision (lock or no — the user authored
+// them; the LLM's repeat is a hallucination at this point). Dedupes by name
+// AND slugline (for settings) so an expand that re-emits "Foundry City" or
+// "INT. FOUNDRY CITY — DAY" can't create a phantom duplicate. Mirrors the
+// server-side dedupe in backfillCanonFromCategories (storyBible#normalizeBibleName).
+const mergeCanonByName = (existing, fresh) => {
+ // Empty/missing fresh — return `existing` unchanged (preserve reference so
+ // a no-op expand doesn't trigger downstream identity-comparing effects).
+ if (!fresh?.length) return existing || [];
+ const norm = (s) => (typeof s === 'string' ? s.trim().toLowerCase() : '');
+ const seen = new Set();
+ for (const e of existing || []) {
+ if (e?.name) seen.add(norm(e.name));
+ if (e?.slugline) seen.add(norm(e.slugline));
+ }
+ const merged = [...(existing || [])];
+ for (const e of fresh) {
+ const nameKey = norm(e?.name);
+ const sluglineKey = norm(e?.slugline);
+ if ((nameKey && seen.has(nameKey)) || (sluglineKey && seen.has(sluglineKey))) continue;
+ if (nameKey) seen.add(nameKey);
+ if (sluglineKey) seen.add(sluglineKey);
+ merged.push(e);
+ }
+ return merged;
+};
+
const humanizeCategory = (key) => CATEGORY_LABELS[key]
|| key.replace(/_/g, ' ').replace(/\b\w/g, (ch) => ch.toUpperCase());
+// Toast summary for handleExpand — same body, different tail depending on
+// whether the auto-save succeeded.
+const expandToast = (draft, variationCount, saved) => {
+ const canonCount = (draft.characters?.length || 0)
+ + (draft.settings?.length || 0)
+ + (draft.objects?.length || 0);
+ const sheetCount = draft.compositeSheets?.length || 0;
+ const base = `Expanded into ${variationCount} variations, ${sheetCount} boards, ${canonCount} canon entries`;
+ return `${base} — ${saved ? 'saved' : 'review then Save'}`;
+};
+
const ensureDraftCategories = (categories = {}) => ({
...Object.fromEntries(WORLD_CATEGORIES.map((c) => [c, { variations: [] }])),
...(categories || {}),
@@ -498,6 +537,15 @@ export default function UniverseBuilder() {
return out;
})();
+ // Merge LLM-emitted canon arrays into the draft's existing canon. Existing
+ // entries always win on name/slugline collision so a re-expand can't
+ // clobber hand-authored or series-extracted records. mergeCanonByName
+ // short-circuits when `fresh` is empty so identity is preserved.
+ const pickCanon = (key) => mergeCanonByName(draft[key] || [], Array.isArray(result[key]) ? result[key] : []);
+ const mergedCharacters = pickCanon('characters');
+ const mergedSettings = pickCanon('settings');
+ const mergedObjects = pickCanon('objects');
+
const expandedDraft = {
...draft,
starterPrompt: pick('starterPrompt', result.starterPrompt),
@@ -507,6 +555,9 @@ export default function UniverseBuilder() {
influences: refinedInfluences,
categories: ensureDraftCategories(mergedCategories),
compositeSheets: mergedSheets,
+ characters: mergedCharacters,
+ settings: mergedSettings,
+ objects: mergedObjects,
llm: result.llm || draft.llm,
};
setDraft(expandedDraft);
@@ -531,6 +582,9 @@ export default function UniverseBuilder() {
styleNotes: expandedDraft.styleNotes || '',
categories: expandedDraft.categories,
compositeSheets: expandedDraft.compositeSheets || [],
+ characters: expandedDraft.characters || [],
+ settings: expandedDraft.settings || [],
+ objects: expandedDraft.objects || [],
influences: ensureInfluences(expandedDraft.influences),
locked: expandedDraft.locked || {},
llm: expandedDraft.llm || {},
@@ -540,11 +594,11 @@ export default function UniverseBuilder() {
const without = prev.filter((w) => w.id !== updated.id);
return [updated, ...without];
});
- toast.success(`Expanded into ${total} variations and ${expandedDraft.compositeSheets?.length || 0} boards — saved`);
+ toast.success(expandToast(expandedDraft, total, true));
return;
}
}
- toast.success(`Expanded into ${total} variations and ${expandedDraft.compositeSheets?.length || 0} boards — review then Save`);
+ toast.success(expandToast(expandedDraft, total, false));
};
// Writes the LLM-refined fields back to the draft. The modal only emits
diff --git a/data.sample/prompts/stages/pipeline-arc-resolve.md b/data.sample/prompts/stages/pipeline-arc-resolve.md
index 58e01aaa52..09ffd29755 100644
--- a/data.sample/prompts/stages/pipeline-arc-resolve.md
+++ b/data.sample/prompts/stages/pipeline-arc-resolve.md
@@ -18,7 +18,13 @@ Every series is published as both a graphic novel (issues → volumes) AND a TV
The arc is grounded in this World Builder world: **{{worldName}}**. When you rewrite synopses, ground them in these entities by name. If a finding flagged "world entity drift", swap the made-up entity for the closest match below.
-### World entity categories
+### World canon — named characters, places, objects
+
+```
+{{worldCanonText}}
+```
+
+### World entity categories — exploratory variation buckets
```
{{worldCategoriesText}}
diff --git a/data.sample/prompts/stages/pipeline-volume-verify.md b/data.sample/prompts/stages/pipeline-volume-verify.md
index 22e4e1cb26..652c0b272c 100644
--- a/data.sample/prompts/stages/pipeline-volume-verify.md
+++ b/data.sample/prompts/stages/pipeline-volume-verify.md
@@ -18,7 +18,13 @@ Every series is published in two parallel formats: graphic novel (issues → vol
The arc was authored against this World Builder world: **{{worldName}}**. Continuity findings should call out when the volume references factions / characters / locations that don't exist in this entity set.
-### World entity categories
+### World canon — named characters, places, objects
+
+```
+{{worldCanonText}}
+```
+
+### World entity categories — exploratory variation buckets
```
{{worldCategoriesText}}
diff --git a/scripts/migrations/019-arc-verify-resolve-canon-context.js b/scripts/migrations/019-arc-verify-resolve-canon-context.js
new file mode 100644
index 0000000000..028968aae5
--- /dev/null
+++ b/scripts/migrations/019-arc-verify-resolve-canon-context.js
@@ -0,0 +1,118 @@
+/**
+ * Add `{{worldCanonText}}` context block to arc-verify + arc-resolve prompt
+ * templates so the LLM sees named universe canon (characters/places/objects)
+ * alongside the existing exploratory `worldCategoriesText`.
+ *
+ * Why:
+ * Phase A retired the default `characters` category; characters now live in
+ * `universe.characters[]` (canon). Without this template change, arc-level
+ * prompts that grounded continuity findings in entity names lost the
+ * character roster entirely. See PLAN.md → Phase B + the
+ * "arcPlanner prompt context — include canon" backlog item it folded in.
+ *
+ * Strategy — unmodified-only update, mirrors migration 003:
+ * - If the on-disk file matches the prior shipped MD5 (either the pre-005
+ * hash or the currently-shipped hash), replace with the data.sample
+ * version that includes {{worldCanonText}}.
+ * - If diverged (user customized), warn and skip.
+ *
+ * Idempotent: a re-run on the new hash is a no-op.
+ */
+
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { createHash } from 'crypto';
+
+const md5 = (str) => {
+ const normalized = str.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
+ return createHash('md5').update(normalized).digest('hex');
+};
+
+// Hashes the file may have on disk pre-migration (per-file array — most
+// recent shipped hash first, then older). Any match is treated as
+// "unmodified by user → safe to replace."
+const ACCEPTED_OLD_MD5 = {
+ 'pipeline-arc-resolve.md': [
+ 'a8677bbe1eb38f871fb152a5b0fec7c6', // current (pre-Phase B) shipped
+ '87bc5c01f1a8a97b681727a38b05edc6', // pre-005 (shape-aware), still in setup-data.js OLD list
+ ],
+ 'pipeline-volume-verify.md': [
+ '03f3c874cb80e1c98abcf03168fa7a92', // current (pre-Phase B) shipped
+ 'c6ea28e972ad6e229bafb2d602b4dda3', // pre-005 (shape-aware), still in setup-data.js OLD list
+ ],
+};
+
+// New shipped hashes — what data.sample carries post-migration.
+const NEW_SHIPPED_MD5 = {
+ 'pipeline-arc-resolve.md': '2651dc3947adc75c02c4f394135f2703',
+ 'pipeline-volume-verify.md': '56ad31371452a6fdf68597512f8c0d35',
+};
+
+export default {
+ async up({ rootDir }) {
+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ const sampleDir = join(rootDir, 'data.sample', 'prompts', 'stages');
+
+ let updated = 0;
+ let alreadyCurrent = 0;
+ let skipped = 0;
+
+ for (const filename of Object.keys(ACCEPTED_OLD_MD5)) {
+ const dataPath = join(stagesDir, filename);
+ const samplePath = join(sampleDir, filename);
+
+ const existing = await readFile(dataPath, 'utf-8').catch((err) => {
+ if (err.code !== 'ENOENT') throw err;
+ return null;
+ });
+
+ if (existing === null) {
+ // setup-data.js will copy it on next run; nothing for us to do.
+ console.log(`📄 arc-prompt ${filename}: not present in data/, will be created by setup-data.js`);
+ continue;
+ }
+
+ const existingMd5 = md5(existing);
+
+ if (existingMd5 === NEW_SHIPPED_MD5[filename]) {
+ alreadyCurrent++;
+ continue;
+ }
+
+ const acceptedOld = ACCEPTED_OLD_MD5[filename];
+ if (!acceptedOld.includes(existingMd5)) {
+ console.warn(
+ `⚠️ arc-prompt ${filename} has been customized — skipping auto-update.\n` +
+ ` To pick up {{worldCanonText}} manually, diff:\n` +
+ ` data.sample/prompts/stages/${filename}\n` +
+ ` against your current:\n` +
+ ` data/prompts/stages/${filename}\n` +
+ ` and add the new "World canon" block above the categories block.`,
+ );
+ skipped++;
+ continue;
+ }
+
+ const sampleContent = await readFile(samplePath, 'utf-8');
+ await writeFile(dataPath, sampleContent);
+ console.log(`✅ updated arc-prompt: ${filename}`);
+ updated++;
+ }
+
+ if (updated > 0) {
+ console.log(`📝 arc-prompt canon-context migration: ${updated} updated, ${alreadyCurrent} already current, ${skipped} skipped (customized)`);
+ } else if (skipped > 0) {
+ console.log(`📝 arc-prompt canon-context migration: all files either current or customized (${skipped} skipped)`);
+ } else {
+ console.log(`📝 arc-prompt canon-context migration: all files already up to date`);
+ }
+
+ if (skipped > 0) {
+ console.warn(
+ `\n⚠️ ${skipped} arc prompt(s) could not be auto-updated because they were customized.\n` +
+ ` The {{worldCanonText}} block will not render character names in arc-verify/resolve\n` +
+ ` until the files are merged manually. See data.sample/prompts/stages/.`,
+ );
+ }
+ },
+};
diff --git a/scripts/setup-data.js b/scripts/setup-data.js
index cc7ae81d36..2283538fcd 100644
--- a/scripts/setup-data.js
+++ b/scripts/setup-data.js
@@ -151,8 +151,12 @@ const SHIPPED_PROMPT_OLD_MD5 = {
// Shape-aware additions (migration 005).
'pipeline-arc-overview.md': '6a3ecab43d1f46b7ef9aab6c69ea0326',
'pipeline-arc-verify.md': '52e31abc93e3105176236fcaa5d1575a',
- 'pipeline-volume-verify.md': 'c6ea28e972ad6e229bafb2d602b4dda3',
- 'pipeline-arc-resolve.md': '87bc5c01f1a8a97b681727a38b05edc6',
+ // volume-verify: c6ea28… (pre-005) and 03f3c8… (post-005, pre-019) both
+ // auto-updatable to the post-019 (worldCanonText) hash.
+ 'pipeline-volume-verify.md': ['c6ea28e972ad6e229bafb2d602b4dda3', '03f3c874cb80e1c98abcf03168fa7a92'],
+ // arc-resolve: 87bc5c… (pre-005) and a8677b… (post-005, pre-019) both
+ // auto-updatable to the post-019 (worldCanonText) hash.
+ 'pipeline-arc-resolve.md': ['87bc5c01f1a8a97b681727a38b05edc6', 'a8677bbe1eb38f871fb152a5b0fec7c6'],
// Shot decomposition additions (migration 006).
'pipeline-extract-scenes.md': '59fa5ee305ce53d91eb15224d8b546d3',
// INT/EXT + time-of-day additions to the places extractor (migration 007).
@@ -177,8 +181,8 @@ const SHIPPED_PROMPT_NEW_MD5 = {
'pipeline-season-episodes.md':'50c68a29c3ebc275db3095d06bd87100',
'pipeline-arc-overview.md': 'd34d72b8e49ba303d38607845dd87f1c',
'pipeline-arc-verify.md': 'ff56d8387162017e08d5d0491060ddd6',
- 'pipeline-volume-verify.md': '03f3c874cb80e1c98abcf03168fa7a92',
- 'pipeline-arc-resolve.md': 'a8677bbe1eb38f871fb152a5b0fec7c6',
+ 'pipeline-volume-verify.md': '56ad31371452a6fdf68597512f8c0d35',
+ 'pipeline-arc-resolve.md': '2651dc3947adc75c02c4f394135f2703',
'pipeline-extract-scenes.md': 'c51fb208568d0d903eb43b437478b0ba',
'writers-room-places.md': '24a33628cc94d80fa5ca60831d973daf',
'cos-agent-briefing.md': 'dccb392a43cbd3dac900fee12c31619a',
diff --git a/server/lib/universePromptRenderers.js b/server/lib/universePromptRenderers.js
index a4f627b8a2..fe71c04716 100644
--- a/server/lib/universePromptRenderers.js
+++ b/server/lib/universePromptRenderers.js
@@ -31,3 +31,52 @@ export function renderCompositesForPrompt(composites, { showLocked = false } = {
})
.join('\n');
}
+
+// Per-canon-kind formatting table — header label + per-entry line builder.
+// One row per canon trunk; renderCanonForPrompt iterates this so a future
+// kind addition (or field tweak) is a one-line change.
+const CANON_SECTIONS = [
+ {
+ field: 'characters',
+ header: 'characters',
+ formatEntry: (c) => {
+ const desc = c.physicalDescription || c.description || '';
+ const role = c.role ? ` [${c.role}]` : '';
+ return ` - ${c.name}${role}${desc ? `: ${desc}` : ''}`;
+ },
+ },
+ {
+ field: 'settings',
+ header: 'places',
+ formatEntry: (s) => {
+ const label = s.name || s.slugline || '(unnamed)';
+ const desc = s.description || '';
+ const palette = s.palette ? ` palette: ${s.palette}` : '';
+ return ` - ${label}${desc ? `: ${desc}` : ''}${palette}`;
+ },
+ },
+ {
+ field: 'objects',
+ header: 'objects',
+ formatEntry: (o) => {
+ const desc = o.description || '';
+ const sig = o.significance ? ` (${o.significance})` : '';
+ return ` - ${o.name}${desc ? `: ${desc}` : ''}${sig}`;
+ },
+ },
+];
+
+// Render the universe's canon arrays (characters/settings/objects) into a
+// prompt-friendly text block. Distinct from renderCategoriesForPrompt because
+// canon entries are first-class named entities with rich metadata, not
+// exploratory variations — the arc planner references them by name.
+export function renderCanonForPrompt(world) {
+ if (!world || typeof world !== 'object') return '';
+ const sections = [];
+ for (const { field, header, formatEntry } of CANON_SECTIONS) {
+ const entries = Array.isArray(world[field]) ? world[field] : [];
+ if (!entries.length) continue;
+ sections.push(`${header}:\n${entries.map(formatEntry).join('\n')}`);
+ }
+ return sections.join('\n\n');
+}
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index 0c3b2008ad..b7e54c4055 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -6,7 +6,7 @@
* GET /api/universe-builder/:id → Universe
* PATCH /api/universe-builder/:id → Universe
* DELETE /api/universe-builder/:id → { id }
- * POST /api/universe-builder/expand → { influences, categories, compositeSheets, llm }
+ * POST /api/universe-builder/expand → { logline, premise, styleNotes, influences, categories, compositeSheets, characters, settings, objects, llm }
* POST /api/universe-builder/:id/render → { runId, collectionId, jobIds, promptCount }
* GET /api/universe-builder/:id/runs → Run[]
*/
diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.js
index b705e070b9..a67831691d 100644
--- a/server/services/pipeline/arcPlanner.js
+++ b/server/services/pipeline/arcPlanner.js
@@ -39,7 +39,7 @@ import { recommendStructure, describeStructure } from '../../lib/seasonStructure
import { LENGTH_PROFILE_NAMES, DEFAULT_LENGTH_PROFILE } from '../../lib/issueLength.js';
import { getUniverse } from '../universeBuilder.js';
import { getSeriesCanon } from './seriesCanon.js';
-import { renderCategoriesForPrompt, renderCompositesForPrompt } from '../../lib/universePromptRenderers.js';
+import { renderCategoriesForPrompt, renderCompositesForPrompt, renderCanonForPrompt } from '../../lib/universePromptRenderers.js';
export const ERR_VALIDATION = 'PIPELINE_ARC_VALIDATION';
const makeErr = (message, code) => Object.assign(new Error(message), { code });
@@ -95,6 +95,10 @@ async function loadWorldContext(universeId) {
worldInfluencesAvoid: avoid.length ? avoid.join(', ') : '(none)',
worldCategoriesText: renderCategoriesForPrompt(world.categories) || '(none)',
worldCompositesText: renderCompositesForPrompt(world.compositeSheets) || '(none)',
+ // Universe canon — named characters/places/objects the arc references by
+ // name. Separate from categories because the LLM should treat these as
+ // first-class entities, not exploratory variations.
+ worldCanonText: renderCanonForPrompt(world) || '(none)',
};
}
@@ -110,6 +114,7 @@ const EMPTY_WORLD_CONTEXT = {
worldInfluencesAvoid: '(none)',
worldCategoriesText: '(none — series has no linked Universe Builder world)',
worldCompositesText: '(none)',
+ worldCanonText: '(none — series has no linked Universe Builder world)',
};
// Resolve world context, accepting an optional preloaded value so callers
diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.js
index ae7b33f2db..cf57253958 100644
--- a/server/services/pipeline/arcPlanner.test.js
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -169,14 +169,15 @@ describe('arcPlanner — generateArcOverview', () => {
{ label: 'The Lollipop Bureau', prompt: 'pastel public-facing agency' },
{ label: 'The Velvet Null', prompt: 'minimalist rival' },
] },
- // `characters` was retired as a default category in schema v4 — any
- // variations under it now fold into universe.characters[] (canon).
- // Use the cast leads as canon characters directly. Note: arcPlanner's
- // current `worldCategoriesText` only reads from categories; canon
- // characters aren't included yet (deferred to Phase B/C — see
- // PLAN.md Backlog: "arcPlanner prompt context should include canon").
- // For now this test only asserts category data flows through.
},
+ // Canon characters (Phase B contract — first-class named entities; the
+ // `characters` default category was retired in Phase A schema v4).
+ characters: [
+ { name: 'Mira Holt', physicalDescription: 'field detective in a chartreuse coat' },
+ ],
+ objects: [
+ { name: 'The Tongue', description: 'an artifact that absorbs language' },
+ ],
compositeSheets: [
{ kind: 'reference_sheet', label: 'Rival agencies branding', prompt: 'comparison sheet' },
],
@@ -197,6 +198,12 @@ describe('arcPlanner — generateArcOverview', () => {
expect(ctx.worldCategoriesText).toContain('factions');
expect(ctx.worldCategoriesText).toContain('The Lollipop Bureau');
expect(ctx.worldCategoriesText).toContain('The Velvet Null');
+ // Phase B: canon entries surface in their own context field so the LLM
+ // can reference characters/places/objects by name (independent of
+ // categories, which stay as the exploratory-variation surface).
+ expect(ctx.worldCanonText).toContain('Mira Holt');
+ expect(ctx.worldCanonText).toContain('field detective');
+ expect(ctx.worldCanonText).toContain('The Tongue');
expect(ctx.worldCompositesText).toContain('Rival agencies branding');
expect(ctx.worldInfluencesEmbrace).toContain('Moebius');
expect(ctx.worldInfluencesAvoid).toContain('gritty');
@@ -212,6 +219,7 @@ describe('arcPlanner — generateArcOverview', () => {
const ctx = stageRunnerSpy.mock.calls[0][1];
expect(ctx.worldName).toMatch(/no linked world/i);
expect(ctx.worldCategoriesText).toMatch(/none/i);
+ expect(ctx.worldCanonText).toMatch(/none/i);
});
it('throws ERR_VALIDATION + skips the LLM call when arc is locked', async () => {
diff --git a/server/services/universeBuilderExpand.js b/server/services/universeBuilderExpand.js
index 0030c1fb9c..fb5aa0d8db 100644
--- a/server/services/universeBuilderExpand.js
+++ b/server/services/universeBuilderExpand.js
@@ -14,6 +14,7 @@
import { getActiveProvider, getProviderById } from "./providers.js";
import {
WORLD_CATEGORIES,
+ CATEGORY_KINDS,
LOCKABLE_FIELDS,
LOCKABLE_FIELD_LABELS,
PROMPT_FRAGMENT_MAX,
@@ -27,6 +28,7 @@ import {
sanitizeCompositeSheets,
sanitizeInfluences,
} from "./universeBuilder.js";
+import { sanitizeBibleList, BIBLE_KIND, BIBLE_SOURCE } from "../lib/storyBible.js";
import { ServerError } from "../lib/errorHandler.js";
import { extractJson as extractJsonShared } from "../lib/jsonExtract.js";
import {
@@ -126,25 +128,31 @@ Return a SINGLE JSON object. NO markdown, NO commentary. The object MUST have th
- 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.
- influences: object { "embrace": [string], "avoid": [string] }. THIS IS THE UNIVERSE'S STYLE + NEGATIVE PROMPT. Each list is a set of short prompt tokens (max 120 chars each, max 30 per list). The "embrace" list is joined verbatim as the positive style prompt prepended to every render (palette, lighting, render quality, artist references — e.g. "moebius linework", "cel-shading", "dust palette"). The "avoid" list is joined verbatim as the negative prompt (e.g. "blurry", "lowres", "watermark", "extra fingers"). Use short token-style labels, NOT full sentences. When influence input is provided above, preserve those entries unless the starter idea explicitly contradicts them.
-- categories: object. Atomic reusable buckets. Use snake_case keys. Start from these common buckets when useful:
+- characters: array. Named cast members central to this universe. Each item has { "name": string (max 120 chars), "physicalDescription": string (max 1000 chars, what they look like — face, build, age range, distinguishing marks), "personality": string (max 600 chars), "background": string (max 800 chars, where they come from + role in the world), "prompt": string (max 400 chars, the render-prompt fragment used for reference images), "tags": [string] (1-3 short labels like "protagonist", "antagonist", "supporting") }. Generate 0-8 leads. Distinct from category "variations" (which are exploratory render prompts) — these are first-class entities that downstream pipeline stages address by name.
+- settings: array. Named recurring places in this universe. Each item has { "name": string (max 120 chars, human label like "Foundry City"), "slugline": string (max 120 chars, screenplay-style location header like "EXT. FOUNDRY CITY — DAY"), "description": string (max 1000 chars), "palette": string (max 300 chars, dominant colors), "recurringDetails": string (max 600 chars, recognizable motifs that recur across scenes), "prompt": string (max 400 chars, render-prompt fragment), "tags": [string] }. Generate 0-8 key places.
+- objects: array. Named props / vehicles / artifacts with story weight. Each item has { "name": string (max 120 chars), "description": string (max 1000 chars, what it looks like + what it does), "significance": string (max 600 chars, why it matters to the story), "prompt": string (max 400 chars, render-prompt fragment), "tags": [string] }. Generate 0-5 hero objects.
+- categories: object. Atomic reusable buckets for VISUAL EXPLORATION — bulk-render N variations to see a range of options. Use snake_case keys. Start from these common buckets when useful:
${WORLD_CATEGORIES.map((c) => ` - ${c}`).join("\n")}
Add, remove, or rename buckets to fit the user's actual universe-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.
-Each category value is an object containing a "variations" array. Each variation has the shape { "label": string (max 80 chars), "prompt": string (max 400 chars, comma-separated tokens describing ONE specific subject in this category) }. Concrete example for one category:
- "landscapes": { "variations": [
+Each category value is an object with TWO fields: { "kind": one of ${CATEGORY_KINDS.map((k) => `"${k}"`).join(" | ")}, "variations": array }. The "kind" tags which canon trunk the bucket belongs to — use "characters" for buckets of people/groups (factions, tribes, clans), "settings" for places (landscapes, environments, colonies, structures), "objects" for things (vehicles, tools, artifacts), and "other" when nothing else fits. Each variation has the shape { "label": string (max 80 chars), "prompt": string (max 400 chars, comma-separated tokens describing ONE specific subject in this category) }. Concrete example for one category:
+ "landscapes": { "kind": "settings", "variations": [
{ "label": "Crystalline canyon basin", "prompt": "vast crystalline canyon, salt flats, low horizon" },
{ "label": "Scrap-iron dune sea", "prompt": "rolling dunes of rusted scrap, half-buried machinery" }
] }
Do NOT use \`[...]\`, \`…\`, or any other placeholder/elision tokens — every array MUST contain real variation objects.
+Canon vs categories: a single named entity belongs in CANON (characters/settings/objects) — the protagonist "Ash" goes in characters[], not in a category. A bucket of N exploratory looks belongs in categories — "what could 5 different faction outfit styles look like" goes in a "factions" category with variations[]. The user will iterate on each surface separately.
+
Concrete compositeSheets examples:
{ "kind": "reference_sheet", "label": "Gas-Giant Drifters costume sheet", "prompt": "Create a clean illustrated costume reference sheet for Gas-Giant Drifters, a human colony living on floating platforms and balloon settlements high in a gas giant atmosphere. Show a simplified character lineup with five figures: kite child, storm scout, main hero, sky elder, and rig worker. Include material swatches for sailcloth, balloon-skin, rubberized algae fabric, salvaged foil, flex-ceramic patches, storm-glass lenses, braided tether cord, and copper wire ornament. Include fastener/accessory icons for buckles, spring clips, pressure rings, carabiner hooks, breathing collar, goggles, tether belt, strapped sky boots, and wind streamer tabs. Include a color strip: storm blue, saffron, hot coral, orange, slate gray, cream, electric cyan, copper, cloud white. Minimal readable layout, elegant negative space, light background hints of balloon platforms and storm clouds, not baroque, not hyper-detailed." }
{ "kind": "world_pitch_poster", "label": "Universe summary concept pitch poster", "prompt": "Create a cinematic universe summary concept pitch poster for the whole setting. Use an editorial art-board layout: one dominant hero panorama showing the signature universe location, several smaller inset environment and culture images, a small creature/species lineup, visual-language thumbnails, color palette strip, material/texture swatches, light-and-atmosphere notes, and theme icons. Include large title typography and a short subtitle/logline area, plus readable section headers such as The Universe, The Feel, Aesthetic, Environments, Cultures, Tone, Color Palette, Materials & Textures, and Light & Atmosphere. Keep body copy as short graphic blocks, not dense paragraphs. The poster should feel like a concept pitch board for a film/series/game, with clear hierarchy, elegant negative space, and cohesive art direction." }
# Rules
-- Generate 5-12 categories total, choosing the buckets that serve the starter idea. Generate 4-10 variations per category. They must be visually distinct from each other but stylistically consistent with the universe.
+- Populate canon with the named entities you'd reference by name in a script. Empty arrays are fine when the starter idea doesn't imply specific characters/places/objects yet.
+- Generate 5-12 categories total, choosing the buckets that serve the starter idea. Generate 4-10 variations per category. They must be visually distinct from each other but stylistically consistent with the universe. Tag each category's "kind" so it lands under the right canon trunk in the UI.
- Generate 3-8 compositeSheets when the starter idea involves clothing systems, colonies, factions, cultures, species, vehicles, settlements, props, posters, decks, or other grouped visual-design systems.
- For broad universe/universe/story settings, always include 1-3 "world_pitch_poster" compositeSheets in addition to any "reference_sheet" boards. These are summary concept pitch posters, not atomic character or environment sheets.
- "label" is a short name a human can recognize (e.g. "Crystalline canyon basin", "Scavenger walker mech").
@@ -174,7 +182,10 @@ const isExpansionShape = (o) =>
typeof o.styleNotes === "string" ||
(o.influences && typeof o.influences === "object") ||
(o.categories && typeof o.categories === "object") ||
- Array.isArray(o.compositeSheets));
+ Array.isArray(o.compositeSheets) ||
+ Array.isArray(o.characters) ||
+ Array.isArray(o.settings) ||
+ Array.isArray(o.objects));
const extractJson = (raw) => {
// Empty input is a "client-side" oversight (no LLM output at all) — keep
@@ -258,9 +269,30 @@ const normalizeCompositeSheets = (raw) =>
: [],
);
+// Run an LLM-emitted canon array through the same sanitizer the universe
+// service uses on persisted entries, so the merged-into-draft result has
+// every required field (id, createdAt, etc.) and survives a round-trip
+// through updateUniverse without losing structure. Returns [] for non-arrays
+// so the merge step downstream can rely on `Array.isArray`. Stamps `source`
+// pre-sanitize so the sanitizer's `ensureSource` allowlist validates it (a
+// post-sanitize stamp would bypass that check).
+const normalizeCanonArray = (raw, kind) => {
+ if (!Array.isArray(raw)) return [];
+ const stamped = raw.map((e) => (e && typeof e === 'object' ? { ...e, source: BIBLE_SOURCE.UNIVERSE_EXPAND } : e));
+ // Expand is creating fresh entries; let the sanitizer stamp timestamps
+ // instead of preserving (likely-absent) ones from the LLM output.
+ return sanitizeBibleList(stamped, kind, { preserveTimestamps: false });
+};
+
/**
* Expand a starter prompt into a structured universe template draft.
- * Returns { logline, premise, styleNotes, influences, categories, compositeSheets, llm: { provider, model } }.
+ * Returns { logline, premise, styleNotes, influences, categories, compositeSheets,
+ * characters, settings, objects, llm: { provider, model } }.
+ *
+ * Canon arrays (characters/settings/objects) are sanitized through
+ * sanitizeBibleList so they're shape-compatible with universe.characters[],
+ * universe.settings[], universe.objects[] — the client merges them into the
+ * draft's canon arrays alongside the category merge.
*
* @param {object} options
* @param {string} options.starterPrompt
@@ -357,6 +389,12 @@ export async function expandWorldTemplate({
const compositeSheets = normalizeCompositeSheets(
parsed.compositeSheets || [],
);
+ // normalizeCanonArray stamps `source: BIBLE_SOURCE.UNIVERSE_EXPAND` on each
+ // entry before sanitize, so provenance lands on disk consistently with the
+ // existing categories→canon backfill in universeBuilder.js.
+ const characters = normalizeCanonArray(parsed.characters, BIBLE_KIND.CHARACTER);
+ const settings = normalizeCanonArray(parsed.settings, BIBLE_KIND.SETTING);
+ const objects = normalizeCanonArray(parsed.objects, BIBLE_KIND.OBJECT);
// sanitizeInfluences enforces the same per-entry cap, list cap, and
// case-insensitive dedupe used everywhere else. Distinguish "LLM omitted
// influences entirely" (preserve the user's pinned references) from "LLM
@@ -378,11 +416,11 @@ export async function expandWorldTemplate({
0,
);
console.log(
- `🌍 Universe Builder expansion complete — runId=${runId} ${totalVariations} variations, ${compositeSheets.length} composite sheets, bible=${logline ? "yes" : "no"} (${perCat})`,
+ `🌍 Universe Builder expansion complete — runId=${runId} ${totalVariations} variations, ${compositeSheets.length} composite sheets, canon=${characters.length}/${settings.length}/${objects.length} (chars/places/objs), bible=${logline ? "yes" : "no"} (${perCat})`,
);
- if (totalVariations === 0 && compositeSheets.length === 0) {
+ if (totalVariations === 0 && compositeSheets.length === 0 && characters.length === 0 && settings.length === 0 && objects.length === 0) {
console.warn(
- `⚠️ Universe Builder expansion produced 0 variations — inspect data/runs/${runId}/output.txt for the raw LLM response`,
+ `⚠️ Universe Builder expansion produced 0 variations + 0 canon — inspect data/runs/${runId}/output.txt for the raw LLM response`,
);
}
@@ -393,6 +431,9 @@ export async function expandWorldTemplate({
influences: influencesOut,
categories,
compositeSheets,
+ characters,
+ settings,
+ objects,
llm: { provider: provider.id, model: selectedModel || null },
};
}
@@ -550,6 +591,7 @@ export const __testing = {
extractVariationsJson,
normalizeCategories,
normalizeCompositeSheets,
+ normalizeCanonArray,
buildExpansionPrompt,
buildCategoryGeneratePrompt,
};
diff --git a/server/services/universeBuilderExpand.test.js b/server/services/universeBuilderExpand.test.js
index d3918bbe7e..8575bb87b7 100644
--- a/server/services/universeBuilderExpand.test.js
+++ b/server/services/universeBuilderExpand.test.js
@@ -6,6 +6,7 @@ const {
extractJson,
normalizeCategories,
normalizeCompositeSheets,
+ normalizeCanonArray,
buildExpansionPrompt,
} = __testing;
// Anchor the legacy assertions on the static body of the prompt — the only
@@ -288,6 +289,55 @@ describe("universeBuilderExpand.normalizeCompositeSheets", () => {
});
});
+describe("universeBuilderExpand.normalizeCanonArray", () => {
+ it("returns [] for non-array input", () => {
+ expect(normalizeCanonArray(null, "character")).toEqual([]);
+ expect(normalizeCanonArray(undefined, "character")).toEqual([]);
+ expect(normalizeCanonArray("not an array", "character")).toEqual([]);
+ expect(normalizeCanonArray({}, "character")).toEqual([]);
+ });
+
+ it("sanitizes a character entry to the bible shape (id, timestamps, physicalDescription)", () => {
+ const out = normalizeCanonArray(
+ [{ name: "Ash", physicalDescription: "young survivor with iron rebar" }],
+ "character",
+ );
+ expect(out).toHaveLength(1);
+ expect(out[0].name).toBe("Ash");
+ expect(out[0].physicalDescription).toBe("young survivor with iron rebar");
+ expect(out[0].id).toBeTruthy();
+ expect(out[0].createdAt).toBeTruthy();
+ });
+
+ it("sanitizes a setting entry, requiring at least one identifier (name OR slugline)", () => {
+ const out = normalizeCanonArray(
+ [
+ { name: "Foundry City", description: "vast iron metropolis", palette: "rust + brass" },
+ { slugline: "INT. FOUNDRY CITY — DAY" },
+ { description: "no name no slugline — dropped" },
+ ],
+ "setting",
+ );
+ expect(out).toHaveLength(2);
+ expect(out[0].name).toBe("Foundry City");
+ expect(out[0].palette).toBe("rust + brass");
+ expect(out[1].slugline).toBe("INT. FOUNDRY CITY — DAY");
+ });
+
+ it("sanitizes an object entry, requiring a name", () => {
+ const out = normalizeCanonArray(
+ [
+ { name: "The Tongue", description: "an artifact that absorbs language", significance: "central MacGuffin" },
+ { description: "nameless — dropped" },
+ ],
+ "object",
+ );
+ expect(out).toHaveLength(1);
+ expect(out[0].name).toBe("The Tongue");
+ expect(out[0].significance).toBe("central MacGuffin");
+ });
+});
+
describe("universeBuilderExpand.EXPANSION_PROMPT", () => {
it("allows dynamic universe-building buckets and reference-sheet domains", () => {
expect(EXPANSION_PROMPT).toContain("Add, remove, or rename buckets");
@@ -317,6 +367,31 @@ describe("universeBuilderExpand.EXPANSION_PROMPT", () => {
expect(EXPANSION_PROMPT).toContain('"avoid"');
});
+ it("asks the LLM to emit canon arrays (characters / settings / objects) with rich metadata", () => {
+ // Phase B contract: canon arrays are first-class outputs of the expand
+ // call. The client merges them into universe.characters[]/.settings[]/.objects[]
+ // and the redesigned UI surfaces them under their canon trunks. If this
+ // assertion fails, also verify normalizeCanonArray + expandWorldTemplate
+ // still surface the returned values in the response payload.
+ expect(EXPANSION_PROMPT).toContain("characters:");
+ expect(EXPANSION_PROMPT).toContain("physicalDescription");
+ expect(EXPANSION_PROMPT).toContain("settings:");
+ expect(EXPANSION_PROMPT).toContain("slugline");
+ expect(EXPANSION_PROMPT).toContain("recurringDetails");
+ expect(EXPANSION_PROMPT).toContain("objects:");
+ expect(EXPANSION_PROMPT).toContain("significance");
+ });
+
+ it("teaches the LLM to tag each category with a `kind` so it lands under the right canon trunk", () => {
+ // Without this, post-Phase-A UIs that group categories by kind put every
+ // new bucket under 'other' until the user hand-sorts.
+ expect(EXPANSION_PROMPT).toContain('"kind"');
+ expect(EXPANSION_PROMPT).toContain('"characters"');
+ expect(EXPANSION_PROMPT).toContain('"settings"');
+ expect(EXPANSION_PROMPT).toContain('"objects"');
+ expect(EXPANSION_PROMPT).toContain('"other"');
+ });
+
it("omits the Influences input section when no influences are provided", () => {
const out = buildExpansionPrompt({ starterPrompt: "seed" });
expect(out).not.toContain("# Influences");