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
refactor: one shared lib owns the per-record LLM route pin instead of each subsystem re-deriving it (#4793)
[._.]/ Adam Eivy3167e709f684
diff --git a/server/lib/README.md b/server/lib/README.mdindex 2caa9d615b..aceaa53ba1 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -86,6 +86,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `storyboardScenes.js` | Durable ids + id-first addressing for `stages.storyboards.scenes[]` (#3413). `ensureStoryboardIds(scenes)` stamps a deterministic `scene-NN` / `shot-NN` id on any entry lacking one — and re-stamps later copies of a DUPLICATE id (collision-escaped with a `-2` suffix, so peers and concurrent readers derive identical ids); `resolveStoryboardTarget(list, { id, index })` → `{ index, record, matchedBy, stale }` resolves a captured id against a fresh array, falling back to the index only when no id was captured, and reporting `stale: true` (409, never an index retarget) when a captured id is gone. || `seasonStructure.js` | Season/episode structure recommendation. || `seriesCharacterArc.js` | Per-character story-arc shapes (`series.characterArcs[]`): want/need, start → end state, transition beats. Sanitizers + `renderCharacterArcsForPrompt` for the `arc.transitions` editorial check. |+| `llmRoutePin.js` | The per-record LLM route pin `{ providerId, model, effort }` — `LLM_ROUTE_PIN_LIMITS` + `llmRoutePinSchema` (door check, `effort` as the shared `EFFORT_LEVELS` enum), `sanitizeLlmRoutePin(raw)` (trim/cap, `null` for an all-empty pin), and `resolveLlmRoutePin(pin, perCall)` → `{ providerId, model, effort, providerMatchesPin }`. Owns the never-cross-providers rule once: a per-call pick beats the pin, and the pin's model/effort are inherited only while the effective provider is still the one they were picked for. Consumed by `seriesLlmOverride.js` and FableLoom's play pin. || `seriesLlmOverride.js` | Pure `resolveSeriesLlmOverride(series, { overrideProvider, overrideModel })` → `{ provider, model, providerMatchesSeries }` — shared fallback so Pipeline LLM actions honor the series' configured provider/model, only inheriting the series model when the effective provider still matches. || `bibleExtractor.js` | LLM bible-extraction stage + sanitization. || `catalogBulkParsers.js` | Dependency-free markdown/CSV/JSON parsers for `POST /api/catalog/bulk-import` and YAML/markdown serializers for `GET /api/catalog/export`. |diff --git a/server/lib/fableLoomValidation.js b/server/lib/fableLoomValidation.jsindex 69418755ce..0c680275aa 100644--- a/server/lib/fableLoomValidation.js+++ b/server/lib/fableLoomValidation.js@@ -8,7 +8,7 @@import { z } from 'zod';import { LOOM_LIMITS } from '../services/fableLoom/limits.js';import { LOOM_FORMATS } from '../services/fableLoom/formats.js';-import { EFFORT_LEVELS } from './providerModels.js';+import { llmRoutePinSchema } from './llmRoutePin.js';const name = z.string().trim().min(1).max(LOOM_LIMITS.NAME_MAX);const logline = z.string().max(LOOM_LIMITS.LOGLINE_MAX);@@ -19,17 +19,12 @@ const title = z.string().max(LOOM_LIMITS.EPISODE_TITLE_MAX);const synopsis = z.string().max(LOOM_LIMITS.SYNOPSIS_MAX);const nodeIdStr = z.string().min(1).max(80);const format = z.enum(LOOM_FORMATS);-// The loom's pinned play routing. Nullable per field ('' from a cleared select-// is normalized to null by the sanitizer) and nullable as a whole, so the UI-// can clear the pin outright. `effort` is the shared ladder enum, not a free-// string — the runner would clamp an unknown level silently, and the door-// check is where a typo should surface.-const effort = z.enum(EFFORT_LEVELS);-const playSettings = z.object({- providerId: z.string().max(LOOM_LIMITS.PROVIDER_ID_MAX).nullable().optional(),- model: z.string().max(LOOM_LIMITS.MODEL_ID_MAX).nullable().optional(),- effort: effort.nullable().optional(),-}).nullable();+// The loom's pinned play routing is the shared per-record LLM route pin+// (`server/lib/llmRoutePin.js`), nullable as a whole so the UI can clear it+// outright. Its `effort` is the shared ladder enum rather than a free string —+// the runner would clamp an unknown level silently, and the door check is+// where a typo should surface.+const playSettings = llmRoutePinSchema.nullable();// Index filter. `?seriesId=` scopes the list to the looms soft-linked to one// pipeline series (the series detail page's "Branching narratives" card). An@@ -120,11 +115,8 @@ export const nodeCreateSchema = z.object({export const nodePatchSchema = z.object(nodeFields);-const llmPickFields = {- providerId: z.string().max(LOOM_LIMITS.PROVIDER_ID_MAX).optional(),- model: z.string().max(LOOM_LIMITS.MODEL_ID_MAX).optional(),- effort: effort.optional(),-};+// A per-call pick carries the same three dimensions as the saved pin.+const llmPickFields = llmRoutePinSchema.shape;export const weaveSchema = z.object({guidance: z.string().max(4000).optional(),diff --git a/server/lib/index.js b/server/lib/index.jsindex bb5146ea60..b3658831fa 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -84,6 +84,7 @@ export * from './shotGrammar.js';export * from './storyboardScenes.js';export * from './seasonStructure.js';export * from './seriesCharacterArc.js';+export * from './llmRoutePin.js';export * from './seriesLlmOverride.js';export * from './storyArc.js';export * from './styleGuide.js';diff --git a/server/lib/llmRoutePin.js b/server/lib/llmRoutePin.jsnew file mode 100644index 0000000000..96961b8e1f--- /dev/null+++ b/server/lib/llmRoutePin.js@@ -0,0 +1,86 @@+/**+ * The per-record LLM route pin — `{ providerId, model, effort }` saved on a+ * record so an action run against it uses the provider the user picked there+ * instead of the global active provider.+ *+ * Eight subsystems each hand-rolled this shape (series `llm`, FableLoom+ * `playSettings`, CoS job pins, creative-director stage pins, …), and every+ * copy re-derived the same rule from scratch. This module owns it once:+ *+ * **A model id and an effort level belong to the provider they were picked+ * for.** Forwarding either to a different provider fails at run time — a+ * `claude --model gemini-…` spawn, or an effort level the target CLI's ladder+ * has never heard of. So a per-call pick beats the pin outright, and the pin's+ * model/effort are inherited ONLY while the effective provider is still the+ * one they were picked for. A per-call switch that names no model leaves the+ * model blank so the new provider's default resolves.+ *+ * `null` (never `''`) marks an unset dimension, so "fall through to the next+ * layer" stays distinguishable from a deliberate empty choice.+ */++import { z } from 'zod';+import { EFFORT_LEVELS } from './providerModels.js';+import { trimTo } from './storyBible.js';++/** Field caps for a pin — the one source of truth for both the door check+ * (`llmRoutePinSchema`) and the sanitizer, so they can never drift. */+export const LLM_ROUTE_PIN_LIMITS = Object.freeze({+ PROVIDER_ID_MAX: 100,+ MODEL_ID_MAX: 200,+ EFFORT_MAX: 20,+});++/**+ * Zod fragment for a pin. Every field is nullable (a cleared select sends+ * `null`) and optional (an unset dimension is simply absent). `effort` is the+ * shared ladder enum rather than a capped free string — the runner clamps an+ * unknown level silently, and the door check is where a typo should surface.+ * Callers add `.nullable()` when the whole pin can be cleared at once.+ */+export const llmRoutePinSchema = z.object({+ providerId: z.string().max(LLM_ROUTE_PIN_LIMITS.PROVIDER_ID_MAX).nullable().optional(),+ model: z.string().max(LLM_ROUTE_PIN_LIMITS.MODEL_ID_MAX).nullable().optional(),+ effort: z.enum(EFFORT_LEVELS).nullable().optional(),+});++/**+ * Trim/cap a raw pin into the stored shape. Returns `null` for a non-object or+ * an all-empty pin, so a record never persists a pin that pins nothing.+ *+ * @param {unknown} raw+ * @returns {{ providerId: string|null, model: string|null, effort: string|null }|null}+ */+export function sanitizeLlmRoutePin(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const pick = (value, max) => trimTo(value, max) || null;+ const pin = {+ providerId: pick(raw.providerId, LLM_ROUTE_PIN_LIMITS.PROVIDER_ID_MAX),+ model: pick(raw.model, LLM_ROUTE_PIN_LIMITS.MODEL_ID_MAX),+ effort: pick(raw.effort, LLM_ROUTE_PIN_LIMITS.EFFORT_MAX),+ };+ return Object.values(pin).some(Boolean) ? pin : null;+}++/**+ * Resolve the effective route for one call against a saved pin.+ *+ * `providerMatchesPin` is `true` when the call is still running on the+ * provider the pin's model/effort were picked for — either because the call+ * named no provider, or because it named the pinned one. Callers surface it+ * when they need to explain why a pinned model was dropped.+ *+ * @param {{ providerId?: string|null, model?: string|null, effort?: string|null }|null|undefined} pin+ * @param {{ providerId?: string|null, model?: string|null, effort?: string|null }} [perCall]+ * @returns {{ providerId: string|null, model: string|null, effort: string|null, providerMatchesPin: boolean }}+ */+export function resolveLlmRoutePin(pin, perCall = {}) {+ const pinned = pin || {};+ const providerMatchesPin = !perCall.providerId || perCall.providerId === pinned.providerId;+ return {+ providerId: perCall.providerId || pinned.providerId || null,+ model: perCall.model || (providerMatchesPin ? pinned.model : null) || null,+ effort: perCall.effort || (providerMatchesPin ? pinned.effort : null) || null,+ providerMatchesPin,+ };+}diff --git a/server/lib/llmRoutePin.test.js b/server/lib/llmRoutePin.test.jsnew file mode 100644index 0000000000..6de9cecd47--- /dev/null+++ b/server/lib/llmRoutePin.test.js@@ -0,0 +1,108 @@+import { describe, it, expect } from 'vitest';+import {+ LLM_ROUTE_PIN_LIMITS,+ llmRoutePinSchema,+ resolveLlmRoutePin,+ sanitizeLlmRoutePin,+} from './llmRoutePin.js';++describe('sanitizeLlmRoutePin', () => {+ it('trims each dimension and nulls the empty ones', () => {+ expect(sanitizeLlmRoutePin({ providerId: ' claude ', model: '', effort: null })).toEqual({+ providerId: 'claude',+ model: null,+ effort: null,+ });+ });++ it('returns null for a non-object, a missing pin, or an all-empty pin', () => {+ expect(sanitizeLlmRoutePin(null)).toBeNull();+ expect(sanitizeLlmRoutePin(undefined)).toBeNull();+ expect(sanitizeLlmRoutePin('claude')).toBeNull();+ expect(sanitizeLlmRoutePin({ providerId: ' ' })).toBeNull();+ });++ it('caps each field at its limit', () => {+ const pin = sanitizeLlmRoutePin({+ providerId: 'p'.repeat(500),+ model: 'm'.repeat(500),+ effort: 'e'.repeat(500),+ });+ expect(pin.providerId).toHaveLength(LLM_ROUTE_PIN_LIMITS.PROVIDER_ID_MAX);+ expect(pin.model).toHaveLength(LLM_ROUTE_PIN_LIMITS.MODEL_ID_MAX);+ expect(pin.effort).toHaveLength(LLM_ROUTE_PIN_LIMITS.EFFORT_MAX);+ });+});++describe('llmRoutePinSchema', () => {+ it('accepts a full pin, a partial pin, and per-field nulls', () => {+ expect(llmRoutePinSchema.safeParse({ providerId: 'claude', model: 'opus', effort: 'high' }).success).toBe(true);+ expect(llmRoutePinSchema.safeParse({ providerId: 'claude' }).success).toBe(true);+ expect(llmRoutePinSchema.safeParse({ providerId: null, model: null, effort: null }).success).toBe(true);+ expect(llmRoutePinSchema.safeParse({}).success).toBe(true);+ });++ it('rejects an effort outside the shared ladder rather than letting the runner clamp it', () => {+ expect(llmRoutePinSchema.safeParse({ effort: 'turbo' }).success).toBe(false);+ });++ it('rejects an over-length provider or model id', () => {+ expect(llmRoutePinSchema.safeParse({ providerId: 'p'.repeat(500) }).success).toBe(false);+ expect(llmRoutePinSchema.safeParse({ model: 'm'.repeat(500) }).success).toBe(false);+ });+});++describe('resolveLlmRoutePin', () => {+ const pin = { providerId: 'claude', model: 'opus', effort: 'high' };++ it('falls back to the whole pin when the call names nothing', () => {+ expect(resolveLlmRoutePin(pin)).toEqual({ ...pin, providerMatchesPin: true });+ expect(resolveLlmRoutePin(pin, {})).toEqual({ ...pin, providerMatchesPin: true });+ });++ it('inherits the pinned model and effort when the call names the pinned provider', () => {+ expect(resolveLlmRoutePin(pin, { providerId: 'claude' })).toEqual({ ...pin, providerMatchesPin: true });+ });++ it('drops the pinned model and effort when the call switches provider', () => {+ expect(resolveLlmRoutePin(pin, { providerId: 'codex' })).toEqual({+ providerId: 'codex',+ model: null,+ effort: null,+ providerMatchesPin: false,+ });+ });++ it('honors an explicit per-call model and effort across a provider switch', () => {+ expect(resolveLlmRoutePin(pin, { providerId: 'codex', model: 'gpt-x', effort: 'low' })).toEqual({+ providerId: 'codex',+ model: 'gpt-x',+ effort: 'low',+ providerMatchesPin: false,+ });+ });++ it('lets a per-call pick beat the pin on one dimension while inheriting the rest', () => {+ expect(resolveLlmRoutePin(pin, { model: 'sonnet' })).toEqual({+ providerId: 'claude',+ model: 'sonnet',+ effort: 'high',+ providerMatchesPin: true,+ });+ });++ it('tolerates a missing pin', () => {+ expect(resolveLlmRoutePin(null, { providerId: 'codex' })).toEqual({+ providerId: 'codex',+ model: null,+ effort: null,+ providerMatchesPin: false,+ });+ expect(resolveLlmRoutePin(undefined)).toEqual({+ providerId: null,+ model: null,+ effort: null,+ providerMatchesPin: true,+ });+ });+});diff --git a/server/lib/seriesLlmOverride.js b/server/lib/seriesLlmOverride.jsindex 4d71acef31..3c024b225e 100644--- a/server/lib/seriesLlmOverride.js+++ b/server/lib/seriesLlmOverride.js@@ -4,14 +4,14 @@// extract-scenes, season-episodes-generate) honors the provider/model picked// in the series header instead of the global active provider.//-// A model id is provider-specific, so the series model is only inherited when-// the EFFECTIVE provider is still the series provider. An override that-// switches providers without naming a model leaves the model blank, so the new-// provider's default resolves rather than forwarding a foreign model id that-// would fail.-//-// Returns `undefined` (not `''`) for an unresolved provider/model so callers-// can pass the result straight through to the extractor without re-mapping.+// The never-cross-providers rule this rests on lives in `llmRoutePin.js`: a+// model id belongs to the provider it was picked for, so the series model is+// only inherited while the EFFECTIVE provider is still the series provider.+// This module is the series-shaped adapter over it — `series.llm` spells the+// pin `{ provider, model }` and callers want `undefined` (not `null`) for an+// unresolved field so the result passes straight through to the extractor.++import { resolveLlmRoutePin } from './llmRoutePin.js';/*** Resolve the effective LLM provider/model for a Pipeline action against a series.@@ -21,12 +21,13 @@* @returns {{ provider: string|undefined, model: string|undefined, providerMatchesSeries: boolean }}*/export function resolveSeriesLlmOverride(series, { overrideProvider, overrideModel } = {}) {- const seriesProvider = series?.llm?.provider || '';- const provider = overrideProvider || seriesProvider || undefined;- // No override means we're using the series provider, so the series model is- // always safe to inherit; an override matches only when it names the same- // provider the series model belongs to.- const providerMatchesSeries = !overrideProvider || overrideProvider === seriesProvider;- const model = overrideModel || (providerMatchesSeries ? series?.llm?.model : undefined) || undefined;- return { provider, model, providerMatchesSeries };+ const { providerId, model, providerMatchesPin } = resolveLlmRoutePin(+ { providerId: series?.llm?.provider, model: series?.llm?.model },+ { providerId: overrideProvider, model: overrideModel },+ );+ return {+ provider: providerId ?? undefined,+ model: model ?? undefined,+ providerMatchesSeries: providerMatchesPin,+ };}diff --git a/server/services/fableLoom/limits.js b/server/services/fableLoom/limits.jsindex 7e5e51b86c..35f47e9876 100644--- a/server/services/fableLoom/limits.js+++ b/server/services/fableLoom/limits.js@@ -24,7 +24,4 @@ export const LOOM_LIMITS = Object.freeze({TRIGGER_MAX: 160,TRIGGERS_MAX: 8,TRANSITION_DESC_MAX: 500,- PROVIDER_ID_MAX: 100,- MODEL_ID_MAX: 200,- EFFORT_MAX: 20,});diff --git a/server/services/fableLoom/records.js b/server/services/fableLoom/records.jsindex 8fec98f1bb..982ace0954 100644--- a/server/services/fableLoom/records.js+++ b/server/services/fableLoom/records.js@@ -13,6 +13,7 @@import { randomUUID } from 'crypto';import { ServerError } from '../../lib/errorHandler.js';import { isStr, trimTo } from '../../lib/storyBible.js';+import { sanitizeLlmRoutePin } from '../../lib/llmRoutePin.js';import { getUniverse } from '../universeBuilder.js';import { getSeries } from '../pipeline/series.js';import {@@ -33,24 +34,6 @@ const isSafeImageFilename = (value) =>const nullableRef = (value) => (isStr(value) && value.trim() ? value.trim().slice(0, LOOM_LIMITS.REF_ID_MAX) : null);-/**- * The loom's pinned routing for the play stage — which provider/model/effort- * turns a reader's free text into a path. Stored as a whole object so an- * unset dimension stays unset (null = "fall through to the stage pin / active- * provider"), rather than collapsing to an empty string that would read as a- * deliberate choice downstream.- */-const sanitizePlaySettings = (raw) => {- if (!raw || typeof raw !== 'object') return null;- const pick = (value, max) => trimTo(value, max) || null;- const settings = {- providerId: pick(raw.providerId, LOOM_LIMITS.PROVIDER_ID_MAX),- model: pick(raw.model, LOOM_LIMITS.MODEL_ID_MAX),- effort: pick(raw.effort, LOOM_LIMITS.EFFORT_MAX),- };- return Object.values(settings).some(Boolean) ? settings : null;-};-const sanitizePos = (raw) => (raw && typeof raw === 'object'&& Number.isFinite(raw.x) && Number.isFinite(raw.y)? { x: Math.round(raw.x), y: Math.round(raw.y) }@@ -135,7 +118,10 @@ export function sanitizeLoom(raw) {premise: trimTo(raw.premise, LOOM_LIMITS.PREMISE_MAX),styleNotes: trimTo(raw.styleNotes, LOOM_LIMITS.STYLE_NOTES_MAX),format: asLoomFormat(raw.format),- playSettings: sanitizePlaySettings(raw.playSettings),+ // The loom's route pin for the play stage — which provider/model/effort+ // turns a reader's free text into a path. An unset dimension stays null+ // ('fall through to the stage pin / active provider').+ playSettings: sanitizeLlmRoutePin(raw.playSettings),universeId: nullableRef(raw.universeId),seriesId: nullableRef(raw.seriesId),episodes: (Array.isArray(raw.episodes) ? raw.episodes : [])diff --git a/server/services/fableLoom/weave.js b/server/services/fableLoom/weave.jsindex bc0cba995c..c9f7116643 100644--- a/server/services/fableLoom/weave.js+++ b/server/services/fableLoom/weave.js@@ -16,6 +16,7 @@ import { randomUUID } from 'crypto';import { ServerError } from '../../lib/errorHandler.js';import { runStagedLLM } from '../../lib/stageRunner.js';import { isStr, trimTo } from '../../lib/storyBible.js';+import { resolveLlmRoutePin } from '../../lib/llmRoutePin.js';import { renderCanonForPrompt } from '../../lib/universePromptRenderers.js';import { analyzeEpisodeGraph, describeGraphForPrompt } from '../../lib/fableLoomGraph.js';import { getUniverse } from '../universeBuilder.js';@@ -50,22 +51,11 @@ const llmOptions = ({ providerId, model, effort } = {}, source) => ({* overrides deliberately — the author chose this narrator for this story, so* it outranks a global stage pin the same way a per-call pick does.*- * A model id and an effort level are both provider-specific, so the loom's are- * inherited only while the EFFECTIVE provider is still the one they were- * picked for. A per-call override that switches providers without naming its- * own falls through to the new provider's defaults rather than forwarding a- * foreign model id that would fail — the same rule as- * `resolveSeriesLlmOverride` (server/lib/seriesLlmOverride.js).+ * The never-cross-providers rule (a pinned model/effort is inherited only+ * while the effective provider still matches) comes from the shared resolver+ * in `server/lib/llmRoutePin.js`.*/-const playRouting = (loom, { providerId, model, effort } = {}) => {- const pinned = loom.playSettings || {};- const inherits = !providerId || providerId === pinned.providerId;- return {- providerId: providerId || pinned.providerId || null,- model: model || (inherits ? pinned.model : null) || null,- effort: effort || (inherits ? pinned.effort : null) || null,- };-};+const playRouting = (loom, perCall) => resolveLlmRoutePin(loom.playSettings, perCall);/*** Render the linked universe's canon as a prompt digest via the shared