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(universe-builder): DRY resolveProviderAndModel + findBibleEntryByName (#289)

[._.]/ Adam Eivyc37dcc01ca00
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 6d427ed0a4..2d65916434 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -24,3 +24,5 @@
- **`ImageGenSettingsForm` extended** with `showLoras` + `showStylePreset` props (mounts `LoraPicker` / `StylePresetPicker`) and the previously-hidden CFG / quantize / model-defaults reset.
- **`getStylePresetById` helper** added to `server/lib/writersRoomStylePresets.js` — Map-backed O(1) lookup that replaces the hand-rolled `STYLE_PRESETS.find(...)` pattern.
- **`updateUniverse(id, patch, options)`** API client now passes options through to the underlying `request()` helper, enabling silent error mode.
+- **`resolveProviderAndModel({providerId, model})`** added to `server/lib/promptRunner.js`. Collapses the 4 inlined `getProviderById/getActiveProvider/resolveEffectiveModel` chains in `universeBuilderExpand.js` (×2), `universeBuilderRefine.js`, and `universeBuilderPromote.js` onto one helper. The next caller is a one-import addition; the previous pattern was already drifting in error-handling specifics.
+- **`findBibleEntryByName(list, name)`** added to `server/lib/storyBible.js` for the "match name OR aliases case-insensitively" predicate. Replaces the inlined `.find(...)` in `universeBuilderPromote.js`'s duplicate-collision check. (`foldRetiredCharactersBucket` keeps its O(1) `Set` index over normalized names+aliases — a per-iteration live-array lookup would be O(n*m) when folding a large retired bucket against a large canon.)
diff --git a/DONE.md b/DONE.md
index cb79103bb1..a1327f5ded 100644
--- a/DONE.md
+++ b/DONE.md
@@ -9,6 +9,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./
## 2026-05
- **CoS — explicit `init()` instead of module-level auto-init.** Dropped the `NODE_ENV !== 'test' && VITEST !== 'true'` guard from `server/services/cos.js`; `init` is now exported and called from `server/index.js` alongside the other startup `*.init()` calls. Test imports no longer spin up event listeners / timers as a side effect, and the prod boot path no longer branches on test-env vars.
+- **Universe Builder DRY — `resolveProviderAndModel` + `findBibleEntryByName`.** Two shared helpers landed in `server/lib/`. The first collapses four inlined `getProviderById/getActiveProvider/resolveEffectiveModel` chains across the universe-builder LLM entrypoints onto one helper; the second consolidates the "case-insensitive name OR alias" predicate at the promote duplicate-collision check. (The retired-characters bucket fold keeps its O(1) seen-set index since it folds entries into a growing array — a per-iteration linear scan would have made it O(n*m).)
- **CoS / Agent lifecycle hardening.** Six backlog items flushed in one pass. (1) TUI providers now usable from the manual `/api/runs` runner panel — the client-side disable was stale once the server-side `executeTuiRun` branch landed in `routes/runs.js`. (2) Extracted two complementary helpers in `agentLifecycle.js` so the central completion sequence is shared between runner-mode `handleAgentCompletion`, the TUI `finish` path, and the direct-CLI `close` handler: `releaseAgentLane({ agentId, success, duration, exitCode, executionId, laneName, errorExecutionMessage })` fires lane release + tool-execution tracking EARLY (before output I/O / error analysis / state writes) so other lane tasks aren't blocked, and `finalizeAgent({ agentId, task, runId, providerId, success, exitCode, duration, outputBuffer, errorAnalysis, terminatedByUser, isTruthyMetaFn, error, completionReason })` runs the centralized state writes sequentially (persistSimplifySummaries → completeAgent → completeAgentRun → updateTask → provider markers → processAgentCompletion). A future divergence in any leg is now a one-place fix. (3) Wrapped `handleAgentCompletion` in try/finally so a throw from any inner step still drops the `runnerAgents` Map entry (previously leaked forever on memory-extraction crashes, JIRA push failures, etc.). (4) Added `isTuiProvider` next to `isClaudeCliProvider` and lifted `providerTypeClass` from `AIProviders.jsx` into `client/src/utils/providers.js`. (5) Converted `spawnTuiAgent` + `spawnDirectly` from 11-positional-arg signatures to options objects. (6) Wrapped `shellService.createShellSession` for agent TUIs in a thin `createAgentTuiSession({ agentId, provider, tuiConfig, cwd, onData, onExit })` helper. Regression-pin tests in `agentLifecycle.test.js` flipped from "documents the gap" to "asserts the guard fires."
- **Importer — section follow-ups landed.** Auto-detect content type stage (`importer-classify`, light-tier head pass that pre-selects the radio); in-place `proseExcerpt` edit affordance per issue card so users can trim/correct boundaries without re-running Analyze (3 heavy-tier calls); `replaceMode` flag wipes existing issues + overwrites arc/seasons on re-import (destructive opt-in for existing series); partial-commit retry now drops arc/seasons/canon from the retry payload via `arcAlreadyPersisted` context so a parallel-tab edit isn't overwritten; React.memo on per-issue and per-season cards (with stable patcher + memoized seasonOptions) so unedited cards skip render on keystroke; `ARC_SHAPE_IDS` exposed via `/importer/config` and `IMPORTER_ARC_ROLES_FALLBACK` retired from the client (server is now the sole source of arc roles + shape ids); screenplay-prompt split logic gates on `isUserRequestedCount` rather than conflating it with the per-type default; "(first season)" UI label replaced with the actual lowest-numbered season + title.
- **Sharing — auto-unsubscribe on local record delete.** `recordEvents.js` now hooks `deleteSeries` / `deleteUniverse` so orphaned `data/sharing/subscriptions.json` entries clean up automatically instead of logging errors on the next re-export attempt.
diff --git a/PLAN.md b/PLAN.md
index ad4ebc30c9..9c118a0e84 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -12,9 +12,6 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
- **Phase C — Layout rewrite.** Tabbed top-level (Bible / Cast / Places / Objects / Other / Composites / Render) with URL state (`?tab=cast&bucket=heroes` per CLAUDE.md linkable-routes convention) — Bible is its own tab (not a sticky header). Per-trunk view = sub-bucket chip filter row + responsive card grid. Unify `CanonCard` + a new card for category variations into a single `EntryCard` component (renders thumbnail from `primaryImageRef` or most recent render). **Canon entries are first-class batch-render targets** alongside category variations and composite sheets: per-bucket actions are "Generate N more" + "Bulk-render this bucket"; per-trunk action is "Bulk-render all Cast/Places/Objects" (includes BOTH canon entries AND every variation in every sub-bucket under that trunk); the Batch Render tab itself offers per-trunk, per-bucket, and "All canon" selectors plus the existing composite-sheets mode. Composite reference images stay intact as their own render mode (no regression). Server-side: extend `compilePrompts` to accept canon entries as render sources (synthesize a prompt from `name + physicalDescription/palette/description`, layered with the universe style preset the same way variations are today). The **Other** tab only appears when un-kinded buckets exist, and shows the **Auto-sort with AI** action. Mobile: tabs collapse to a select dropdown.
- **Phase D — Polish & promotion.** ~~"Promote variation to canon" action~~ shipped: `POST /api/universe-builder/:id/promote-variation` LLM-expands a `{label, prompt}` variation into a full canon entry (per-kind `physicalDescription` / `slugline`+`palette` / `description`+`significance`) and atomically writes the canon append + variation removal in one `updateUniverse` patch. CategoryEditor renders a promote button per row; Other-tab buckets open a trunk picker (since `kind: 'other'` can't be auto-resolved). Duplicate-name collisions short-circuit with a 409 before the LLM call. Deferred: client component tests; standalone design doc (not warranted — CLAUDE.md notes + this PR's prose cover the contract).
- **Phase D follow-ups (deferred from the Phase D PR):**
- - [ ] **Extract `resolveProviderAndModel({providerId, model})` into `server/lib/promptRunner.js`.** The same 5-line `getProviderById/getActiveProvider/resolveEffectiveModel` chain now lives in `expandWorldTemplate` (`universeBuilderExpand.js`), the refine entrypoint (`universeBuilderRefine.js`), AND `promoteVariationToCanon` (`universeBuilderPromote.js`). Three identical copies — consolidate next time we touch any of them.
- - [ ] **Add `findBibleEntryByName(list, name)` to `server/lib/storyBible.js`.** The "match name OR aliases case-insensitively" pattern lives in `promoteVariationToCanon` (duplicate-collision check) and `foldRetiredCharactersBucket` (seen-set construction) in `universeBuilder.js`. Will land a third caller when the Phase C auto-sort classifier ships.
- - [x] ~~**Serialize universe write-paths server-side.**~~ **Shipped 2026-05-17** — added `queueUniverseWrite` (single file-level queue) in `server/services/universeBuilder.js`. All five mutating fns (`createUniverse`, `insertUniverseWithId`, `updateUniverse`, `deleteUniverse`, `recordRun`) now enqueue onto it. The previously-inlined queue pattern from `pipeline/issues.js`, `pipeline/series.js`, and `mediaCollections.js` was extracted to a shared `server/lib/fileWriteQueue.js` factory (`createFileWriteQueue()`) and all four services were migrated onto it — drops 36 lines of copy-paste and the next pattern-tweak is a one-place fix. The unqueued migration write inside `readState()` was also removed (race-prone vs. concurrent queued writers); the next queued mutator persists the migrated shape naturally. Per CLAUDE.md "a `Map<recordId, Promise>` is *not* enough — collapse the queue to a single tail per shared file": same JSON file ⇒ single tail, not per-id. 4 regression tests cover same-universe concurrent PATCHes, cross-universe concurrent PATCHes, queue-poison-recovery, and recordRun + updateUniverse mixed concurrency; 4 helper tests pin the factory contract.
- [ ] **Client component tests for `CategoryEditor` promote wiring + `TrunkView` button visibility.** Assert promote button disabled when `!selectedId`, picker opens for `kind: 'other'` buckets, picker option click invokes `onPromote` with the correct `targetKind`. No client vitest infra wired for `UniverseBuilder.jsx` yet — add when the page's first spec lands.
- **Phase C follow-ups (deferred from the Phase C PR):**
- [ ] **Auto-sort with AI** — LLM-classify each `kind: 'other'` bucket into characters/settings/objects + suggest a meaningful name. New server route `POST /api/universe-builder/:id/auto-sort` that sends bucket keys + variation labels to the active LLM and applies the classification. Currently the Other-tab button is a stub that points users at re-running Generate From Idea (Phase B's expand emits kind tags). Land in a follow-up to keep the Phase C PR scoped.
@@ -91,6 +88,8 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
### Code quality / dedup (from `/simplify` passes)
+- [ ] **More `resolveProviderAndModel` migration candidates.** When the helper landed in `server/lib/promptRunner.js` (universe-builder PR), three additional pure two-step provider-resolution chains were left alone to keep scope tight: `server/services/agentContentGenerator.js#runAIGeneration` (line ~80–90), `server/services/agentPersonalityGenerator.js` (line ~68–79), `server/services/loops.js` (line ~64–77). All three are textbook fits (no `enabled` gate, no typed-error throw mid-chain). Migration is one-import + 5-line collapse per file.
+- [ ] **Extract `assertProvider(provider, { errorMessage, code, status })` helper.** After the `resolveProviderAndModel` migration there are now 4 `if (!provider) throw …` sites with varying error shapes (`Error` vs `ServerError`, `status: 400/503`, codes `NO_PROVIDER`/`UNIVERSE_PROMOTE_NO_PROVIDER`/etc.). One helper that takes the error-shape args would consolidate without forcing each caller to share the same error type.
- [ ] **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.
- [x] ~~**Canon-merge can revert concurrent deletions/renames.**~~ **Fixed in Phase B Copilot iteration 15** — handleExpand records each merge's NEW canon entries in a `pendingCanonAdditionsRef` sidecar; handleSave + handleExpand auto-save + handleCanonChange now merge ONLY that ledger onto the refetched server canon (not the full stale draft). Concurrent deletions in other tabs/surfaces are preserved because the deleted entry isn't in the ledger, so the server response (which already lacks it) wins.
diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.js
index 5e6128e1bd..60af74940e 100644
--- a/server/lib/promptRunner.js
+++ b/server/lib/promptRunner.js
@@ -27,6 +27,7 @@
*/
import { createRun, executeApiRun, executeCliRun, extractBakedModel, hasModelFlag, stopRun, patchRunMetadata } from '../services/runner.js';
+import { getActiveProvider, getProviderById } from '../services/providers.js';
import { executeTuiRun } from './tuiPromptRunner.js';
const DEFAULT_TIMEOUT_MS = 300000;
@@ -77,6 +78,32 @@ export function resolveEffectiveModel(provider, callerModel) {
return baked || provider?.defaultModel || provider?.models?.[0] || null;
}
+/**
+ * Resolve `{provider, selectedModel}` for an LLM caller. Prefers
+ * `providerId` — any `getProviderById` failure (stale id, lookup
+ * error, network blip) falls through to `getActiveProvider`. Returns
+ * `{provider: null, selectedModel: null}` when neither resolves a
+ * provider (e.g. no providers configured), so callers throw their own
+ * typed error.
+ *
+ * Note: errors from `getActiveProvider` (e.g. toolkit not initialized)
+ * still propagate — only `getProviderById` failures are swallowed.
+ * This mirrors the inline pattern this helper replaced. If a caller
+ * wants total "always-null on failure" semantics, wrap the call in
+ * their own try/catch.
+ *
+ * @param {object} args
+ * @param {string} [args.providerId]
+ * @param {string} [args.model]
+ * @returns {Promise<{ provider: object|null, selectedModel: string|null }>}
+ */
+export async function resolveProviderAndModel({ providerId, model } = {}) {
+ let provider = providerId ? await getProviderById(providerId).catch(() => null) : null;
+ if (!provider) provider = await getActiveProvider();
+ const selectedModel = provider ? resolveEffectiveModel(provider, model) : null;
+ return { provider, selectedModel };
+}
+
/**
* Run a prompt through a provider and resolve with the streamed text +
* run id. Rejects (via the strictest discriminator) on any runner-
diff --git a/server/lib/promptRunner.test.js b/server/lib/promptRunner.test.js
index 563e02d746..3555ad585e 100644
--- a/server/lib/promptRunner.test.js
+++ b/server/lib/promptRunner.test.js
@@ -22,9 +22,18 @@ vi.mock('./tuiPromptRunner.js', () => ({
executeTuiRun: vi.fn(),
}));
+// providers.js is a compatibility shim that throws when the toolkit hasn't
+// been initialized via setAIToolkit(). Mock it so the resolveProviderAndModel
+// tests can drive the active/by-id lookups directly.
+vi.mock('../services/providers.js', () => ({
+ getActiveProvider: vi.fn(),
+ getProviderById: vi.fn(),
+}));
+
const runner = await import('../services/runner.js');
const tuiRunner = await import('./tuiPromptRunner.js');
-const { runPromptThroughProvider } = await import('./promptRunner.js');
+const providers = await import('../services/providers.js');
+const { runPromptThroughProvider, resolveProviderAndModel } = await import('./promptRunner.js');
const apiProvider = (extra = {}) => ({
id: 'mock-api', type: 'api', defaultModel: 'm-default', ...extra,
@@ -539,3 +548,53 @@ describe('promptRunner — API timeout enforcement', () => {
vi.useRealTimers();
});
});
+
+describe('resolveProviderAndModel', () => {
+ beforeEach(() => {
+ providers.getActiveProvider.mockReset();
+ providers.getProviderById.mockReset();
+ });
+
+ it('uses providerId when it resolves; selectedModel falls back to defaultModel', async () => {
+ providers.getProviderById.mockResolvedValue({ id: 'p-1', type: 'api', defaultModel: 'm-default' });
+ const out = await resolveProviderAndModel({ providerId: 'p-1' });
+ expect(providers.getProviderById).toHaveBeenCalledWith('p-1');
+ expect(providers.getActiveProvider).not.toHaveBeenCalled();
+ expect(out.provider?.id).toBe('p-1');
+ expect(out.selectedModel).toBe('m-default');
+ });
+
+ it('caller model wins over provider.defaultModel when the provider honors overrides', async () => {
+ providers.getProviderById.mockResolvedValue({ id: 'p-1', type: 'api', defaultModel: 'm-default' });
+ const out = await resolveProviderAndModel({ providerId: 'p-1', model: 'm-override' });
+ expect(out.selectedModel).toBe('m-override');
+ });
+
+ it('falls back to getActiveProvider when providerId lookup throws', async () => {
+ providers.getProviderById.mockRejectedValue(new Error('stale id'));
+ providers.getActiveProvider.mockResolvedValue({ id: 'active-1', type: 'api', defaultModel: 'm-default' });
+ const out = await resolveProviderAndModel({ providerId: 'p-stale' });
+ expect(out.provider?.id).toBe('active-1');
+ expect(out.selectedModel).toBe('m-default');
+ });
+
+ it('falls back to getActiveProvider when providerId resolves to null', async () => {
+ providers.getProviderById.mockResolvedValue(null);
+ providers.getActiveProvider.mockResolvedValue({ id: 'active-1', type: 'api', defaultModel: 'm-default' });
+ const out = await resolveProviderAndModel({ providerId: 'p-missing' });
+ expect(out.provider?.id).toBe('active-1');
+ });
+
+ it('skips getProviderById entirely when no providerId is given', async () => {
+ providers.getActiveProvider.mockResolvedValue({ id: 'active-1', type: 'api', defaultModel: 'm-default' });
+ const out = await resolveProviderAndModel({});
+ expect(providers.getProviderById).not.toHaveBeenCalled();
+ expect(out.provider?.id).toBe('active-1');
+ });
+
+ it('returns { provider: null, selectedModel: null } when neither resolves', async () => {
+ providers.getActiveProvider.mockResolvedValue(null);
+ const out = await resolveProviderAndModel({});
+ expect(out).toEqual({ provider: null, selectedModel: null });
+ });
+});
diff --git a/server/lib/storyBible.js b/server/lib/storyBible.js
index 0cdf27ce99..75221a5d34 100644
--- a/server/lib/storyBible.js
+++ b/server/lib/storyBible.js
@@ -174,6 +174,21 @@ export const isBlank = (v) => {
export const normalizeBibleName = (name) => String(name || '').trim().toLowerCase();
+/**
+ * Case-insensitive lookup by `name` OR `aliases[]` (using
+ * `normalizeBibleName`). Returns the first match or undefined; tolerates a
+ * non-array list, blank needle, and null entries. Settings use sluglines
+ * for their primary identity; use `normalizeSlugline` + a Map lookup for
+ * those instead — this helper is name-keyed.
+ */
+export function findBibleEntryByName(list, name) {
+ if (!Array.isArray(list)) return undefined;
+ const needle = normalizeBibleName(name);
+ if (!needle) return undefined;
+ return list.find((e) => normalizeBibleName(e?.name) === needle
+ || (Array.isArray(e?.aliases) && e.aliases.some((a) => normalizeBibleName(a) === needle)));
+}
+
// Fields the LLM should NEVER set on a canon entry it just generated.
// `id/createdAt/updatedAt` get freshly minted by the per-kind sanitizer; a
// hallucinated `locked: true` would block user edits without a Lock UI click;
diff --git a/server/lib/storyBible.test.js b/server/lib/storyBible.test.js
index b37eb70502..c10bfd9e47 100644
--- a/server/lib/storyBible.test.js
+++ b/server/lib/storyBible.test.js
@@ -24,6 +24,7 @@ const {
isBlank,
normalizeBibleName,
normalizeSlugline,
+ findBibleEntryByName,
BIBLE_LIMITS,
BIBLE_KIND,
createBibleStore,
@@ -533,6 +534,40 @@ describe('storyBible — helpers', () => {
expect(normalizeBibleName(' Aria Reyes ')).toBe('aria reyes');
expect(normalizeBibleName(null)).toBe('');
});
+
+ describe('findBibleEntryByName', () => {
+ const list = [
+ { id: 'a', name: 'Ashley', aliases: ['Ash', 'Ash-bot'] },
+ { id: 'b', name: 'Crystalline Canyon' }, // no aliases array
+ { id: 'c', name: 'Reyes', aliases: null }, // null aliases tolerated
+ null, // null entry tolerated
+ ];
+
+ it('matches by case-insensitive name', () => {
+ expect(findBibleEntryByName(list, 'ashley')?.id).toBe('a');
+ expect(findBibleEntryByName(list, ' ASHLEY ')?.id).toBe('a');
+ });
+
+ it('matches by alias when present', () => {
+ expect(findBibleEntryByName(list, 'ash')?.id).toBe('a');
+ expect(findBibleEntryByName(list, 'Ash-Bot')?.id).toBe('a');
+ });
+
+ it('returns undefined when no entry matches', () => {
+ expect(findBibleEntryByName(list, 'Nobody')).toBeUndefined();
+ });
+
+ it('returns undefined for blank/missing needles', () => {
+ expect(findBibleEntryByName(list, '')).toBeUndefined();
+ expect(findBibleEntryByName(list, ' ')).toBeUndefined();
+ expect(findBibleEntryByName(list, null)).toBeUndefined();
+ });
+
+ it('returns undefined for a non-array list', () => {
+ expect(findBibleEntryByName(null, 'Ashley')).toBeUndefined();
+ expect(findBibleEntryByName(undefined, 'Ashley')).toBeUndefined();
+ });
+ });
});
// ---------------------------------------------------------------------------
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index 5f6c2362e5..7b0a184358 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -481,7 +481,10 @@ function foldRetiredCharactersBucket(raw, canon) {
// variation matching an existing alias should collide and NOT create a
// duplicate. Without alias indexing, an "Ashley" character with alias
// "Ash" plus a `categories.characters: [{label: "Ash"}]` payload would
- // produce two records.
+ // produce two records. We keep a Set (rather than re-scanning the live
+ // array via findBibleEntryByName each iteration) so the per-variation
+ // membership test stays O(1) — folding a large retired bucket against a
+ // large canon would otherwise be O(n*m).
const seen = new Set();
for (const e of next.characters) {
if (e?.name) seen.add(normalizeBibleName(e.name));
diff --git a/server/services/universeBuilderExpand.js b/server/services/universeBuilderExpand.js
index 3a85b1c2fa..dd93d0beb4 100644
--- a/server/services/universeBuilderExpand.js
+++ b/server/services/universeBuilderExpand.js
@@ -11,7 +11,6 @@
* model so the UI still works for users who haven't configured a stage.
*/
-import { getActiveProvider, getProviderById } from "./providers.js";
import {
WORLD_CATEGORIES,
CATEGORY_KINDS,
@@ -33,7 +32,7 @@ import { sanitizeBibleList, stripCanonControlFields, BIBLE_KIND, BIBLE_SOURCE }
import { ServerError } from "../lib/errorHandler.js";
import { extractJson as extractJsonShared } from "../lib/jsonExtract.js";
import {
- resolveEffectiveModel,
+ resolveProviderAndModel,
runPromptThroughProvider,
} from "../lib/promptRunner.js";
@@ -341,18 +340,11 @@ export async function expandWorldTemplate({
// the LLM prompt or the returned result. Empty / missing → empty lists.
const safeInfluences = sanitizeInfluences(influences);
- let provider = providerId
- ? await getProviderById(providerId).catch(() => null)
- : null;
- if (!provider) provider = await getActiveProvider();
+ // Resolve the model the runner will ACTUALLY execute (honoring CLI baked
+ // --model flags) so the log line + returned `llm.model` don't lie.
+ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });
if (!provider)
throw new Error("No AI provider available for universe expansion");
- // resolveEffectiveModel mirrors what promptRunner resolves internally
- // so the log line below + the returned `llm.model` field reflect what
- // actually executed. For CLI providers with a baked --model/-m flag
- // in args it returns the args-pinned id (not provider.defaultModel,
- // which can diverge).
- const selectedModel = resolveEffectiveModel(provider, model);
const fullPrompt = buildExpansionPrompt({
starterPrompt: starterPrompt.trim(),
@@ -593,10 +585,8 @@ export async function generateCategoryVariations({
? existingLabels.filter((l) => typeof l === "string" && l.trim()).map((l) => l.trim())
: [];
- let provider = providerId ? await getProviderById(providerId).catch(() => null) : null;
- if (!provider) provider = await getActiveProvider();
+ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });
if (!provider) throw new Error("No AI provider available for variation generation");
- const selectedModel = resolveEffectiveModel(provider, model);
const fullPrompt = buildCategoryGeneratePrompt({
category: category.trim(),
diff --git a/server/services/universeBuilderPromote.js b/server/services/universeBuilderPromote.js
index dcd037c37c..4b58073010 100644
--- a/server/services/universeBuilderPromote.js
+++ b/server/services/universeBuilderPromote.js
@@ -5,7 +5,6 @@
* patch so the transition is atomic.
*/
-import { getActiveProvider, getProviderById } from './providers.js';
import {
getUniverse,
updateUniverse,
@@ -15,17 +14,15 @@ import {
import {
sanitizeBibleList,
stripCanonControlFields,
- normalizeBibleName,
+ findBibleEntryByName,
+ normalizeSlugline,
BIBLE_FIELD,
BIBLE_SOURCE,
BIBLE_LIMITS,
} from '../lib/storyBible.js';
import { ServerError } from '../lib/errorHandler.js';
import { extractJson as extractJsonShared } from '../lib/jsonExtract.js';
-import {
- resolveEffectiveModel,
- runPromptThroughProvider,
-} from '../lib/promptRunner.js';
+import { resolveProviderAndModel, runPromptThroughProvider } from '../lib/promptRunner.js';
// Inverse of BIBLE_FIELD: trunk-name (canon array key) → singular BIBLE_KIND.
// Derived from the source-of-truth map so the two can't drift. `other` is
@@ -207,11 +204,24 @@ export async function promoteVariationToCanon(universeId, options = {}) {
// Refuse silent duplicate creation: if a canon entry with the variation's
// label already exists, surface a 409 so the UI can suggest "open the
// existing entry" or "rename then promote" rather than producing a second
- // record that the merge logic would silently swallow on next save.
+ // record that the merge logic would silently swallow on next save. For
+ // settings (kind whose identity is slugline-keyed via MERGE_CONFIG), also
+ // match the variation label against existing entries' `slugline` so a
+ // dash-variant or slug-vs-name promotion doesn't slip past name-only
+ // matching.
const existingCanon = Array.isArray(universe[bibleField]) ? universe[bibleField] : [];
- const labelKey = normalizeBibleName(variation.label);
- const collision = existingCanon.find((e) => normalizeBibleName(e?.name) === labelKey
- || (Array.isArray(e?.aliases) && e.aliases.some((a) => normalizeBibleName(a) === labelKey)));
+ let collision = findBibleEntryByName(existingCanon, variation.label);
+ if (!collision && targetKind === 'settings') {
+ const needleSlug = normalizeSlugline(variation.label);
+ if (needleSlug) {
+ collision = existingCanon.find((e) => {
+ if (!e || typeof e !== 'object') return false;
+ if (normalizeSlugline(e.slugline) === needleSlug) return true;
+ if (normalizeSlugline(e.name) === needleSlug) return true;
+ return false;
+ });
+ }
+ }
if (collision) {
throw new ServerError(
`Canon ${targetKind} "${variation.label}" already exists — rename the variation or open the existing entry`,
@@ -223,14 +233,12 @@ export async function promoteVariationToCanon(universeId, options = {}) {
);
}
- let provider = providerId ? await getProviderById(providerId).catch(() => null) : null;
- if (!provider) provider = await getActiveProvider();
+ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });
if (!provider) {
throw new ServerError('No AI provider available for variation promotion', {
status: 503, code: 'UNIVERSE_PROMOTE_NO_PROVIDER',
});
}
- const selectedModel = resolveEffectiveModel(provider, model);
const prompt = buildPromotePrompt({
targetKind,
diff --git a/server/services/universeBuilderPromote.test.js b/server/services/universeBuilderPromote.test.js
index 1accb2a5ce..1029dfb83e 100644
--- a/server/services/universeBuilderPromote.test.js
+++ b/server/services/universeBuilderPromote.test.js
@@ -18,20 +18,17 @@ vi.mock('crypto', async () => {
return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };
});
-// Stub the provider + LLM dispatch so tests don't need a live runner. The
+// Stub the LLM dispatch so tests don't need a live runner. The
// `runPromptThroughProvider` mock is overridden per-test to return the
-// per-kind JSON shape we expect from the LLM.
-const getActiveProviderMock = vi.fn();
-const getProviderByIdMock = vi.fn();
-vi.mock('./providers.js', () => ({
- getActiveProvider: (...a) => getActiveProviderMock(...a),
- getProviderById: (...a) => getProviderByIdMock(...a),
-}));
-
+// per-kind JSON shape we expect from the LLM. `resolveProviderAndModel`
+// is stubbed flat — `promptRunner.test.js` already exercises its real
+// branching, so re-mirroring it here would just double-mock the same
+// contract.
+const resolveProviderAndModelMock = vi.fn();
const runPromptThroughProviderMock = vi.fn();
vi.mock('../lib/promptRunner.js', () => ({
runPromptThroughProvider: (...a) => runPromptThroughProviderMock(...a),
- resolveEffectiveModel: (_provider, model) => model || 'mock-default',
+ resolveProviderAndModel: (...a) => resolveProviderAndModelMock(...a),
}));
// Pull services AFTER mocks register so module-level imports resolve through
@@ -62,11 +59,11 @@ const mockLlm = (entry) => {
beforeEach(() => {
fileStore.clear();
uuidCounter = 0;
- getActiveProviderMock.mockReset();
- getProviderByIdMock.mockReset();
+ resolveProviderAndModelMock.mockReset();
runPromptThroughProviderMock.mockReset();
- getActiveProviderMock.mockResolvedValue({
- id: 'provider-mock', name: 'Mock', type: 'api', defaultModel: 'mock-default',
+ resolveProviderAndModelMock.mockResolvedValue({
+ provider: { id: 'provider-mock', name: 'Mock', type: 'api', defaultModel: 'mock-default' },
+ selectedModel: 'mock-default',
});
});
@@ -95,8 +92,13 @@ describe('universeBuilderPromote — happy path', () => {
const result = await promoteSvc.promoteVariationToCanon(w.id, {
category: 'landscapes',
label: 'Crystalline canyon',
+ providerId: 'p-explicit',
+ model: 'm-explicit',
});
+ // Arg-shape pin: a future typo (provider/Provider/etc.) would silently
+ // pass under a flat resolver mock without this assertion.
+ expect(resolveProviderAndModelMock).toHaveBeenCalledWith({ providerId: 'p-explicit', model: 'm-explicit' });
expect(result.targetKind).toBe('settings');
expect(result.entry.name).toBe('Crystalline Canyon');
expect(result.entry.palette).toContain('pale violet');
@@ -311,6 +313,33 @@ describe('universeBuilderPromote — error paths', () => {
expect(runPromptThroughProviderMock).not.toHaveBeenCalled();
});
+ it('409s on settings slugline collision (name differs, slugline matches)', async () => {
+ // Variation label maps to an existing setting via slugline normalization
+ // — the name-only check would miss this, but the kind-specific slugline
+ // fallback catches it.
+ const existing = [{
+ name: 'Foundry City Bay',
+ slugline: 'EXT. FOUNDRY CITY — DAY',
+ description: 'A pre-existing canon entry keyed by slugline.',
+ }];
+ const w = await seedUniverseWithBucket(
+ {
+ landscapes: {
+ kind: 'settings',
+ variations: [{ label: 'EXT. FOUNDRY CITY - DAY', prompt: 'dawn light over docks' }],
+ },
+ },
+ { settings: existing },
+ );
+ await expect(
+ promoteSvc.promoteVariationToCanon(w.id, {
+ category: 'landscapes',
+ label: 'EXT. FOUNDRY CITY - DAY',
+ }),
+ ).rejects.toMatchObject({ status: 409, code: 'UNIVERSE_PROMOTE_DUPLICATE' });
+ expect(runPromptThroughProviderMock).not.toHaveBeenCalled();
+ });
+
it('throws 502 when the LLM returns invalid JSON', async () => {
const w = await seedUniverseWithBucket({
landscapes: {
diff --git a/server/services/universeBuilderRefine.js b/server/services/universeBuilderRefine.js
index a4291ab5e0..009b46dc86 100644
--- a/server/services/universeBuilderRefine.js
+++ b/server/services/universeBuilderRefine.js
@@ -12,9 +12,7 @@
*/
import { ServerError } from "../lib/errorHandler.js";
-import { getActiveProvider, getProviderById } from "./providers.js";
-import { runPromptThroughProvider } from "../lib/promptRunner.js";
-import { resolveEffectiveModel } from "../lib/promptRunner.js";
+import { resolveProviderAndModel, runPromptThroughProvider } from "../lib/promptRunner.js";
import {
renderCategoriesForPrompt as renderCategoriesShared,
renderCompositesForPrompt as renderCompositesShared,
@@ -410,10 +408,7 @@ export async function refineWorldPrompts({
);
}
- let provider = providerId
- ? await getProviderById(providerId).catch(() => null)
- : null;
- if (!provider) provider = await getActiveProvider();
+ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });
if (!provider) {
throw new ServerError("No AI provider available for universe refinement", {
status: 400,
@@ -427,11 +422,6 @@ export async function refineWorldPrompts({
);
}
- // Resolve the model id that will ACTUALLY execute so the response /
- // run record / log line match the args-pinned id when a CLI provider's
- // args have a baked --model/-m flag. Shared helper documents the
- // decision table.
- const selectedModel = resolveEffectiveModel(provider, model) || "";
if (!selectedModel && provider.type === "api") {
throw new ServerError("Model is required for universe refinement", {
status: 400,