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

refactor([extract-mergeexpandintodraft-draft-result-from]): extract mergeExpandIntoDraft pure helper

[._.]/ Adam Eivy8bb4fecc5cac
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 04f2a71fbe..c7f7aa943e 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -60,3 +60,9 @@ grep -i "what you want to do" client/src/lib/README.md
| `unsorted.js` | Synthetic "Unsorted" collection from media not filed in any real collection. |
| `upsertByIdPrepend.js` | Newest-first upsert into an id-keyed list. |
| `voiceLabel.js` | `formatVoiceLabel(v, engine?)` — display label for a TTS voice record. Engine-specific formatters plug into a lookup table; new engines extend that map. |
+
+## Page-scoped pure helpers
+
+| Module | Purpose |
+|---|---|
+| `universeBuilderExpand.js` | `mergeExpandIntoDraft(draft, result)` — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with `kind` precedence, canon dedupe by name/slugline/alias). Also exports `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` for callers that need the building blocks (per-category Generate, save-time refetch+merge). |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index b16de47734..68e3aebf33 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -31,3 +31,6 @@ export * from './mediaNavigation.js';
export * from './unsorted.js';
export * from './upsertByIdPrepend.js';
export * from './voiceLabel.js';
+
+// === Page-scoped pure helpers ===
+export * from './universeBuilderExpand.js';
diff --git a/client/src/lib/universeBuilderExpand.js b/client/src/lib/universeBuilderExpand.js
new file mode 100644
index 0000000000..7e8c759464
--- /dev/null
+++ b/client/src/lib/universeBuilderExpand.js
@@ -0,0 +1,296 @@
+// Pure merge: take a Universe-Builder draft + an LLM expand-API result and
+// produce the next draft, alongside metadata the I/O shell in
+// `pages/UniverseBuilder.jsx#handleExpand` needs to drive toasts, auto-save,
+// and the pending-canon-additions ledger.
+//
+// Splitting the merge out lets us unit-test the lock/precedence/dedupe rules
+// without standing up the whole component, and shrinks `handleExpand` to its
+// I/O concerns (validation, API call, setDraft, auto-save, toast).
+//
+// Inputs:
+// - draft: the live builder draft (locked map, categories, sheets, canon, …)
+// - result: the LLM expand-API payload
+//
+// Output:
+// {
+// expandedDraft, // the next draft to put into React state
+// addedCanonCount, // NEW canon entries this expand contributed
+// pendingAdditions, // { characters, places, objects } — net-new only
+// lockedKeys, // string[] for the "preserved N locked fields" log line
+// }
+//
+// Lock semantics:
+// - For scalar fields in WORLD_LOCKABLE_FIELDS, locked → keep draft value;
+// unlocked → take the LLM value unless the LLM omitted (null/undefined).
+// A returned empty string IS applied — it's an intentional clear.
+// - Variations/sheets aren't lock-scoped, but per-item `locked: true` rows
+// are preserved and merged ahead of LLM output.
+// - Canon arrays merge by name/slugline/alias collision (existing wins).
+import { mergeInfluencesWithLocks } from '../services/api';
+import { normalizeSlugline } from './scenePrompt';
+
+// Match server's BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX so the client doesn't
+// optimistically display + count entries the server will silently truncate
+// at sanitize time. Without this cap, the post-expand toast can claim
+// "+12 canon entries" while the server-saved record only kept some of them.
+export const CLIENT_CANON_MAX = 200;
+
+// Merge two variation arrays under a single category bucket. Locked rows
+// (already filtered upstream into `existing`) come first; LLM-supplied
+// freshrows go second; dedup is label-keyed (case-insensitive). Rows missing a
+// `label` (malformed LLM payloads) are dropped from both sides — keeping them
+// in `merged` while excluding from the dedup Set would let a fresh row with
+// the same missing label silently duplicate.
+export const mergeVariations = (existing, fresh) => {
+ const merged = [];
+ const seen = new Set();
+ for (const v of [...(existing || []), ...(fresh || [])]) {
+ const key = v?.label?.toLowerCase();
+ if (!key || seen.has(key)) continue;
+ seen.add(key);
+ merged.push(v);
+ }
+ 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). Mirrors the
+// server-side dedupe in backfillCanonFromCategories + storyBible's
+// MERGE_CONFIG (`storyBible.js` keyFields).
+//
+// Identity rules are kind-aware to match the server's MERGE_CONFIG:
+// - characters/objects → `normalizeBibleName` (trim + lowercase) on `name`
+// AND `aliases[]`. Without aliases, an existing
+// character "Ashley" with alias "Ash" would not
+// collide with an LLM-returned "Ash", producing a
+// duplicate canon entry the user has to merge by hand.
+// - places → `normalizeSlugline` for BOTH `slugline` AND `name`
+// (`storyBible.js` MERGE_CONFIG.place.keyFields).
+// Without this, sluglines that differ only in dash
+// style or punctuation ("INT. FOUNDRY CITY — DAY"
+// vs "INT FOUNDRY CITY - DAY") would land as two
+// separate place-canon entries, and `Foundry-City`
+// vs `Foundry City` would duplicate by name even
+// though every downstream lookup treats them as one.
+export const mergeCanonByName = (existing, fresh, kind = 'character') => {
+ // 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 isPlace = kind === 'place';
+ const normName = isPlace
+ ? (s) => (typeof s === 'string' ? normalizeSlugline(s) : '')
+ : (s) => (typeof s === 'string' ? s.trim().toLowerCase() : '');
+ const normSlug = (s) => (typeof s === 'string' ? normalizeSlugline(s) : '');
+ // Aliases participate in identity for character/object only — places use
+ // slugline collision instead (the server's MERGE_CONFIG.place has no
+ // aliases field).
+ const aliasKeys = (entry) => {
+ if (isPlace || !Array.isArray(entry?.aliases)) return [];
+ return entry.aliases.map(normName).filter(Boolean);
+ };
+ const seen = new Set();
+ for (const e of existing || []) {
+ if (e?.name) seen.add(normName(e.name));
+ if (e?.slugline) seen.add(normSlug(e.slugline));
+ for (const k of aliasKeys(e)) seen.add(k);
+ }
+ const merged = [...(existing || [])];
+ for (const e of fresh) {
+ const nameKey = normName(e?.name);
+ const sluglineKey = normSlug(e?.slugline);
+ const aliasMatches = aliasKeys(e);
+ const collides = (nameKey && seen.has(nameKey))
+ || (sluglineKey && seen.has(sluglineKey))
+ || aliasMatches.some((k) => seen.has(k));
+ // On collision, still register every identity key the fresh entry
+ // carried — so a *later* fresh entry with overlapping aliases/sluglines
+ // is recognized as a within-batch duplicate too. Without this, fresh
+ // entry A (collides on alias) gets skipped silently and fresh entry B
+ // (uses A's primary name) slips in as a duplicate of the existing record.
+ if (nameKey) seen.add(nameKey);
+ if (sluglineKey) seen.add(sluglineKey);
+ for (const k of aliasMatches) seen.add(k);
+ if (collides) continue;
+ if (merged.length >= CLIENT_CANON_MAX) break;
+ merged.push(e);
+ }
+ return merged;
+};
+
+// Compute the net-new canon entries between `existing` and `merged` (i.e.
+// the rows the LLM contributed this round). Identity matches mergeCanonByName
+// for character/object (name + aliases); places use slugline. Used by the
+// pending-canon-additions ledger so the save path can re-merge only the net
+// new entries against a freshly-refetched server canon (concurrent edit
+// safety).
+const computeCanonAdditions = (existing, merged, kind = 'character') => {
+ const isPlace = kind === 'place';
+ const normName = isPlace
+ ? (s) => (typeof s === 'string' ? normalizeSlugline(s) : '')
+ : (s) => (typeof s === 'string' ? s.trim().toLowerCase() : '');
+ const normSlug = (s) => (typeof s === 'string' ? normalizeSlugline(s) : '');
+ const existingNames = new Set(
+ (existing || []).map((e) => normName(e?.name)).filter(Boolean),
+ );
+ const existingSluglines = new Set(
+ (existing || []).map((e) => normSlug(e?.slugline)).filter(Boolean),
+ );
+ return (merged || []).filter((e) => {
+ const n = normName(e?.name);
+ const s = normSlug(e?.slugline);
+ return !(n && existingNames.has(n)) && !(s && existingSluglines.has(s));
+ });
+};
+
+// Categories ship with a `kind` that pins the bucket to a canon trunk
+// (`characters`/`places`/`objects`/`other`). Precedence:
+// - existing non-'other' draft kind (user curated it to a specific trunk)
+// - LLM-returned kind for this expand round (fresh classification)
+// - existing 'other' draft kind (Phase-B default for custom buckets)
+// - undefined (server's sanitizeCategory falls back to default-map / 'other')
+// Allowing a fresh LLM kind to supersede an existing 'other' is intentional:
+// pre-Phase-B "factions" buckets saved as `other` can be promoted to
+// `characters` by a re-expand without requiring the user to manually change
+// the trunk. User-curated non-`other` kinds (e.g. `places`) are preserved.
+const resolveCategoryKind = (existingKind, freshKind) => {
+ if (existingKind && existingKind !== 'other') return existingKind;
+ return freshKind || existingKind;
+};
+
+const mergeCategoriesWithLocks = (draftCategories, llmCategories, preservedVariations) => {
+ const mergedCategories = {};
+ const allCatKeys = new Set([
+ ...Object.keys(preservedVariations),
+ ...Object.keys(llmCategories),
+ ]);
+ for (const cat of allCatKeys) {
+ const locked = preservedVariations[cat] || [];
+ const fresh = (llmCategories[cat]?.variations || []);
+ const kind = resolveCategoryKind(draftCategories?.[cat]?.kind, llmCategories[cat]?.kind);
+ mergedCategories[cat] = {
+ ...(kind ? { kind } : {}),
+ variations: mergeVariations(locked, fresh),
+ };
+ }
+ return mergedCategories;
+};
+
+// Composite-sheet merge follows the same locked-first + dedupe-by-label pattern
+// as variations. Labels are case-insensitive; sheets without a label are dropped
+// (mirrors mergeVariations' missing-key handling).
+const mergeCompositeSheets = (preservedSheets, llmSheets) => {
+ const seen = new Set();
+ const out = [];
+ for (const s of preservedSheets || []) {
+ const key = s?.label?.toLowerCase();
+ if (!key || seen.has(key)) continue;
+ seen.add(key);
+ out.push(s);
+ }
+ for (const s of llmSheets || []) {
+ const key = s?.label?.toLowerCase();
+ if (!key || seen.has(key)) continue;
+ seen.add(key);
+ out.push(s);
+ }
+ return out;
+};
+
+// Distinguish "LLM omitted the field" (null/undefined → keep draft) from "LLM
+// returned empty string" (a legitimate "" — the user's `||` would silently
+// restore a stale value they wanted gone).
+const pickLockableScalar = (key, locks, draft, llmValue) => {
+ if (locks[key]) return draft[key];
+ return llmValue == null ? draft[key] : llmValue;
+};
+
+// Pull the per-item-locked variations + composite sheets out of a draft so
+// they can both (1) ride along with the expand API request (server-side
+// prompt-builder uses them to tell the LLM not to regenerate locked items)
+// AND (2) seed mergeExpandIntoDraft's pre-merge state on the way back in.
+// Single source so the two surfaces can't drift.
+export const extractPreservedFromDraft = (draft) => {
+ const preservedVariations = {};
+ for (const [cat, bucket] of Object.entries(draft?.categories || {})) {
+ const locked = (bucket?.variations || []).filter((v) => v?.locked === true);
+ if (locked.length) preservedVariations[cat] = locked;
+ }
+ const preservedCompositeSheets = (draft?.compositeSheets || []).filter((s) => s?.locked === true);
+ return { preservedVariations, preservedCompositeSheets };
+};
+
+export const mergeExpandIntoDraft = (draft, result, opts = {}) => {
+ // Caller can pass a pre-baked ensureDraftCategories so the helper stays
+ // free of WORLD_CATEGORIES knowledge (which lives in pages/UniverseBuilder.jsx).
+ const ensureCategories = opts.ensureDraftCategories || ((c) => c || {});
+ const locks = draft.locked || {};
+
+ const { preservedVariations, preservedCompositeSheets } = extractPreservedFromDraft(draft);
+
+ const refinedInfluences = mergeInfluencesWithLocks(locks, result.influences, draft.influences);
+ const mergedCategories = mergeCategoriesWithLocks(
+ draft.categories || {},
+ result.categories || {},
+ preservedVariations,
+ );
+ const mergedSheets = mergeCompositeSheets(preservedCompositeSheets, result.compositeSheets);
+
+ // 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, kind) => mergeCanonByName(
+ draft[key] || [],
+ Array.isArray(result[key]) ? result[key] : [],
+ kind,
+ );
+ const mergedCharacters = pickCanon('characters', 'character');
+ const mergedPlaces = pickCanon('places', 'place');
+ const mergedObjects = pickCanon('objects', 'object');
+
+ // Count NEW canon entries this expand added (post-merge minus pre-existing).
+ // Used by the toast so a re-expand on a populated universe doesn't claim
+ // credit for entries the user already authored. Existing entries always win
+ // on collision in mergeCanonByName, so the delta is always non-negative.
+ const addedCanonCount =
+ (mergedCharacters.length - (draft.characters?.length || 0))
+ + (mergedPlaces.length - (draft.places?.length || 0))
+ + (mergedObjects.length - (draft.objects?.length || 0));
+
+ const expandedDraft = {
+ ...draft,
+ starterPrompt: pickLockableScalar('starterPrompt', locks, draft, result.starterPrompt),
+ logline: pickLockableScalar('logline', locks, draft, result.logline),
+ premise: pickLockableScalar('premise', locks, draft, result.premise),
+ styleNotes: pickLockableScalar('styleNotes', locks, draft, result.styleNotes),
+ influences: refinedInfluences,
+ categories: ensureCategories(mergedCategories),
+ compositeSheets: mergedSheets,
+ characters: mergedCharacters,
+ places: mergedPlaces,
+ objects: mergedObjects,
+ llm: result.llm || draft.llm,
+ };
+
+ // Net-new entries only — what the I/O shell stashes in the
+ // pending-canon-additions ledger so a manual save (or refetch-merge) can
+ // re-apply just the LLM contributions against the freshest server canon.
+ const pendingAdditions = addedCanonCount > 0 ? {
+ characters: computeCanonAdditions(draft.characters, mergedCharacters, 'character'),
+ places: computeCanonAdditions(draft.places, mergedPlaces, 'place'),
+ objects: computeCanonAdditions(draft.objects, mergedObjects, 'object'),
+ } : { characters: [], places: [], objects: [] };
+
+ const lockedKeys = Object.keys(locks).filter((k) => locks[k]);
+
+ return {
+ expandedDraft,
+ addedCanonCount,
+ pendingAdditions,
+ lockedKeys,
+ mergedCharacters,
+ mergedPlaces,
+ mergedObjects,
+ };
+};
diff --git a/client/src/lib/universeBuilderExpand.test.js b/client/src/lib/universeBuilderExpand.test.js
new file mode 100644
index 0000000000..c12dbafd76
--- /dev/null
+++ b/client/src/lib/universeBuilderExpand.test.js
@@ -0,0 +1,327 @@
+import { describe, it, expect } from 'vitest';
+import {
+ mergeVariations,
+ mergeCanonByName,
+ extractPreservedFromDraft,
+ mergeExpandIntoDraft,
+ CLIENT_CANON_MAX,
+} from './universeBuilderExpand.js';
+
+// Identity helper used in several lock/clear tests below.
+const draftFixture = (over = {}) => ({
+ starterPrompt: 'cyberpunk city',
+ logline: 'L1',
+ premise: 'P1',
+ styleNotes: 'S1',
+ influences: { embrace: ['noir'], avoid: ['high-fantasy'] },
+ locked: {},
+ categories: {},
+ compositeSheets: [],
+ characters: [],
+ places: [],
+ objects: [],
+ llm: { provider: 'codex', model: 'gpt-5' },
+ ...over,
+});
+
+describe('mergeVariations', () => {
+ it('dedupes case-insensitively by label, existing first', () => {
+ const out = mergeVariations(
+ [{ label: 'Existing One' }],
+ [{ label: 'existing one' }, { label: 'fresh' }],
+ );
+ expect(out.map((v) => v.label)).toEqual(['Existing One', 'fresh']);
+ });
+
+ it('drops rows missing a label from both sides (no silent dup)', () => {
+ const out = mergeVariations(
+ [{ label: 'a' }, { label: '' }],
+ [{ label: 'a' }, { label: undefined }, { label: 'b' }],
+ );
+ expect(out.map((v) => v.label)).toEqual(['a', 'b']);
+ });
+
+ it('handles null/undefined inputs', () => {
+ expect(mergeVariations(null, [{ label: 'x' }])).toEqual([{ label: 'x' }]);
+ expect(mergeVariations([{ label: 'x' }], null)).toEqual([{ label: 'x' }]);
+ expect(mergeVariations(null, null)).toEqual([]);
+ });
+});
+
+describe('mergeCanonByName', () => {
+ it('returns existing unchanged when fresh is empty (preserves reference)', () => {
+ const existing = [{ name: 'Ashley' }];
+ expect(mergeCanonByName(existing, [], 'character')).toBe(existing);
+ expect(mergeCanonByName(existing, null, 'character')).toBe(existing);
+ });
+
+ it('character: trim+lowercase name collision; existing wins', () => {
+ const out = mergeCanonByName(
+ [{ name: 'Ashley', role: 'protagonist' }],
+ [{ name: ' ashley ', role: 'antagonist' }, { name: 'Bobby' }],
+ 'character',
+ );
+ expect(out).toHaveLength(2);
+ expect(out[0]).toEqual({ name: 'Ashley', role: 'protagonist' });
+ expect(out[1].name).toBe('Bobby');
+ });
+
+ it('character: alias matches existing primary name', () => {
+ const out = mergeCanonByName(
+ [{ name: 'Ashley', aliases: ['Ash'] }],
+ [{ name: 'Ash', role: 'should not duplicate' }],
+ 'character',
+ );
+ expect(out).toHaveLength(1);
+ expect(out[0].name).toBe('Ashley');
+ });
+
+ it('character: fresh entry registers its keys even on collision (within-batch dedupe)', () => {
+ const out = mergeCanonByName(
+ [{ name: 'Ashley', aliases: ['Ash'] }],
+ [
+ { name: 'Mr X', aliases: ['Ash'] }, // collides via alias with existing → skip
+ { name: 'Ash', role: 'would otherwise slip in' }, // collides with first fresh's claimed alias
+ ],
+ 'character',
+ );
+ expect(out).toHaveLength(1);
+ expect(out[0].name).toBe('Ashley');
+ });
+
+ it('place: slugline collision wins even with different name punctuation', () => {
+ const out = mergeCanonByName(
+ [{ name: 'Foundry City', slugline: 'INT. FOUNDRY CITY - DAY' }],
+ [
+ { name: 'Foundry-City', slugline: 'INT. FOUNDRY CITY — DAY' },
+ { name: 'Other Place', slugline: 'EXT. WHARF - NIGHT' },
+ ],
+ 'place',
+ );
+ expect(out).toHaveLength(2);
+ expect(out[0].slugline).toBe('INT. FOUNDRY CITY - DAY');
+ expect(out[1].name).toBe('Other Place');
+ });
+
+ it('place: aliases NOT used as identity key', () => {
+ const out = mergeCanonByName(
+ [{ name: 'Foundry City', aliases: ['Foundry'] }],
+ [{ name: 'Foundry', slugline: 'INT. FOUNDRY - DAY' }],
+ 'place',
+ );
+ expect(out).toHaveLength(2);
+ });
+
+ it('caps merged output at CLIENT_CANON_MAX (mirror of server BIBLE_LIMITS)', () => {
+ const existing = Array.from({ length: CLIENT_CANON_MAX - 1 }, (_, i) => ({ name: `e${i}` }));
+ const fresh = Array.from({ length: 5 }, (_, i) => ({ name: `f${i}` }));
+ const out = mergeCanonByName(existing, fresh, 'character');
+ expect(out).toHaveLength(CLIENT_CANON_MAX);
+ });
+});
+
+describe('extractPreservedFromDraft', () => {
+ it('returns only items with locked: true', () => {
+ const { preservedVariations, preservedCompositeSheets } = extractPreservedFromDraft({
+ categories: {
+ weapons: { variations: [{ label: 'A', locked: true }, { label: 'B' }] },
+ food: { variations: [{ label: 'C' }] },
+ },
+ compositeSheets: [
+ { label: 'sheet1', locked: true },
+ { label: 'sheet2' },
+ ],
+ });
+ expect(preservedVariations).toEqual({ weapons: [{ label: 'A', locked: true }] });
+ expect(preservedCompositeSheets).toEqual([{ label: 'sheet1', locked: true }]);
+ });
+
+ it('handles missing categories/compositeSheets', () => {
+ expect(extractPreservedFromDraft({})).toEqual({
+ preservedVariations: {},
+ preservedCompositeSheets: [],
+ });
+ expect(extractPreservedFromDraft(null)).toEqual({
+ preservedVariations: {},
+ preservedCompositeSheets: [],
+ });
+ });
+});
+
+describe('mergeExpandIntoDraft', () => {
+ it('locked scalar field keeps draft value; unlocked takes LLM value', () => {
+ const draft = draftFixture({ locked: { logline: true } });
+ const { expandedDraft } = mergeExpandIntoDraft(draft, {
+ logline: 'LLM-overridden',
+ premise: 'LLM-premise',
+ });
+ expect(expandedDraft.logline).toBe('L1'); // locked → draft wins
+ expect(expandedDraft.premise).toBe('LLM-premise'); // unlocked → LLM wins
+ });
+
+ it('unlocked + LLM null/undefined → keep draft (absent semantics)', () => {
+ const draft = draftFixture();
+ const { expandedDraft } = mergeExpandIntoDraft(draft, {
+ logline: null,
+ premise: undefined,
+ styleNotes: 'kept',
+ });
+ expect(expandedDraft.logline).toBe('L1');
+ expect(expandedDraft.premise).toBe('P1');
+ expect(expandedDraft.styleNotes).toBe('kept');
+ });
+
+ it('unlocked + LLM empty string → applies the clear', () => {
+ const draft = draftFixture();
+ const { expandedDraft } = mergeExpandIntoDraft(draft, {
+ logline: '',
+ premise: 'still there',
+ });
+ expect(expandedDraft.logline).toBe('');
+ expect(expandedDraft.premise).toBe('still there');
+ });
+
+ it('locked variations survive a regeneration; unlocked re-merged with fresh', () => {
+ const draft = draftFixture({
+ categories: {
+ weapons: { kind: 'object', variations: [{ label: 'sword', locked: true }, { label: 'old-bow' }] },
+ },
+ });
+ const { expandedDraft } = mergeExpandIntoDraft(draft, {
+ categories: {
+ weapons: { kind: 'object', variations: [{ label: 'bow' }, { label: 'sword' /* dup, drops */ }] },
+ },
+ });
+ // 'sword' (locked) keeps its slot at the top; 'bow' added; LLM duplicate dropped.
+ expect(expandedDraft.categories.weapons.variations.map((v) => v.label))
+ .toEqual(['sword', 'bow']);
+ expect(expandedDraft.categories.weapons.kind).toBe('object');
+ });
+
+ it('category kind precedence: user-curated non-other survives LLM reclassification', () => {
+ const draft = draftFixture({
+ categories: { factions: { kind: 'characters', variations: [{ label: 'X', locked: true }] } },
+ });
+ const { expandedDraft } = mergeExpandIntoDraft(draft, {
+ categories: { factions: { kind: 'object', variations: [] } },
+ });
+ expect(expandedDraft.categories.factions.kind).toBe('characters');
+ });
+
+ it('category kind precedence: existing "other" can be upgraded by fresh LLM kind', () => {
+ const draft = draftFixture({
+ categories: { factions: { kind: 'other', variations: [{ label: 'X', locked: true }] } },
+ });
+ const { expandedDraft } = mergeExpandIntoDraft(draft, {
+ categories: { factions: { kind: 'characters', variations: [] } },
+ });
+ expect(expandedDraft.categories.factions.kind).toBe('characters');
+ });
+
+ it('locked composite sheets survive; LLM dups dropped by case-insensitive label', () => {
+ const draft = draftFixture({
+ compositeSheets: [
+ { label: 'cover', locked: true, body: 'draft' },
+ { label: 'old', body: 'unlocked draft' },
+ ],
+ });
+ const { expandedDraft } = mergeExpandIntoDraft(draft, {
+ compositeSheets: [
+ { label: 'COVER', body: 'LLM duplicate' },
+ { label: 'splash', body: 'LLM new' },
+ ],
+ });
+ // Locked sheet keeps its top slot + draft body; unlocked draft sheet is
+ // dropped (composite-sheet merge is locks-only, not free-form preservation);
+ // LLM "splash" is appended.
+ expect(expandedDraft.compositeSheets.map((s) => s.label)).toEqual(['cover', 'splash']);
+ expect(expandedDraft.compositeSheets[0].body).toBe('draft');
+ });
+
+ it('canon merge: existing wins on name collision; addedCanonCount reflects net-new only', () => {
+ const draft = draftFixture({
+ characters: [{ name: 'Ashley', role: 'protagonist' }],
+ });
+ const { expandedDraft, addedCanonCount, mergedCharacters } = mergeExpandIntoDraft(draft, {
+ characters: [
+ { name: 'ashley', role: 'antagonist' /* collides, dropped */ },
+ { name: 'Bobby' /* new */ },
+ ],
+ places: [{ name: 'Foundry City', slugline: 'INT. FOUNDRY - DAY' }],
+ });
+ expect(mergedCharacters).toHaveLength(2);
+ expect(expandedDraft.characters[0].role).toBe('protagonist'); // existing wins
+ expect(addedCanonCount).toBe(2); // 1 char (Bobby) + 1 place (Foundry City)
+ });
+
+ it('pendingAdditions: only net-new entries, partitioned by trunk', () => {
+ const draft = draftFixture({
+ characters: [{ name: 'Ashley' }],
+ places: [{ name: 'Wharf', slugline: 'EXT. WHARF - NIGHT' }],
+ });
+ const { pendingAdditions } = mergeExpandIntoDraft(draft, {
+ characters: [{ name: 'Ashley' }, { name: 'Bobby' }],
+ places: [{ name: 'New Place', slugline: 'INT. NEW - DAY' }],
+ objects: [{ name: 'Sword' }],
+ });
+ expect(pendingAdditions.characters.map((c) => c.name)).toEqual(['Bobby']);
+ expect(pendingAdditions.places.map((p) => p.name)).toEqual(['New Place']);
+ expect(pendingAdditions.objects.map((o) => o.name)).toEqual(['Sword']);
+ });
+
+ it('pendingAdditions empty when nothing net-new', () => {
+ const draft = draftFixture({ characters: [{ name: 'Ashley' }] });
+ const { addedCanonCount, pendingAdditions } = mergeExpandIntoDraft(draft, {
+ characters: [{ name: 'ashley' }],
+ });
+ expect(addedCanonCount).toBe(0);
+ expect(pendingAdditions).toEqual({ characters: [], places: [], objects: [] });
+ });
+
+ it('lockedKeys lists only entries where locked[k] is truthy', () => {
+ const draft = draftFixture({
+ locked: { logline: true, premise: false, styleNotes: true },
+ });
+ const { lockedKeys } = mergeExpandIntoDraft(draft, {});
+ expect(new Set(lockedKeys)).toEqual(new Set(['logline', 'styleNotes']));
+ });
+
+ it('influences locks: locked sublist keeps draft, unlocked accepts LLM clear', () => {
+ const draft = draftFixture({
+ locked: { influencesEmbrace: true },
+ influences: { embrace: ['noir', 'cyberpunk'], avoid: ['fantasy'] },
+ });
+ const { expandedDraft } = mergeExpandIntoDraft(draft, {
+ influences: { embrace: ['REPLACED'], avoid: [] /* explicit clear */ },
+ });
+ expect(expandedDraft.influences.embrace).toEqual(['noir', 'cyberpunk']);
+ expect(expandedDraft.influences.avoid).toEqual([]);
+ });
+
+ it('llm fallback: missing llm in result preserves draft llm', () => {
+ const draft = draftFixture({ llm: { provider: 'x', model: 'y' } });
+ const a = mergeExpandIntoDraft(draft, {}).expandedDraft.llm;
+ const b = mergeExpandIntoDraft(draft, { llm: { provider: 'new', model: 'z' } }).expandedDraft.llm;
+ expect(a).toEqual({ provider: 'x', model: 'y' });
+ expect(b).toEqual({ provider: 'new', model: 'z' });
+ });
+
+ it('result.{characters,places,objects} non-array → treated as no canon', () => {
+ const draft = draftFixture({ characters: [{ name: 'Ashley' }] });
+ const { expandedDraft, addedCanonCount } = mergeExpandIntoDraft(draft, {
+ characters: 'not-an-array',
+ places: null,
+ });
+ expect(expandedDraft.characters).toEqual([{ name: 'Ashley' }]);
+ expect(addedCanonCount).toBe(0);
+ });
+
+ it('ensureDraftCategories opts wraps the merged categories when supplied', () => {
+ const ensureDraftCategories = (cats) => ({ defaultBucket: { variations: [] }, ...cats });
+ const draft = draftFixture();
+ const { expandedDraft } = mergeExpandIntoDraft(draft, {
+ categories: { weapons: { variations: [{ label: 'sword' }] } },
+ }, { ensureDraftCategories });
+ expect(Object.keys(expandedDraft.categories).sort()).toEqual(['defaultBucket', 'weapons']);
+ });
+});
diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsx
index 722f905d98..09ae088da7 100644
--- a/client/src/pages/UniverseBuilder.jsx
+++ b/client/src/pages/UniverseBuilder.jsx
@@ -22,7 +22,7 @@ import {
renderWorld, listWorldRuns, getProviders, refineWorldPrompts, WORLD_CATEGORIES,
WORLD_CATEGORY_KEY_MAX, COMPOSITE_PROMPT_MAX, WORLD_LOGLINE_MAX,
WORLD_PREMISE_MAX, WORLD_STYLE_NOTES_MAX, WORLD_LOCKABLE_FIELDS,
- ensureInfluences, isInfluenceLockField, mergeInfluencesWithLocks,
+ ensureInfluences, isInfluenceLockField,
listImageModels, listLorasFull, getSettings,
} from '../services/api';
import useClickOutside from '../hooks/useClickOutside';
@@ -45,10 +45,12 @@ import { listImageGallery } from '../services/apiImageVideo';
import TabPills from '../components/ui/TabPills';
import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../lib/imageGenBackends';
import { PIPELINE_IMAGE_DEFAULTS, readPipelineImageSettings } from '../lib/pipelineImageDefaults';
-import { normalizeSlugline } from '../lib/scenePrompt';
import { hasCanonDescriptorContent, descriptorForCanonEntry } from '../lib/canonPrompt';
import { upsertByIdPrepend } from '../lib/upsertByIdPrepend';
import { BIBLE_LIMITS } from '../lib/bibleLimits';
+import {
+ mergeVariations, mergeCanonByName, mergeExpandIntoDraft, extractPreservedFromDraft,
+} from '../lib/universeBuilderExpand';
// Mirror of server-side appendEntryImageRef cap (most recent N wins). Used
// so optimistic on-completion appends produce the same final array shape
@@ -113,96 +115,6 @@ const normalizeCategoryKey = (raw) => (raw || '')
.replace(/_{2,}/g, '_')
.slice(0, WORLD_CATEGORY_KEY_MAX);
-// Merge `fresh` items after `existing`, case-insensitively deduping by label.
-// Used by both Expand (locked + LLM result) and per-category Generate (current
-// + LLM additions); pinned/existing entries keep their slot at the top.
-// Rows with a missing/non-string label (older universes pre-rename, partial
-// LLM payloads) are dropped from both sides — keeping them in `merged` while
-// excluding from the dedup Set would let a fresh row with the same missing
-// label silently duplicate.
-const mergeVariations = (existing, fresh) => {
- const merged = [];
- const seen = new Set();
- for (const v of [...(existing || []), ...(fresh || [])]) {
- const key = v?.label?.toLowerCase();
- if (!key || seen.has(key)) continue;
- seen.add(key);
- merged.push(v);
- }
- 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). Mirrors the
-// server-side dedupe in backfillCanonFromCategories + storyBible's
-// MERGE_CONFIG (`storyBible.js` keyFields).
-//
-// Identity rules are kind-aware to match the server's MERGE_CONFIG:
-// - characters/objects → `normalizeBibleName` (trim + lowercase) on `name`
-// AND `aliases[]`. Without aliases, an existing
-// character "Ashley" with alias "Ash" would not
-// collide with an LLM-returned "Ash", producing a
-// duplicate canon entry the user has to merge by hand.
-// - places → `normalizeSlugline` for BOTH `slugline` AND `name`
-// (`storyBible.js` MERGE_CONFIG.place.keyFields).
-// Without this, sluglines that differ only in dash
-// style or punctuation ("INT. FOUNDRY CITY — DAY"
-// vs "INT FOUNDRY CITY - DAY") would land as two
-// separate place-canon entries, and `Foundry-City`
-// vs `Foundry City` would duplicate by name even
-// though every downstream lookup treats them as one.
-// Match server's BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX so the client doesn't
-// optimistically display + count entries the server will silently truncate
-// at sanitize time. Without this cap, the post-expand toast can claim
-// "+12 canon entries" while the server-saved record only kept some of them.
-const CLIENT_CANON_MAX = 200;
-
-const mergeCanonByName = (existing, fresh, kind = 'character') => {
- // 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 isPlace = kind === 'place';
- const normName = isPlace
- ? (s) => (typeof s === 'string' ? normalizeSlugline(s) : '')
- : (s) => (typeof s === 'string' ? s.trim().toLowerCase() : '');
- const normSlug = (s) => (typeof s === 'string' ? normalizeSlugline(s) : '');
- // Aliases participate in identity for character/object only — places use
- // slugline collision instead (the server's MERGE_CONFIG.place has no
- // aliases field).
- const aliasKeys = (entry) => {
- if (isPlace || !Array.isArray(entry?.aliases)) return [];
- return entry.aliases.map(normName).filter(Boolean);
- };
- const seen = new Set();
- for (const e of existing || []) {
- if (e?.name) seen.add(normName(e.name));
- if (e?.slugline) seen.add(normSlug(e.slugline));
- for (const k of aliasKeys(e)) seen.add(k);
- }
- const merged = [...(existing || [])];
- for (const e of fresh) {
- const nameKey = normName(e?.name);
- const sluglineKey = normSlug(e?.slugline);
- const aliasMatches = aliasKeys(e);
- const collides = (nameKey && seen.has(nameKey))
- || (sluglineKey && seen.has(sluglineKey))
- || aliasMatches.some((k) => seen.has(k));
- // On collision, still register every identity key the fresh entry
- // carried — so a *later* fresh entry with overlapping aliases/sluglines
- // is recognized as a within-batch duplicate too. Without this, fresh
- // entry A (collides on alias) gets skipped silently and fresh entry B
- // (uses A's primary name) slips in as a duplicate of the existing record.
- if (nameKey) seen.add(nameKey);
- if (sluglineKey) seen.add(sluglineKey);
- for (const k of aliasMatches) seen.add(k);
- if (collides) continue;
- if (merged.length >= CLIENT_CANON_MAX) break;
- merged.push(e);
- }
- return merged;
-};
-
const humanizeCategory = (key) => CATEGORY_LABELS[key]
|| key.replace(/_/g, ' ').replace(/\b\w/g, (ch) => ch.toUpperCase());
@@ -1099,16 +1011,11 @@ export default function UniverseBuilder() {
toast.error('Add a starter prompt to expand');
return;
}
- // Extract per-item locks so the server can include them in the LLM
- // prompt (avoid duplicate generation) AND we can merge them back in
- // after the result returns. Only LOCKED entries are forwarded — the
+ // Extract per-item locks so the server can include them in the LLM prompt
+ // (avoid duplicate generation) AND mergeExpandIntoDraft can merge them back
+ // in after the result returns. Only LOCKED entries are forwarded — the
// unlocked items get fully replaced.
- const preservedVariations = {};
- for (const [cat, bucket] of Object.entries(draft.categories || {})) {
- const locked = (bucket?.variations || []).filter((v) => v?.locked === true);
- if (locked.length) preservedVariations[cat] = locked;
- }
- const preservedCompositeSheets = (draft.compositeSheets || []).filter((s) => s?.locked === true);
+ const { preservedVariations, preservedCompositeSheets } = extractPreservedFromDraft(draft);
setExpanding(true);
const result = await expandUniverse({
@@ -1127,102 +1034,9 @@ export default function UniverseBuilder() {
}).catch((e) => { toast.error(`Expansion failed: ${e.message}`); return null; });
setExpanding(false);
if (!result) return;
- // For each lockable field: pick the LLM's value when unlocked (falling
- // back to the draft if the LLM produced empty); pick the draft's value
- // verbatim when locked. Categories + compositeSheets aren't lockable
- // (the lock UI scopes to the bible/prompt scalars), so they always
- // come from the LLM. `starterPrompt` is normally untouched by expand
- // (the LLM doesn't return one), but if it ever did, lock honoring
- // protects the user's edits.
- const locks = draft.locked || {};
- // Distinguish "LLM omitted the field" (null/undefined → keep draft) from
- // "LLM returned empty string" (a legitimate "" — the user's `||` would
- // silently restore a stale value they wanted gone).
- const pick = (key, llmValue) => {
- if (locks[key]) return draft[key];
- return llmValue == null ? draft[key] : llmValue;
- };
- const refinedInfluences = mergeInfluencesWithLocks(locks, result.influences, draft.influences);
- const llmCategories = result.categories || {};
- const mergedCategories = {};
- const allCatKeys = new Set([
- ...Object.keys(preservedVariations),
- ...Object.keys(llmCategories),
- ]);
- for (const cat of allCatKeys) {
- const locked = preservedVariations[cat] || [];
- const fresh = (llmCategories[cat]?.variations || []);
- // Preserve the bucket's `kind` so the category-to-canon-trunk contract
- // survives the round-trip. Precedence:
- // - existing non-'other' draft kind (user curated it to a specific trunk)
- // - LLM-returned kind for this expand round (fresh classification)
- // - existing 'other' draft kind (Phase-B default for custom buckets)
- // - undefined (server's sanitizeCategory falls back to default-map / 'other')
- // Allowing a fresh LLM kind to supersede an existing 'other' is intentional:
- // pre-Phase-B "factions" buckets saved as `other` can be promoted to
- // `characters` by a re-expand without requiring the user to manually change
- // the trunk. User-curated non-`other` kinds (e.g. `places`) are preserved.
- const existingKind = draft.categories?.[cat]?.kind;
- const freshKind = llmCategories[cat]?.kind;
- const kind = (existingKind && existingKind !== 'other') ? existingKind : (freshKind || existingKind);
- mergedCategories[cat] = {
- ...(kind ? { kind } : {}),
- variations: mergeVariations(locked, fresh),
- };
- }
- // Composite sheets merge follows the same locked-first + dedupe pattern.
- const mergedSheets = (() => {
- const llmSheets = result.compositeSheets || [];
- const seen = new Set(preservedCompositeSheets.map((s) => s.label.toLowerCase()));
- const out = [...preservedCompositeSheets];
- for (const s of llmSheets) {
- const key = s.label?.toLowerCase();
- if (!key || seen.has(key)) continue;
- seen.add(key);
- out.push(s);
- }
- return out;
- })();
-
- // 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.
- //
- // `kind` is passed so places use `normalizeSlugline` for both `name` and
- // `slugline` (matching the server's MERGE_CONFIG.place.keyFields) —
- // dash/punct-variant identifiers collide instead of duplicating.
- const pickCanon = (key, kind) => mergeCanonByName(
- draft[key] || [],
- Array.isArray(result[key]) ? result[key] : [],
- kind,
- );
- const mergedCharacters = pickCanon('characters', 'character');
- const mergedPlaces = pickCanon('places', 'place');
- const mergedObjects = pickCanon('objects', 'object');
- // Count NEW canon entries this expand added (post-merge minus pre-existing).
- // Used by the toast so a re-expand on a populated universe doesn't claim
- // credit for entries the user already authored. Existing entries always win
- // on collision in mergeCanonByName, so the delta is always non-negative.
- const addedCanonCount =
- (mergedCharacters.length - (draft.characters?.length || 0))
- + (mergedPlaces.length - (draft.places?.length || 0))
- + (mergedObjects.length - (draft.objects?.length || 0));
-
- const expandedDraft = {
- ...draft,
- starterPrompt: pick('starterPrompt', result.starterPrompt),
- logline: pick('logline', result.logline),
- premise: pick('premise', result.premise),
- styleNotes: pick('styleNotes', result.styleNotes),
- influences: refinedInfluences,
- categories: ensureDraftCategories(mergedCategories),
- compositeSheets: mergedSheets,
- characters: mergedCharacters,
- places: mergedPlaces,
- objects: mergedObjects,
- llm: result.llm || draft.llm,
- };
+ const {
+ expandedDraft, addedCanonCount, pendingAdditions, lockedKeys,
+ } = mergeExpandIntoDraft(draft, result, { ensureDraftCategories });
setDraft(expandedDraft);
// Flag the merged-but-not-yet-persisted canon so a subsequent manual
// Save (if auto-save fails or is bypassed) includes the new entries.
@@ -1231,23 +1045,12 @@ export default function UniverseBuilder() {
// full stale draft.
if (addedCanonCount > 0) {
setCanonDirty(true);
- const computeAdditions = (existing, merged) => {
- const norm = (s) => (typeof s === 'string' ? s.trim().toLowerCase() : '');
- const existingNames = new Set((existing || []).map((e) => norm(e?.name)).filter(Boolean));
- const existingSluglines = new Set((existing || []).map((e) => norm(e?.slugline)).filter(Boolean));
- return (merged || []).filter((e) => {
- const n = norm(e?.name);
- const s = norm(e?.slugline);
- return !(n && existingNames.has(n)) && !(s && existingSluglines.has(s));
- });
- };
pendingCanonAdditionsRef.current = {
- characters: [...pendingCanonAdditionsRef.current.characters, ...computeAdditions(draft.characters, mergedCharacters)],
- places: [...pendingCanonAdditionsRef.current.places, ...computeAdditions(draft.places, mergedPlaces)],
- objects: [...pendingCanonAdditionsRef.current.objects, ...computeAdditions(draft.objects, mergedObjects)],
+ characters: [...pendingCanonAdditionsRef.current.characters, ...pendingAdditions.characters],
+ places: [...pendingCanonAdditionsRef.current.places, ...pendingAdditions.places],
+ objects: [...pendingCanonAdditionsRef.current.objects, ...pendingAdditions.objects],
};
}
- const lockedKeys = Object.keys(locks).filter((k) => locks[k]);
if (lockedKeys.length) {
console.log(`🔒 Universe Builder expand preserved ${lockedKeys.length} locked field(s): ${lockedKeys.join(', ')}`);
}