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
feat: pipeline readers resolve canon from linked universe (Phase B)
[._.]/ Adam Eivy2b7c4b50eba1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 374c9d159b..9fcea7add2 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -187,6 +187,30 @@## Changed+- **Pipeline render paths read canon from the linked universe (Phase B).**+ Comic-page, panel, storyboard, and arc-planner LLM contexts now resolve+ characters/places/objects via `getSeriesCanon(series)` — preferring the+ series's linked universe canon and falling back to the series's own arrays+ only when the universe isn't migrated yet. Switching the source of truth+ to the universe is the prerequisite for crossover series sharing a cast.++ Migration utility: `node server/services/pipeline/migrateSeriesCanon.js`+ (optional `--dry-run`) copies each series's+ `series.{characters,settings,objects}[]` into its linked universe via+ `mergeExtractedBible` (dedup by name). Idempotent. Auto-creates a+ universe for orphan series. Does NOT clear the series arrays — they stay+ as a pre-migration fallback until Phase B.2 drops the schema fields.++ Fallback is **all-or-nothing per series**: if a series has any kind+ populated locally that the universe hasn't received yet, we read the+ whole series-side canon (rather than mixing universe characters with+ series settings and producing silent hybrid stale data).++ Phase B.2 (next): point the per-issue Nouns page directly at universe+ canon, remove series-side bible arrays from the schema, drop the+ legacy `extractAndMergeIntoSeries` + `refineCharacterDescription`+ functions.+- **BREAKING — World Builder is now Universe Builder.** A universe can containmany worlds, and stories within the same universe can share canon (characters,places, things) across multiple series — Marvel-style crossovers. This is adiff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex 5bd17788b1..80ce5bd25b 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -399,7 +399,13 @@ router.post('/series/:id/extract-bible', asyncHandler(async (req, res) => {}// Delegate the extract → merge → patch chain to the service layer so- // mergeExtractedBible stays a service-internal concern.+ // mergeExtractedBible stays a service-internal concern. (Phase B note:+ // this still writes into series.characters; the per-issue Nouns page+ // reads from there. Render paths prefer universe canon via+ // getSeriesCanon — so once the user runs migrateSeriesCanon and starts+ // managing canon on the Universe Canon page, this legacy series-write+ // becomes dead-end data. Removed in Phase B.2 when the Nouns page+ // points at universe directly.)const result = await seriesSvc.extractAndMergeIntoSeries(series.id, {kinds: body.kinds,corpus,diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.jsindex f64a25364f..4b0073108b 100644--- a/server/services/pipeline/arcPlanner.js+++ b/server/services/pipeline/arcPlanner.js@@ -26,6 +26,7 @@ import { listIssues } from './issues.js';import { sanitizeArc, sanitizeSeasonList, sanitizeSeason, buildSeason } from '../../lib/storyArc.js';import { recommendStructure, describeStructure } from '../../lib/seasonStructure.js';import { getUniverse } from '../universeBuilder.js';+import { getSeriesCanon } from './seriesCanon.js';import { renderCategoriesForPrompt, renderCompositesForPrompt } from '../../lib/universePromptRenderers.js';export const ERR_VALIDATION = 'PIPELINE_ARC_VALIDATION';@@ -102,6 +103,7 @@ async function resolveWorldContext(series, preloaded) {async function buildArcOverviewContext(series, preloadedWorld) {const structure = recommendStructure(series.issueCountTarget);const world = await resolveWorldContext(series, preloadedWorld);+ const canon = await getSeriesCanon(series);return {series: {name: series.name,@@ -116,9 +118,9 @@ async function buildArcOverviewContext(series, preloadedWorld) {: '(no target episode count set — propose 1–3 volumes based on premise weight)',recommendedSeasonCount: structure ? structure.seasons : '',recommendedPerSeasonJson: structure ? JSON.stringify(structure.perSeason) : '[]',- existingCharactersJson: JSON.stringify(series.characters || [], null, 2),- existingSettingsJson: JSON.stringify(series.settings || [], null, 2),- existingObjectsJson: JSON.stringify(series.objects || [], null, 2),+ existingCharactersJson: JSON.stringify(canon.characters, null, 2),+ existingSettingsJson: JSON.stringify(canon.settings, null, 2),+ existingObjectsJson: JSON.stringify(canon.objects, null, 2),};}@@ -190,6 +192,7 @@ async function buildSeasonEpisodesContext(series, season, priorSeasons, priorIss? '(this is the first season — no prior context)': priorSeasons.map((s) => renderPriorSeason(s, priorIssues)).join('\n\n');const world = await resolveWorldContext(series, preloadedWorld);+ const canon = await getSeriesCanon(series);return {series: {name: series.name,@@ -212,9 +215,9 @@ async function buildSeasonEpisodesContext(series, season, priorSeasons, priorIssendingHook: season.endingHook,episodeCountTarget: season.episodeCountTarget,},- existingCharactersJson: JSON.stringify(series.characters || [], null, 2),- existingSettingsJson: JSON.stringify(series.settings || [], null, 2),- existingObjectsJson: JSON.stringify(series.objects || [], null, 2),+ existingCharactersJson: JSON.stringify(canon.characters, null, 2),+ existingSettingsJson: JSON.stringify(canon.settings, null, 2),+ existingObjectsJson: JSON.stringify(canon.objects, null, 2),};}@@ -356,6 +359,7 @@ async function buildVerifyContext(series, preloadedWorld) {}const arc = series.arc || {};const world = await resolveWorldContext(series, preloadedWorld);+ const canon = await getSeriesCanon(series);return {series: {name: series.name,@@ -370,9 +374,9 @@ async function buildVerifyContext(series, preloadedWorld) {themesCsv: Array.isArray(arc.themes) ? arc.themes.join(', ') : '',},seasonsTreeJson: JSON.stringify(tree, null, 2),- existingCharactersJson: JSON.stringify(series.characters || [], null, 2),- existingSettingsJson: JSON.stringify(series.settings || [], null, 2),- existingObjectsJson: JSON.stringify(series.objects || [], null, 2),+ existingCharactersJson: JSON.stringify(canon.characters, null, 2),+ existingSettingsJson: JSON.stringify(canon.settings, null, 2),+ existingObjectsJson: JSON.stringify(canon.objects, null, 2),};}diff --git a/server/services/pipeline/migrateSeriesCanon.js b/server/services/pipeline/migrateSeriesCanon.jsnew file mode 100644index 0000000000..df9c0c6204--- /dev/null+++ b/server/services/pipeline/migrateSeriesCanon.js@@ -0,0 +1,97 @@+// One-shot migration: copy series.{characters,settings,objects} into the+// linked universe so Phase B readers (which prefer universe canon) have data+// to read. Idempotent — re-running merges by name without creating dupes.+//+// Runs on demand via CLI: `node server/services/pipeline/migrateSeriesCanon.js`+// or programmatically from server boot if we ever auto-migrate.+//+// Does NOT clear the series's arrays. They stay as a fallback (and as the+// edit surface for the existing per-series UI) until Phase B.2 drops them.++import { listSeries, updateSeries } from './series.js';+import { getUniverse, createUniverse, updateUniverse } from '../universeBuilder.js';+import { mergeExtractedBible, BIBLE_FIELD } from '../../lib/storyBible.js';++// Reverse of BIBLE_FIELD — maps the persisted field name (`characters`) back+// to its BIBLE_KIND value (`character`) so the migration can call+// mergeExtractedBible per field. Sourcing this from BIBLE_FIELD keeps one+// source of truth: when a new kind lands in storyBible.js, this map updates+// automatically.+const KIND_BY_FIELD = Object.freeze(+ Object.fromEntries(Object.entries(BIBLE_FIELD).map(([kind, field]) => [field, kind])),+);++export async function migrateSeriesCanon({ dryRun = false, log = console.log } = {}) {+ const series = await listSeries();+ const summary = { seriesScanned: 0, seriesMigrated: 0, universesCreated: 0, perKind: { characters: 0, settings: 0, objects: 0 } };++ for (const s of series) {+ summary.seriesScanned += 1;+ const counts = {+ characters: Array.isArray(s.characters) ? s.characters.length : 0,+ settings: Array.isArray(s.settings) ? s.settings.length : 0,+ objects: Array.isArray(s.objects) ? s.objects.length : 0,+ };+ if (counts.characters + counts.settings + counts.objects === 0) continue;++ // Auto-create a universe for orphan series so the migration completes+ // without manual linking. Named after the series so the user can find it+ // and merge later if desired.+ let universeId = s.universeId;+ if (!universeId) {+ if (dryRun) {+ log(`📋 [dry-run] Would create universe for orphan series "${s.name}" (${s.id})`);+ } else {+ const newUniverse = await createUniverse({+ name: `${s.name} (auto-migrated)`,+ starterPrompt: s.logline || s.premise?.slice(0, 500) || '',+ stylePrompt: '',+ negativePrompt: '',+ });+ await updateSeries(s.id, { universeId: newUniverse.id });+ universeId = newUniverse.id;+ summary.universesCreated += 1;+ log(`🌌 Created universe "${newUniverse.name}" (${newUniverse.id}) for orphan series "${s.name}"`);+ }+ }++ const universe = await getUniverse(universeId).catch(() => null);+ if (!universe) {+ log(`⚠️ Series "${s.name}" links to missing universe ${universeId} — skipping`);+ continue;+ }++ const patch = {};+ for (const [field, kind] of Object.entries(KIND_BY_FIELD)) {+ const incoming = Array.isArray(s[field]) ? s[field] : [];+ if (incoming.length === 0) continue;+ const merged = mergeExtractedBible(universe[field] || [], incoming, kind);+ // Skip the write when merge produced no new entries (idempotency).+ if (merged.length > (universe[field] || []).length || JSON.stringify(merged) !== JSON.stringify(universe[field] || [])) {+ patch[field] = merged;+ summary.perKind[field] += incoming.length;+ }+ }++ if (Object.keys(patch).length > 0) {+ if (dryRun) {+ log(`📋 [dry-run] Would merge into universe "${universe.name}": ${Object.entries(counts).map(([k, n]) => `${n} ${k}`).join(', ')} from series "${s.name}"`);+ } else {+ await updateUniverse(universeId, patch);+ summary.seriesMigrated += 1;+ log(`✅ Migrated series "${s.name}" → universe "${universe.name}": ${Object.entries(counts).map(([k, n]) => `${n} ${k}`).join(', ')}`);+ }+ }+ }++ log(`📊 Migration complete: scanned ${summary.seriesScanned} series, migrated ${summary.seriesMigrated}, created ${summary.universesCreated} universe(s)`);+ return summary;+}++// CLI entrypoint: `node server/services/pipeline/migrateSeriesCanon.js [--dry-run]`+if (import.meta.url === `file://${process.argv[1]}`) {+ const dryRun = process.argv.includes('--dry-run');+ migrateSeriesCanon({ dryRun })+ .then(() => process.exit(0))+ .catch((err) => { console.error('❌ Migration failed:', err); process.exit(1); });+}diff --git a/server/services/pipeline/seriesCanon.js b/server/services/pipeline/seriesCanon.jsnew file mode 100644index 0000000000..4e3139dab6--- /dev/null+++ b/server/services/pipeline/seriesCanon.js@@ -0,0 +1,85 @@+// Resolves a series's canon (characters, settings, objects) from the linked+// universe — Phase B of the Universe-as-canon refactor. Before B, each series+// owned its own bible arrays; now canon lives on the universe so multiple+// series can share a cast. The series's own arrays stay populated as a+// fallback for series with no universe link AND for orphan series that+// haven't migrated yet.++import { getUniverse } from '../universeBuilder.js';++/**+ * Read a series's effective canon. Prefers the linked universe; falls back to+ * the series's own arrays when the universe is unset, missing, or empty.+ *+ * The dual-path read makes the migration non-blocking: render paths produce+ * correct results before AND after the one-shot copy in `migrateSeriesCanon`.+ * Once every series's canon lives on its universe, the fallback becomes dead+ * weight and the series.{characters,settings,objects} fields can be dropped+ * from the schema (Phase B.2).+ *+ * @returns {Promise<{ characters, settings, objects, source: 'universe' | 'series' }>}+ */+export async function getSeriesCanon(series) {+ const empty = { characters: [], settings: [], objects: [] };+ if (!series || typeof series !== 'object') return { ...empty, source: 'series' };++ if (series.universeId) {+ const universe = await getUniverse(series.universeId).catch(() => null);+ if (universe) {+ const resolved = pickAllOrNothing(universe, series);+ if (resolved) return resolved;+ }+ }+ return {+ characters: Array.isArray(series.characters) ? series.characters : [],+ settings: Array.isArray(series.settings) ? series.settings : [],+ objects: Array.isArray(series.objects) ? series.objects : [],+ source: 'series',+ };+}++// All-or-nothing: only treat the universe as the source when it has all+// three kinds populated. A half-migrated universe (only characters+// extracted, settings still on series) would otherwise silently mix+// stores — readers can't tell they're getting hybrid canon, and the user+// thinks they've fully migrated. Returning null here forces pure-series+// fallback, which keeps the migration state explicit: either the universe+// is complete or it isn't.+function pickAllOrNothing(universe, series) {+ const characters = Array.isArray(universe.characters) ? universe.characters : [];+ const settings = Array.isArray(universe.settings) ? universe.settings : [];+ const objects = Array.isArray(universe.objects) ? universe.objects : [];+ // If the series never populated a kind to begin with (empty on both+ // sides), don't require it from the universe either.+ const seriesC = Array.isArray(series?.characters) ? series.characters : [];+ const seriesS = Array.isArray(series?.settings) ? series.settings : [];+ const seriesO = Array.isArray(series?.objects) ? series.objects : [];+ const wantsCharacters = seriesC.length > 0;+ const wantsSettings = seriesS.length > 0;+ const wantsObjects = seriesO.length > 0;+ const universeCovers =+ (!wantsCharacters || characters.length > 0)+ && (!wantsSettings || settings.length > 0)+ && (!wantsObjects || objects.length > 0)+ && (characters.length + settings.length + objects.length > 0);+ if (!universeCovers) return null;+ return { characters, settings, objects, source: 'universe' };+}++/**+ * Synchronous variant for hot render paths that already have the universe+ * record in hand (e.g. visualStages.js loads it via getUniverse anyway).+ * Mirrors the per-kind fallback logic in `getSeriesCanon`.+ */+export function resolveSeriesCanonSync(series, universe) {+ if (universe) {+ const resolved = pickAllOrNothing(universe, series);+ if (resolved) return resolved;+ }+ return {+ characters: Array.isArray(series?.characters) ? series.characters : [],+ settings: Array.isArray(series?.settings) ? series.settings : [],+ objects: Array.isArray(series?.objects) ? series.objects : [],+ source: 'series',+ };+}diff --git a/server/services/pipeline/textStages.js b/server/services/pipeline/textStages.jsindex fee115b892..ea53063ae4 100644--- a/server/services/pipeline/textStages.js+++ b/server/services/pipeline/textStages.js@@ -17,6 +17,7 @@import { runStagedLLM } from '../../lib/stageRunner.js';import { getSeries, extractAndMergeIntoSeries } from './series.js';import { getIssue, updateStage, TEXT_STAGE_IDS } from './issues.js';+import { getSeriesCanon } from './seriesCanon.js';const STAGE_TO_TEMPLATE = Object.freeze({idea: 'pipeline-idea-expansion',@@ -30,7 +31,7 @@ const STAGE_TO_TEMPLATE = Object.freeze({* bible (`series.*`) and every *prior* text stage's content (`stages.*`).* Visual stages aren't included — text templates don't need rendered images.*/-function buildStageContext({ series, issue, stageId, seedInput }) {+function buildStageContext({ series, canon, issue, stageId, seedInput }) {const stages = {};for (const id of TEXT_STAGE_IDS) {if (id === stageId) break; // only include stages BEFORE the current one@@ -49,7 +50,7 @@ function buildStageContext({ series, issue, stageId, seedInput }) {premise: series.premise,styleNotes: series.styleNotes,universeId: series.universeId || '',- characters: series.characters || [],+ characters: canon?.characters || series.characters || [],},issue: {number: issue.number,@@ -79,10 +80,11 @@ export async function generateStage(issueId, stageId, options = {}) {const template = STAGE_TO_TEMPLATE[stageId];const issue = await getIssue(issueId);const series = await getSeries(issue.seriesId);+ const canon = await getSeriesCanon(series);await updateStage(issueId, stageId, { status: 'generating', errorMessage: '' });- const ctx = buildStageContext({ series, issue, stageId, seedInput: options.seedInput });+ const ctx = buildStageContext({ series, canon, issue, stageId, seedInput: options.seedInput });// Catch only at this boundary so the stage record persists the failure// before the error bubbles to the caller — without this, an LLM throwdiff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.jsindex 9599e77466..ef961c928c 100644--- a/server/services/pipeline/visualStages.js+++ b/server/services/pipeline/visualStages.js@@ -38,6 +38,7 @@ import { composeStyledPrompt } from '../../lib/composeStyledPrompt.js';import { getDefaultVideoModelId, getVideoModels } from '../../lib/mediaModels.js';import { runStagedLLM } from '../../lib/stageRunner.js';import { runPromptRefine } from './refineHelpers.js';+import { resolveSeriesCanonSync } from './seriesCanon.js';import { ASPECT_PRESETS } from '../../lib/creativeDirectorPresets.js';const SUPPORTED_MODES = new Set(['local', 'codex']);@@ -61,7 +62,10 @@ const loadBibleContext = async (issueId) => {const issue = await getIssue(issueId);const series = await getSeries(issue.seriesId);const world = series.universeId ? await getUniverse(series.universeId).catch(() => null) : null;- return { issue, series, world };+ // Canon prefers the linked universe (Phase B) and falls back to the+ // series's own arrays so pre-migration data still renders correctly.+ const canon = resolveSeriesCanonSync(series, world);+ return { issue, series, world, canon };})();const [chain, settings] = await Promise.all([issueChain, getSettings()]);return { ...chain, settings };@@ -253,7 +257,7 @@ export async function enqueueVisualComicPage(issueId, options = {}) {status: 400, code: 'PIPELINE_COMIC_PAGE_BAD_INDEX',});}- const { issue, settings, series, world } = await loadBibleContext(issueId);+ const { issue, settings, series, world, canon } = await loadBibleContext(issueId);const pages = Array.isArray(issue.stages?.comicPages?.pages) ? issue.stages.comicPages.pages : [];const page = pages[pageIndex];if (!page) {@@ -281,10 +285,12 @@ export async function enqueueVisualComicPage(issueId, options = {}) {);// Characters: union of (a) dialogue CAPS speakers and (b) anyone named in- // panel prose. Deduplicates on id/name inside the matchers.- const charByKey = buildCharByKey(series.characters || []);+ // panel prose. Deduplicates on id/name inside the matchers. Canon is read+ // from `canon` (Phase B helper) which prefers the linked universe and+ // falls back to series arrays for pre-migration data.+ const charByKey = buildCharByKey(canon.characters);const fromDialogue = matchSceneCharacters(dialogueNames, charByKey);- const fromProse = matchCharactersInText(proseHaystack, series.characters || []);+ const fromProse = matchCharactersInText(proseHaystack, canon.characters);const seenCharKeys = new Set();const matchedCharacters = [...fromDialogue, ...fromProse].filter((c) => {const k = c.id || c.name;@@ -296,8 +302,8 @@ export async function enqueueVisualComicPage(issueId, options = {}) {// Settings + objects: text-match against the panel prose. Codex can't take// reference images, so rich text descriptions in the prompt are how we// keep environments and signature props visually consistent page-to-page.- const matchedSettings = matchSettingsInText(proseHaystack, series.settings || []);- const matchedObjects = matchObjectsInText(proseHaystack, series.objects || []);+ const matchedSettings = matchSettingsInText(proseHaystack, canon.settings);+ const matchedObjects = matchObjectsInText(proseHaystack, canon.objects);// composeComicPagePrompt only returns '' when panels.length === 0, which is// already rejected above. The "(continuation of previous beat)" placeholder@@ -328,9 +334,9 @@ export async function enqueueVisualImage(issueId, stageId, options = {}) {status: 400, code: 'PIPELINE_VISUAL_BAD_STAGE',});}- const { settings, series, world } = await loadBibleContext(issueId);+ const { settings, series, world, canon } = await loadBibleContext(issueId);const mode = resolveMode(options, settings);- const matchedCharacters = matchCharactersInText(options.description || '', series.characters || []);+ const matchedCharacters = matchCharactersInText(options.description || '', canon.characters);const prompt = composeVisualPrompt({series,description: options.description,@@ -371,7 +377,7 @@ export async function enqueueStoryboardSceneVideo(issueId, sceneIndex, options =status: 400, code: 'PIPELINE_SCENE_BAD_INDEX',});}- const { issue, settings, series, world } = await loadBibleContext(issueId);+ const { issue, settings, series, world, canon } = await loadBibleContext(issueId);const pythonPath = settings.imageGen?.local?.pythonPath || null;if (!pythonPath) {throw new ServerError(@@ -396,7 +402,7 @@ export async function enqueueStoryboardSceneVideo(issueId, sceneIndex, options =const matchedCharacters = matchCharactersInText(`${scene.description || ''} ${scene.slugline || ''}`,- series.characters || [],+ canon.characters,);const prompt = composeVisualPrompt({series,