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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: Story Builder aesthetic step persists the full expansion via the shared merge (#9588)
[._.]/ Adam Eivyd17e6baa40ef
diff --git a/client/src/lib/universeBuilderExpand.js b/client/src/lib/universeBuilderExpand.jsindex ac6fdf8b0c..cfcf8b00a0 100644--- a/client/src/lib/universeBuilderExpand.js+++ b/client/src/lib/universeBuilderExpand.js@@ -1,303 +1,20 @@-// 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).-// Imports the influence-merge from the targeted apiUniverseBuilder module-// (NOT the global `services/api` barrel) — the helpers are pure functions-// that happen to be exported alongside HTTP wrappers, and tracing through-// the barrel pulls all ~40 service modules into this lib's dep graph,-// defeating the point of a `lib/` vs `services/` boundary.+// Re-export of the pure Universe-Builder expand merge in+// `server/lib/universeExpandMerge.js` — the one definition of the lock /+// preserve / dedupe rules, shared with the Story Builder's server path so the+// two cannot drift. Only the influence merge is client-specific: it comes from+// the targeted apiUniverseBuilder module (NOT the global `services/api` barrel,+// which would pull ~40 service modules into this lib's dep graph).import { mergeInfluencesWithLocks } from '../services/apiUniverseBuilder';-import { BIBLE_LIMITS } from './bibleLimits';-import { normalizeSlugline } from './scenePrompt';--// Aliased so the call site in mergeCanonByName reads naturally. Sourced from-// the BIBLE_LIMITS mirror 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 CANON_ENTRIES_CAP = BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX;--// 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 >= CANON_ENTRIES_CAP) 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: preserved (locked) sheets keep their slot at the top-// unconditionally — the upstream invariant (only `locked: true` rows reach-// here) means a missing label is a bug elsewhere, not a row to silently drop.-// Their labels still seed the dedupe Set so a fresh LLM sheet with the same-// label is suppressed. Mirrors the pre-extraction handleExpand behavior-// byte-for-byte (a malformed preserved sheet with no `label` would have-// crashed the pre-refactor code on `.toLowerCase()` — keeping the same fault-// surface so this is a pure boundary move, not a behavior change).-const mergeCompositeSheets = (preservedSheets, llmSheets) => {- const preserved = preservedSheets || [];- const seen = new Set(preserved.map((s) => s.label.toLowerCase()));- const out = [...preserved];- 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,- };-};+import { mergeExpandIntoDraft as sharedMergeExpandIntoDraft } from '../../../server/lib/universeExpandMerge.js';++export {+ mergeVariations,+ mergeCanonByName,+ extractPreservedFromDraft,+} from '../../../server/lib/universeExpandMerge.js';++export const mergeExpandIntoDraft = (draft, result, opts = {}) => sharedMergeExpandIntoDraft(+ draft,+ result,+ { mergeInfluences: mergeInfluencesWithLocks, ...opts },+);diff --git a/server/lib/README.md b/server/lib/README.mdindex 8bce276f72..e6dae58867 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -194,6 +194,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `universeBibleLimits.js` | Universe bible field size limits shared between server (sanitizer, pipeline) and client (form inputs). || `universeMarkdown.js` | `universeToMarkdown(record)` / `parseUniverseMarkdown(text)` for the Universe Builder's Markdown world-bible export and import, plus safe download filename helpers. || `universePromptRenderers.js` | Renderers that turn a universe's `categories` map + canon into prompt context, including the authored character-engine block and the shared story canon digest. |+| `universeExpandMerge.js` | Pure lock/preserve/dedupe merge of a Universe Builder expansion into a universe draft: `mergeExpandIntoDraft(draft, result, {mergeInfluences, ensureDraftCategories})`, `extractPreservedFromDraft`, `mergeVariations`, `mergeCanonByName` (existing wins; name/alias/slugline identity). The one definition shared by the Universe Builder client (`client/src/lib/universeBuilderExpand.js` re-exports it) and the Story Builder server step. || `universeVisualStyle.js` | The style a universe contributes to an IMAGE prompt: `buildVisualStyleClause(universe, {override, mode})` (curated `influences.embrace` tokens + a series `stylePromptOverride`, NEVER the free-text `styleNotes`, which is writing-stage direction), `universeStylePreset(universe, series)` (the `{prompt, negativePrompt}` preset `composeStyledPrompt` consumes — the one definition shared by the browser and the FableLoom visual-canon compiler, `client/src/lib/universeStylePreset.js` re-exports it), `universeAestheticLine` (the labeled variant canon sheet/LoRA renders lead with), `universeVisualStyleTokens`, `joinInfluenceList` (thin trim+join over one chip-token list, re-exported by `client/src/lib/joinInfluenceList.js` and `server/services/universeBuilder/compile.js`), `splitPromptTokens`, `stripStyleClause(text, clause)` (removes the copy the browser already prefixed, so the compiler keeps the LEADING one — matched on the joined clause so a token with its own punctuation like `M.C. Escher` still matches) and `mergeNegativePromptTokens` (token-level union of comma-joined negatives). || `writersRoomPresets.js` | Writers Room enums (WORK_KINDS, WORK_STATUSES, ANALYSIS_KINDS). || `writersRoomStylePresets.js` | Curated style presets for storyboards + universe. |diff --git a/server/lib/index.js b/server/lib/index.jsindex f1a52ad605..39ae031dde 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -161,6 +161,7 @@ export * from './universeBibleCompleteness.js';export * from './universeBibleLimits.js';export * from './universeMarkdown.js';export * from './universePromptRenderers.js';+export * from './universeExpandMerge.js';export * from './universeVisualStyle.js';export * from './writersRoomPresets.js';export * from './writersRoomStylePresets.js';diff --git a/server/lib/universeExpandMerge.js b/server/lib/universeExpandMerge.jsnew file mode 100644index 0000000000..d23f6026e9--- /dev/null+++ b/server/lib/universeExpandMerge.js@@ -0,0 +1,304 @@+// Shared by the Universe Builder client (client/src/lib/universeBuilderExpand.js+// re-exports it) and the Story Builder's server-side universeAesthetic step, so+// both honor one lock/preserve/dedupe contract. The influence merge is injected+// (opts.mergeInfluences) because each runtime owns its own copy.+//+// 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 { BIBLE_LIMITS } from './bibleLimits.js';+import { normalizeSlugline } from './scenePrompt.js';++// Aliased so the call site in mergeCanonByName reads naturally. Sourced from+// the BIBLE_LIMITS mirror 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 CANON_ENTRIES_CAP = BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX;++// 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 >= CANON_ENTRIES_CAP) 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: preserved (locked) sheets keep their slot at the top+// unconditionally — the upstream invariant (only `locked: true` rows reach+// here) means a missing label is a bug elsewhere, not a row to silently drop.+// Their labels still seed the dedupe Set so a fresh LLM sheet with the same+// label is suppressed. Mirrors the pre-extraction handleExpand behavior+// byte-for-byte (a malformed preserved sheet with no `label` would have+// crashed the pre-refactor code on `.toLowerCase()` — keeping the same fault+// surface so this is a pure boundary move, not a behavior change).+const mergeCompositeSheets = (preservedSheets, llmSheets) => {+ const preserved = preservedSheets || [];+ const seen = new Set(preserved.map((s) => s.label.toLowerCase()));+ const out = [...preserved];+ 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 mergeInfluences = opts.mergeInfluences;+ if (typeof mergeInfluences !== 'function') throw new Error('mergeExpandIntoDraft requires opts.mergeInfluences');+ const refinedInfluences = mergeInfluences(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/server/services/storyBuilder.js b/server/services/storyBuilder.jsindex 51e4405899..10155de9f6 100644--- a/server/services/storyBuilder.js+++ b/server/services/storyBuilder.js@@ -48,8 +48,9 @@ import { hashUpstream, computeStaleSteps, computeSyncDrift } from '../lib/storyBimport { getStoryBuilderStore } from './storyBuilderStore/store.js';import { linkIngredientsToSeries, resolveIngredientsByIds } from './catalogDB.js';import { getActiveCatalogType, payloadSnippet } from '../lib/catalogTypes.js';-import { createUniverse, deleteUniverse, getUniverse, updateUniverse } from './universeBuilder.js';+import { createUniverse, deleteUniverse, getUniverse, mergeInfluencesWithLocks, updateUniverse } from './universeBuilder.js';import { expandWorldTemplate } from './universeBuilderExpand.js';+import { extractPreservedFromDraft, mergeExpandIntoDraft } from '../lib/universeExpandMerge.js';import { refineWorldPrompts } from './universeBuilderRefine.js';import { refineUniverseCharacter } from './universeCanon.js';import {@@ -938,6 +939,7 @@ export async function generateStep(id, stepId, options = {}) {if (!session.universeId) throw makeErr('No universe linked', ERR_VALIDATION);const universe = await getUniverse(session.universeId);emit('Expanding the aesthetic…', 'generate');+ const { preservedVariations, preservedCompositeSheets } = extractPreservedFromDraft(universe);const expanded = await expandWorldTemplate({starterPrompt: universe.starterPrompt || session.seedIdea || universe.name,influences: universe.influences,@@ -945,15 +947,31 @@ export async function generateStep(id, stepId, options = {}) {premise: universe.premise,styleNotes: universe.styleNotes,locked: universe.locked,+ preservedVariations,+ preservedCompositeSheets,providerId: reqProviderId,model: reqModel,});emit('Saving…', 'persist');- const updated = await updateUniverse(session.universeId, {- logline: expanded.logline,- premise: expanded.premise,- styleNotes: expanded.styleNotes,- ...(expanded.influences ? { influences: expanded.influences } : {}),+ // Persist the WHOLE expansion (categories, composite sheets, canon) through+ // the same merge the Universe Builder page uses — never a wholesale write:+ // updateUniverse replaces compositeSheets + canon arrays, so a re-run on a+ // curated universe must merge against the LATEST record (the mutator form+ // runs inside the record's write queue, after the multi-minute LLM call)+ // to keep locked fields, pinned variations/sheets, and existing canon.+ const updated = await updateUniverse(session.universeId, (cur) => {+ const { expandedDraft } = mergeExpandIntoDraft(cur, expanded, { mergeInfluences: mergeInfluencesWithLocks });+ return {+ logline: expandedDraft.logline,+ premise: expandedDraft.premise,+ styleNotes: expandedDraft.styleNotes,+ influences: expandedDraft.influences,+ categories: expandedDraft.categories,+ compositeSheets: expandedDraft.compositeSheets,+ characters: expandedDraft.characters,+ places: expandedDraft.places,+ objects: expandedDraft.objects,+ };});return { result: updated, providerId: expanded.providerId, model: expanded.model };}diff --git a/server/services/storyBuilderAesthetic.test.js b/server/services/storyBuilderAesthetic.test.jsnew file mode 100644index 0000000000..d51f33975c--- /dev/null+++ b/server/services/storyBuilderAesthetic.test.js@@ -0,0 +1,98 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { mockNoPeerSync, mockNoPeers } from '../lib/mockPathsDataRoot.js';++// Contract under test: the universeAesthetic generate persists the WHOLE+// expansion through the shared Universe Builder merge, and a re-run on a+// curated universe keeps locks, pinned variations/sheets, and existing canon.+const fileStore = new Map();+vi.mock('../lib/fileUtils.js', () => ({+ sleep: vi.fn().mockResolvedValue(undefined),+ tryReadFile: vi.fn().mockResolvedValue(null),+ PATHS: { data: '/mock/data' },+ ensureDir: vi.fn().mockResolvedValue(undefined),+ atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),+ readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),+ readJSONFileStrict: vi.fn(async (path, fallback) => ({ ok: true, value: fileStore.has(path) ? fileStore.get(path) : fallback })),+ unreadableStoreError: (filePath) => Object.assign(new Error(`Unreadable JSON file: ${filePath}`), { status: 500, code: 'UNREADABLE_STORE' }),+}));+vi.mock('../instances.js', () => mockNoPeers());+vi.mock('../sharing/peerSync.js', () => mockNoPeerSync());+vi.mock('./stageRunner.js', () => ({ runStagedLLM: vi.fn(), extractJson: (raw) => JSON.parse(raw) }));+vi.mock('./catalogDB.js', () => ({+ listIngredients: vi.fn().mockResolvedValue({ items: [] }),+ linkIngredientsToSeries: vi.fn().mockResolvedValue([]),+ resolveIngredientsByIds: vi.fn().mockResolvedValue([]),+}));+const expandMock = vi.hoisted(() => vi.fn());+vi.mock('./universeBuilderExpand.js', () => ({ expandWorldTemplate: expandMock }));++const sb = await import('./storyBuilder.js');+const universeSvc = await import('./universeBuilder.js');++const expansion = (over = {}) => ({+ logline: 'New logline',+ premise: 'New premise',+ styleNotes: 'New style',+ influences: { embrace: ['noir'], avoid: ['neon'] },+ categories: { landscapes: { variations: [{ label: 'Fresh Vista', prompt: 'a vista' }] } },+ compositeSheets: [{ label: 'Fresh Board', prompt: 'board' }],+ characters: [{ name: 'Ashley', role: 'lead' }],+ places: [{ name: 'Foundry City', slugline: 'INT. FOUNDRY CITY - DAY' }],+ objects: [{ name: 'Brass Key' }],+ providerId: 'p', model: 'm',+ ...over,+});++beforeEach(() => {+ fileStore.clear();+ expandMock.mockReset();+});++describe('storyBuilder universeAesthetic generate', () => {+ it('persists categories, composite sheets, and canon on a fresh universe', async () => {+ const s = await sb.createStorySession({ title: 'Salt Run', seedIdea: 'a foundry city' });+ expandMock.mockResolvedValue(expansion());+ await sb.generateStep(s.id, 'universeAesthetic');+ const u = await universeSvc.getUniverse(s.universeId);+ expect(u.logline).toBe('New logline');+ expect(u.categories.landscapes.variations.map((v) => v.label)).toContain('Fresh Vista');+ expect(u.compositeSheets.map((x) => x.label)).toEqual(['Fresh Board']);+ expect(u.characters.map((c) => c.name)).toEqual(['Ashley']);+ expect(u.places).toHaveLength(1);+ expect(u.objects.map((o) => o.name)).toEqual(['Brass Key']);+ });++ it('a re-run keeps locked fields, pinned items, and merges canon by name', async () => {+ const s = await sb.createStorySession({ title: 'Salt Run', seedIdea: 'a foundry city' });+ expandMock.mockResolvedValue(expansion());+ await sb.generateStep(s.id, 'universeAesthetic');+ const first = await universeSvc.getUniverse(s.universeId);+ await universeSvc.updateUniverse(s.universeId, {+ locked: { logline: true },+ logline: 'Pinned logline',+ categories: { landscapes: { variations: [+ { label: 'Pinned Vista', prompt: 'p', locked: true },+ // Saved items default to locked; explicitly unpin the first run's.+ ...first.categories.landscapes.variations.map((v) => ({ ...v, locked: false })),+ ] } },+ compositeSheets: [{ label: 'Pinned Board', prompt: 'b', locked: true }, ...first.compositeSheets.map((x) => ({ ...x, locked: false }))],+ });+ expandMock.mockResolvedValue(expansion({+ logline: 'Overwrite attempt',+ categories: { landscapes: { variations: [{ label: 'Second Vista', prompt: 'v' }] } },+ compositeSheets: [{ label: 'Second Board', prompt: 'b' }],+ characters: [{ name: ' ashley ' }, { name: 'Bobby' }],+ }));+ await sb.generateStep(s.id, 'universeAesthetic');+ // The pinned items rode along with the request so the LLM won't regenerate them.+ expect(expandMock.mock.calls[1][0].preservedVariations.landscapes.map((v) => v.label)).toEqual(['Pinned Vista']);+ expect(expandMock.mock.calls[1][0].preservedCompositeSheets.map((x) => x.label)).toEqual(['Pinned Board']);+ const u = await universeSvc.getUniverse(s.universeId);+ expect(u.logline).toBe('Pinned logline');+ const labels = u.categories.landscapes.variations.map((v) => v.label);+ expect(labels).toContain('Pinned Vista');+ expect(labels).toContain('Second Vista');+ expect(u.compositeSheets.map((x) => x.label)).toEqual(expect.arrayContaining(['Pinned Board', 'Second Board']));+ expect(u.characters.map((c) => c.name).sort()).toEqual(['Ashley', 'Bobby']);+ });+});