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-canon): Phase B.4 schema teardown

[._.]/ Adam Eivy726adb12376b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 4acc077ae0..b9b88affb6 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -12,6 +12,7 @@
## Changed
- **DONE.md condensed to feature-level summaries.** Dropped file paths, LOC counts, and test counts from the per-date entries; grouped by month with one-line bullets so an LLM can scan completed capabilities without drowning in implementation specifics. Per-release `.changelog/v*.md` files remain the source of truth for the rich details.
+- **Universe-as-Canon — Phase B.4 schema teardown.** Series records no longer carry `characters` / `settings` / `objects` arrays — canon lives exclusively on the linked universe (Phase B.4 of the Universe-as-canon refactor). Sanitizer, Zod `seriesCreateSchema` / `seriesPatchSchema`, and the universe-canon resolver (`services/pipeline/seriesCanon.js`) all drop their series-side fallback paths; the legacy helpers `extractAndMergeIntoSeries`, `refineCharacterDescription` (and the `nounRefine.js` module), and `purgeImageRefFromAllSeries` are removed alongside the routes `POST /pipeline/series/:id/extract-bible` and `POST /pipeline/series/:id/characters/:entryId/refine`. Post-prose bible extraction (`textStages.js`) and storyboard scene extraction (`routes/pipeline.js`) now flow through `extractCanonFromProse` / `getSeriesCanon` against the linked universe, and the image-delete `purgeImageRefFromAll{Series→Universes}` scan was collapsed to the universe side only. Writers Room `promoteWorkToPipeline` mints a fresh universe per work and seeds it with the work's bibles instead of writing them onto the series; `POST /api/universe-builder` now accepts `characters` / `settings` / `objects` on the create-schema so promote + tests + the share-bucket importer can seed canon at creation. Voice-resolution + dialogue extraction in `audio.js` (`resolveVoiceForLine`, `extractDialogueLines`) now take canon-shaped objects (`{ characters }`) so the route can pass universe canon through `getSeriesCanon`. Stale clients sending the old canon fields on series PATCH/POST get a silent strip server-side rather than a 400. Test fixtures across `series.test.js`, `pipeline.test.js`, `promoteToPipeline.test.js`, and `sharing/integration.test.js` were updated to seed canon on a linked universe.
- **Pipeline series arc — inline theme editing.** Theme pills on the Series Arc card are now directly editable: click a pill to rename, hover for the × to remove, click the dashed "+ Add theme" chip to append (up to 20 themes, 100 chars each — matching `ARC_LIMITS` on the server). Writes are optimistic with a single-flight save gate so a blur-then-click sequence can't double-persist against stale state. The redundant comma-separated themes input was removed from the "Edit arc" form; logline / summary / protagonist arc / shape still live there.
- **Universe Builder — unify style/negative prompts with the embrace/avoid chip editor.** The prose `stylePrompt` and `negativePrompt` textareas have been removed; the universe's style + negative prompts now live as draggable token lists in `influences.embrace` / `influences.avoid` and are the single editing surface (relabeled in the UI as "Style prompt (embrace)" and "Negative prompt (avoid)"). The renderer joins each list verbatim into the rendered prompt the same way the prose fields used to compose. Existing universes auto-migrate on first read: prose tokens are split on commas, deduped case-insensitively against any pre-existing chips, capped at 30 per list, and persisted (`schemaVersion` bumped to 3). The LLM expand + refine flows now emit `influences` only — no more separate `stylePrompt`/`negativePrompt` keys. Stale-client PATCH payloads still carrying prose fields are absorbed into the chip lists server-side so a stale browser tab doesn't 400.
diff --git a/PLAN.md b/PLAN.md
index 2f85b7685f..e09ccaff48 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -36,23 +36,14 @@ New on-ramp to the Create pipeline. User pastes a short story / novel / screenpl
The world model is now a Marvel-style **universe** carrying canonical entities (characters, places, objects) that multiple series can share for crossovers + cameos. Shipped 2026-05-14 across Phase 0 (world→universe rename), Phase A (canon arrays + Universe Canon page + cast-wide differentiate + image-delete purge sync), Phase B (render paths read via `getSeriesCanon`), Phase B.2 (Nouns page reads/writes universe canon), Phase B.3a (legacy series-side canon helpers redirect to universe when linked), Phase B.3b (Nouns page drops the orphan series fallback), and the "Appears in" cross-reference footer on every Canon card. Migration scripts: `server/scripts/migrateAll.js` (chains `migrateWorldToUniverse.js` + `migrateSeriesCanon.js`).
-**Phase B.4 — schema teardown (hygiene, no functional gap).** After B.3, `series.{characters,settings,objects}` are dormant — render paths read from universe, the Nouns page writes to universe, and the legacy server functions redirect to universe-side. The series arrays linger only to satisfy tests + the writers-room promotion flow.
+**Phase B.4 — schema teardown (hygiene, no functional gap).** Shipped 2026-05-16 — `series.{characters,settings,objects}` are gone from sanitizer + Zod schemas; `extractAndMergeIntoSeries` / `refineCharacterDescription` (and `nounRefine.js`) / `purgeImageRefFromAllSeries` deleted; routes `POST /pipeline/series/:id/extract-bible` + `POST /pipeline/series/:id/characters/:entryId/refine` removed; Writers Room `promoteWorkToPipeline` mints a universe per work and seeds canon there; `seriesCanon.js` simplified to universe-or-empty (`pickAllOrNothing` + `resolveSeriesCanonSync` removed); voice + dialogue extraction in `audio.js` rebased onto canon-shaped params; storyboard `extract-scenes` route reads canon via `getSeriesCanon`; post-prose extraction (`textStages.js`) calls `extractCanonFromProse(universeId)`. Test fixtures across `series.test.js`, `pipeline.test.js`, `promoteToPipeline.test.js`, `sharing/integration.test.js` updated to seed canon on a linked universe. See NEXT.md.
-- [ ] Drop `series.{characters,settings,objects}` from `sanitizeSeries` + `createSeries`/`updateSeries` + `seriesCreateSchema`/`seriesPatchSchema` Zod (in `server/routes/pipeline.js`). Tests that put canon on series in fixtures need updating: `series.test.js`, `textStages.test.js`, `visualStages.test.js`, `arcPlanner.test.js`, `pipeline.test.js`, `promoteToPipeline.test.js`, and `sceneExtractor.test.js`.
-- [ ] Refactor `services/writersRoom/promoteToPipeline` to create a universe alongside the series (or pick an existing universe), then merge writers-room canon into the universe instead of writing to `series.characters`. Currently the only path that legitimately writes series-side canon. Update `promoteToPipeline.test.js` accordingly.
-- [ ] Delete `extractAndMergeIntoSeries`, `refineCharacterDescription` (and the `nounRefine.js` file), `purgeImageRefFromAllSeries`, and the routes `POST /pipeline/series/:id/extract-bible` + `POST /pipeline/series/:id/characters/:entryId/refine`. Remove the corresponding test blocks. Update `routes/imageGen.js` to drop the series-side purge (universe-side covers everything once canon is universe-only).
-- [ ] Simplify `services/pipeline/seriesCanon.js` — once series arrays are gone, the all-or-nothing fallback becomes "return universe-or-empty"; drop `pickAllOrNothing` and the `resolveSeriesCanonSync` sync variant (only one caller; inline it).
+**Universe-Canon UX follow-ups.** Shipped 2026-05-16 — per-series filter dropdown on Universe Canon page (`?series=<id>` URL param), "Appears in" list sorted by `issueCount` desc, per-series `stylePromptOverride` field wired through `applyWorldStyle` + NounsStage client previews. See NEXT.md.
**Settings → Places kind rename (Phase 0b — deferred during the Universe rename).**
- [ ] Rename `BIBLE_KIND.SETTING` → `BIBLE_KIND.PLACE` and `BIBLE_FIELD[SETTING]: 'settings'` → `'places'`. Touches ~20 files: data (`series.places[]` / `universe.places[]`), sanitizer + Zod schemas, the `writers-room-settings.md` prompt (already renamed file; prompt body still refers to "settings"), `matchSettingsInText` → `matchPlacesInText`, `existingSettingsJson` LLM template var, the `writersRoom/settings.js` bible-handler module + its per-work data files, NounsStage's `KIND.label === 'Settings'`. Stick the rename to bible context — app settings (`services/settings.js`, settings drawer/UI, `imageGen.settings`, `pipeline.settings`) stays as "settings".
-**Universe-Canon UX follow-ups (small, contained).**
-
-- [ ] Sort the per-entry "Appears in" usage list by `issueCount` descending so the most-used series leads. Today renders in encounter order — fine with one series, useful when 2+ link. Touch site: `server/services/canonUsage.js` (the `shape` builder near the bottom).
-- [ ] Filter the Universe Canon page by "in series X" — when one universe holds multiple shows, the user wants to see only canon that's relevant to the show they're working on. New URL param `?series=<id>` + a series picker dropdown in the header. Reuses the existing `canonUsage` to derive the per-series subset.
-- [ ] Per-series `stylePrompt` override — let one series in a universe deviate slightly without forking the whole universe (e.g., noir spin-off). Wire `series.stylePromptOverride` into `composeStyledPrompt` ahead of the universe's stylePrompt; UI on the series page.
-
**Universe-as-Canon Phase 2 — unified Builder UI + categories retirement.**
The server-side lock + provenance + backfill foundation shipped 2026-05-14 (see NEXT.md). The UI still shows the legacy two-page split (Builder for categories/composites, separate Canon page for characters/settings/objects). Follow-up to land the user-visible piece:
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index 9eeee10271..f7d6803fab 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -3,7 +3,7 @@ import { buildFormData } from './apiImageVideo.js';
// Stage IDs mirror server/services/pipeline/issues.js — keep these in sync.
// `nouns` is a UI-only pseudo-stage: it has no server stage record + no LLM
-// template, and its actions wrap existing endpoints (extract-bible + the
+// template, and its actions wrap existing endpoints (extract scenes + the
// generic image gen API). It appears in PIPELINE_TAB_STAGES so it gets a tab
// between Prose and Comic Pages, but it's NOT in server TEXT_STAGE_IDS — so
// auto-run text chain skips it and POST /stages/nouns/generate would 400.
@@ -92,27 +92,6 @@ export const deletePipelineSeries = (id) => request(`/pipeline/series/${encodeUR
method: 'DELETE',
});
-// Extract bibles (characters / settings / objects) from an issue's prose
-// stage and merge them into the series. `kinds` defaults server-side to all
-// three. Pass `parallel: true` to fan out the kinds concurrently — ~3×
-// wall-clock speedup on HTTP-API providers (OpenAI / Anthropic / LM Studio
-// HTTP). Safe to leave off for CLI-only providers (codex / claude-code /
-// gemini-cli) which serialize at the provider session anyway.
-// Returns { series, results } where results is keyed by field name.
-export const extractPipelineBibles = (seriesId, { issueId, corpus, kinds, providerOverride, parallel } = {}) =>
- request(`/pipeline/series/${encodeURIComponent(seriesId)}/extract-bible`, {
- method: 'POST',
- body: JSON.stringify({ issueId, corpus, kinds, providerOverride, parallel }),
- });
-
-// Rewrite one character's physicalDescription so they render distinct from
-// every peer. Returns { series, entry, rationale, changes }.
-export const refinePipelineCharacter = (seriesId, entryId, { providerId, model } = {}) =>
- request(`/pipeline/series/${encodeURIComponent(seriesId)}/characters/${encodeURIComponent(entryId)}/refine`, {
- method: 'POST',
- body: JSON.stringify({ providerId, model }),
- });
-
// ---- Issues ----
export const listPipelineIssues = (seriesId) =>
request(`/pipeline/series/${encodeURIComponent(seriesId)}/issues`);
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index a80ae64295..734ec7f94b 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -35,7 +35,6 @@ import { join, basename, resolve as resolvePath, sep as PATH_SEP } from 'node:pa
import { readFile, writeFile } from 'fs/promises';
import { STYLE_PRESETS } from '../lib/writersRoomStylePresets.js';
import { cleanImageBuffer, CLEAN_LEVELS } from './imageClean.js';
-import { purgeImageRefFromAllSeries } from '../services/pipeline/series.js';
import { purgeImageRefFromAllUniverses } from '../services/universeCanon.js';
const router = Router();
@@ -321,26 +320,17 @@ router.post('/cancel', asyncHandler(async (req, res) => {
router.delete('/:filename', asyncHandler(async (req, res) => {
const result = await local.deleteImage(req.params.filename);
- // Sync both stores: pipeline series.characters/.settings/.objects[].imageRefs
- // AND universe.characters/.settings/.objects[].imageRefs. Both are scanned
- // because Phase A canon entities live on the universe; Phase B will collapse
- // these into one source. Best-effort: a purge failure must not block the
- // gallery delete itself.
- const [seriesPurge, universePurge] = await Promise.all([
- purgeImageRefFromAllSeries(req.params.filename).catch((err) => {
- console.warn(`⚠️ Pipeline ref purge failed for ${req.params.filename}: ${err?.message || err}`);
- return { removed: 0 };
- }),
- purgeImageRefFromAllUniverses(req.params.filename).catch((err) => {
- console.warn(`⚠️ Universe canon purge failed for ${req.params.filename}: ${err?.message || err}`);
- return { removed: 0 };
- }),
- ]);
- const totalRemoved = seriesPurge.removed + universePurge.removed;
- if (totalRemoved > 0) {
- console.log(`🧹 Purged ${totalRemoved} canon ref(s) for ${req.params.filename} (series=${seriesPurge.removed}, universe=${universePurge.removed})`);
+ // Sync universe canon — characters/settings/objects[].imageRefs on every
+ // universe is scanned and any reference to this filename is dropped.
+ // Best-effort: a purge failure must not block the gallery delete itself.
+ const universePurge = await purgeImageRefFromAllUniverses(req.params.filename).catch((err) => {
+ console.warn(`⚠️ Universe canon purge failed for ${req.params.filename}: ${err?.message || err}`);
+ return { removed: 0 };
+ });
+ if (universePurge.removed > 0) {
+ console.log(`🧹 Purged ${universePurge.removed} canon ref(s) for ${req.params.filename}`);
}
- res.json({ ...result, canonRefsRemoved: totalRemoved });
+ res.json({ ...result, canonRefsRemoved: universePurge.removed });
}));
router.post('/:filename/visibility', asyncHandler(async (req, res) => {
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index 200d237879..7e116c1eb2 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -27,9 +27,6 @@ import { z } from 'zod';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import {
validateRequest,
- characterBibleCreateSchema,
- settingBibleCreateSchema,
- objectBibleCreateSchema,
imageEdgeSchema,
refineImagePixelCap,
PIXEL_CAP_MESSAGE,
@@ -54,7 +51,8 @@ import {
refineStoryboardScenePrompt,
buildRenderSlot,
} from '../services/pipeline/visualStages.js';
-import { refineCharacterDescription } from '../services/pipeline/nounRefine.js';
+import { extractCanonFromProse } from '../services/universeCanon.js';
+import { getSeriesCanon } from '../services/pipeline/seriesCanon.js';
import { startEpisodeVideoForIssue, ERR_NO_STORYBOARDS } from '../services/pipeline/episodeVideo.js';
import { COMIC_PAGE_VARIANTS, slotKeyForVariant } from '../services/pipeline/owners.js';
import { ASPECT_RATIOS, QUALITIES } from '../lib/creativeDirectorPresets.js';
@@ -83,7 +81,6 @@ import {
CUSTOM_PAGE_MIN, CUSTOM_PAGE_MAX, CUSTOM_MINUTE_MIN, CUSTOM_MINUTE_MAX,
} from '../lib/issueLength.js';
import { llmSchema } from './universeBuilder.js';
-import { BIBLE_KIND } from '../lib/storyBible.js';
import { ARC_LIMITS, ARC_STATUSES, ARC_SHAPE_IDS, ARC_ROLES, SEASON_STATUSES } from '../lib/storyArc.js';
const router = Router();
@@ -110,34 +107,11 @@ const mapServiceError = (err) => {
};
// ---- Series schemas ----
-
-// Bible entry shape is owned by the canonical schemas in `server/lib/validation.js`
-// (re-exports of the Writers Room character/setting/object create-schemas). The
-// Pipeline extends them here with its own back-compat fields and uses
-// `.passthrough()` so canonical sanitizer-emitted fields (`evidence`,
-// `firstAppearance`, `source`, `createdAt`, `updatedAt`, `missingFromProse`)
-// round-trip cleanly when the client re-saves an existing series. Final
-// enforcement lives in the sanitizer in `server/lib/storyBible.js`.
-const characterSchema = characterBibleCreateSchema.extend({
- id: z.string().trim().max(80).optional(),
- // Back-compat: pre-DRY shape used `description`. Both fields are accepted
- // and the canonical sanitizer normalizes them to `physicalDescription`.
- description: z.string().trim().max(seriesSvc.CHARACTER_DESCRIPTION_MAX).optional(),
- // Pipeline-only image refs (not present on the writers-room shape).
- imageRefs: z.array(z.string().trim().min(1).max(seriesSvc.IMAGE_REF_MAX))
- .max(seriesSvc.IMAGE_REFS_PER_CHARACTER_MAX).optional(),
- // Pipeline preserves a looser `notes` cap (4000) than the writers-room
- // base (2000) — overriding here so user-facing limits don't tighten.
- notes: z.string().trim().max(4000).optional(),
-}).passthrough();
-
-const settingSchema = settingBibleCreateSchema.extend({
- id: z.string().trim().max(80).optional(),
-}).passthrough();
-
-const objectSchema = objectBibleCreateSchema.extend({
- id: z.string().trim().max(80).optional(),
-}).passthrough();
+//
+// Canon (characters / settings / objects) is no longer carried on a series
+// payload — it lives on the linked universe (Phase B.4). The bible-entry
+// Zod shapes (`characterSchema` et al.) and the `BIBLE_KIND` plumbing moved
+// out of this file when the series-side canon routes were retired.
// Visual style ref — `{ id, customPrompt? }`. The id is validated lazily
// (against the catalog in server/lib/visualStyles.js) by the sanitizer at
@@ -201,9 +175,6 @@ const seriesCreateSchema = z.object({
premise: z.string().trim().max(seriesSvc.PREMISE_MAX).optional().default(''),
universeId: z.string().trim().max(seriesSvc.UNIVERSE_ID_MAX).nullable().optional(),
writersRoomWorkId: z.string().trim().max(seriesSvc.WRITERS_ROOM_WORK_ID_MAX).nullable().optional(),
- characters: z.array(characterSchema).max(seriesSvc.BIBLE_ENTRIES_PER_SERIES_MAX).optional(),
- settings: z.array(settingSchema).max(seriesSvc.BIBLE_ENTRIES_PER_SERIES_MAX).optional(),
- objects: z.array(objectSchema).max(seriesSvc.BIBLE_ENTRIES_PER_SERIES_MAX).optional(),
arc: arcSchema.nullable().optional(),
seasons: z.array(seasonSchema).max(ARC_LIMITS.SEASONS_PER_SERIES_MAX).optional(),
locked: seriesLockedSchema.optional(),
@@ -221,9 +192,6 @@ const seriesPatchSchema = z.object({
premise: z.string().trim().max(seriesSvc.PREMISE_MAX).optional(),
universeId: z.string().trim().max(seriesSvc.UNIVERSE_ID_MAX).nullable().optional(),
writersRoomWorkId: z.string().trim().max(seriesSvc.WRITERS_ROOM_WORK_ID_MAX).nullable().optional(),
- characters: z.array(characterSchema).max(seriesSvc.BIBLE_ENTRIES_PER_SERIES_MAX).optional(),
- settings: z.array(settingSchema).max(seriesSvc.BIBLE_ENTRIES_PER_SERIES_MAX).optional(),
- objects: z.array(objectSchema).max(seriesSvc.BIBLE_ENTRIES_PER_SERIES_MAX).optional(),
arc: arcSchema.nullable().optional(),
seasons: z.array(seasonSchema).max(ARC_LIMITS.SEASONS_PER_SERIES_MAX).optional(),
locked: seriesLockedSchema.optional(),
@@ -472,21 +440,6 @@ const comicPagePatchSchema = z.object({
rawText: z.string().max(40000),
});
-// Source: `issueId` (pulls `stages.prose.output`) OR explicit `corpus` text.
-// `parallel: true` runs the three bible kinds concurrently (~3× wall-clock
-// speedup on HTTP-API providers like OpenAI/Anthropic/LM Studio HTTP).
-// Default stays sequential — safe for CLI providers that serialize at the
-// session anyway (codex / claude-code / gemini-cli).
-const extractBibleSchema = z.object({
- kinds: z.array(z.enum([BIBLE_KIND.CHARACTER, BIBLE_KIND.SETTING, BIBLE_KIND.OBJECT]))
- .min(1).max(3).optional()
- .default([BIBLE_KIND.CHARACTER, BIBLE_KIND.SETTING, BIBLE_KIND.OBJECT]),
- issueId: z.string().trim().max(64).optional(),
- corpus: z.string().min(1).max(issuesSvc.STAGE_OUTPUT_MAX).optional(),
- providerOverride: z.string().trim().max(80).optional(),
- parallel: z.boolean().optional(),
-}).refine((p) => p.issueId || p.corpus, { message: 'extract requires either `issueId` or `corpus`' });
-
// Arc / season-episodes / verify — Phase 3 of Story Arc Planning. The three
// LLM calls share a provider/model override shape; the first two also accept
// `commit: true` to persist the LLM output (skipping the preview/confirm step).
@@ -614,7 +567,11 @@ router.post('/issues/:id/stages/audio/extract-lines', asyncHandler(async (req, r
// Carry forward already-rendered audio on re-extract when the same speaker
// + same line text appears in the fresh extraction — otherwise a small edit
// anywhere upstream would silently invalidate every previously-rendered WAV.
- const { lines, preservedCount } = extractDialogueLines(issue, series, {
+ // Phase B.4: canon lives on the linked universe — bind dialogue speakers
+ // by name against `universe.characters` instead of the now-defunct
+ // `series.characters`.
+ const canon = await getSeriesCanon(series);
+ const { lines, preservedCount } = extractDialogueLines(issue, { characters: canon.characters }, {
preserveFrom: existingLines,
});
const { issue: updatedIssue, stage } = await issuesSvc.updateStage(req.params.id, 'audio', {
@@ -689,10 +646,16 @@ router.post('/issues/:id/stages/audio/lines/:lineIdx/render', asyncHandler(async
// Resolve voice via the shared priority chain (explicit > line override
// > character binding > project default). One source of truth, reused by
// the eventual "render all" flow + unit-tested for priority order.
- const series = line.characterId
- ? await seriesSvc.getSeries(issue.seriesId).catch(() => null)
- : null;
- const voiceId = resolveVoiceForLine(line, series, { explicit: body.voiceId });
+ // Phase B.4: the character binding lives on the linked universe — load
+ // it and pass its canon into resolveVoiceForLine through the series-
+ // shaped adapter the helper already accepts.
+ let canonAdapter = null;
+ if (line.characterId) {
+ const series = await seriesSvc.getSeries(issue.seriesId).catch(() => null);
+ const canon = series ? await getSeriesCanon(series) : null;
+ canonAdapter = canon ? { characters: canon.characters } : null;
+ }
+ const voiceId = resolveVoiceForLine(line, canonAdapter, { explicit: body.voiceId });
const synthResult = await synthesizeToFile({ text: line.text, voiceId })
.catch((err) => { throw mapServiceError(err); });
const nextLines = [...lines];
@@ -830,63 +793,11 @@ router.patch('/series/:id', asyncHandler(async (req, res) => {
res.json(s);
}));
-router.post('/series/:id/extract-bible', asyncHandler(async (req, res) => {
- const body = validateRequest(extractBibleSchema, req.body ?? {});
- // Validate series exists up front so a typo returns 404 instead of bubbling
- // out of the service-layer call below.
- const series = await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
-
- let corpus = (body.corpus || '').trim();
- if (!corpus) {
- const issue = await issuesSvc.getIssue(body.issueId).catch((err) => { throw mapServiceError(err); });
- if (issue.seriesId !== series.id) {
- throw new ServerError('Issue does not belong to this series', { status: 400, code: 'PIPELINE_ISSUE_SERIES_MISMATCH' });
- }
- corpus = (issue.stages?.prose?.output || '').trim();
- if (!corpus) {
- throw new ServerError('Issue has no prose to extract from — generate the prose stage first', {
- status: 400, code: 'PIPELINE_NO_PROSE_FOR_EXTRACTION',
- });
- }
- }
-
- // Delegate the extract → merge → patch chain to the service layer so
- // 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,
- parallel: body.parallel,
- providerOverride: body.providerOverride,
- }).catch((err) => { throw mapServiceError(err); });
- res.json(result);
-}));
-
router.delete('/series/:id', asyncHandler(async (req, res) => {
const r = await seriesSvc.deleteSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
res.json(r);
}));
-const refineCharacterSchema = z.object({
- providerId: z.string().trim().max(64).optional(),
- model: z.string().trim().max(128).optional(),
-});
-
-// LLM-driven rewrite of one character's physicalDescription so the rendered
-// image differs from every peer. Preserves evidence + firstAppearance. Returns
-// the updated series so the client can reactively swap state without a refetch.
-router.post('/series/:id/characters/:entryId/refine', asyncHandler(async (req, res) => {
- const body = validateRequest(refineCharacterSchema, req.body ?? {});
- const result = await refineCharacterDescription(req.params.id, req.params.entryId, body)
- .catch((err) => { throw mapServiceError(err); });
- res.json(result);
-}));
-
router.get('/series/:id/issues', asyncHandler(async (req, res) => {
// Validate the series exists so a typo returns 404 instead of [] (less
// confusing for the UI).
@@ -1016,13 +927,16 @@ router.post('/series/:id/seasons/:seasonId/episodes/generate', asyncHandler(asyn
}
// Non-fatal: episode creation already succeeded, so a noisy extraction
- // failure must not invalidate the user's accepted breakdown.
+ // failure must not invalidate the user's accepted breakdown. Phase B.4:
+ // canon lives on the linked universe — orphan series (no universeId)
+ // skip extraction.
+ const series = await seriesSvc.getSeries(req.params.id).catch(() => null);
const corpus = result.episodes
.map((ep) => `## E${ep.number} — ${ep.title}\n\n${ep.logline || ''}\n\n${ep.synopsis || ''}`.trim())
.filter(Boolean)
.join('\n\n');
- if (corpus.trim()) {
- const extractRes = await seriesSvc.extractAndMergeIntoSeries(req.params.id, {
+ if (corpus.trim() && series?.universeId) {
+ const extractRes = await extractCanonFromProse(series.universeId, {
corpus,
providerOverride: body.providerOverride,
parallel: true,
@@ -1035,7 +949,7 @@ router.post('/series/:id/seasons/:seasonId/episodes/generate', asyncHandler(asyn
characters: extractRes.results.characters?.extracted?.length || 0,
settings: extractRes.results.settings?.extracted?.length || 0,
objects: extractRes.results.objects?.extracted?.length || 0,
- series: extractRes.series,
+ universe: extractRes.universe,
};
}
}
@@ -1302,12 +1216,16 @@ router.post('/issues/:id/stages/storyboards/extract-scenes', asyncHandler(async
// Fall back to the series' configured LLM when the client doesn't pass an
// explicit override — every Pipeline LLM action should honor the
// provider/model picked in the issue header (which mirrors series.llm).
+ // Canon lives on the linked universe (Phase B.4). Orphan series render
+ // with empty canon — extractScenes can still produce scenes from the
+ // source text alone, just without character/setting/object grounding.
+ const canon = await getSeriesCanon(series);
const result = await extractScenes({
source,
sourceKind,
- characters: series.characters || [],
- settings: series.settings || [],
- objects: series.objects || [],
+ characters: canon.characters,
+ settings: canon.settings,
+ objects: canon.objects,
work: { title: issue.title, kind: 'tv-episode' },
series: { name: series.name, styleNotes: series.styleNotes },
issue: { number: issue.number, title: issue.title },
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
index 847c4a5c4e..5a17b809a9 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -234,6 +234,7 @@ vi.mock('../lib/multipart.js', () => ({
}));
const pipelineRouter = (await import('./pipeline.js')).default;
+const universeSvc = await import('../services/universeBuilder.js');
function makeApp() {
const app = express();
@@ -463,143 +464,6 @@ describe('pipeline routes', () => {
expect(r.status).toBe(404);
});
- it('POST /series/:id/extract-bible 400s when no issueId and no corpus is supplied', async () => {
- const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
- const r = await request(app).post(`/api/pipeline/series/${ser.body.id}/extract-bible`).send({});
- expect(r.status).toBe(400);
- });
-
- it('POST /series/:id/extract-bible 400s when the issue has no prose stage output', async () => {
- const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
- const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
- const r = await request(app)
- .post(`/api/pipeline/series/${ser.body.id}/extract-bible`)
- .send({ issueId: iss.body.id });
- expect(r.status).toBe(400);
- expect(r.body.error || r.body.message).toMatch(/no prose/i);
- });
-
- it('POST /series/:id/extract-bible 400s when the issue belongs to a different series', async () => {
- const app = makeApp();
- const ser1 = await request(app).post('/api/pipeline/series').send({ name: 'S1' });
- const ser2 = await request(app).post('/api/pipeline/series').send({ name: 'S2' });
- const iss = await request(app).post(`/api/pipeline/series/${ser1.body.id}/issues`).send({ title: 'I' });
- const r = await request(app)
- .post(`/api/pipeline/series/${ser2.body.id}/extract-bible`)
- .send({ issueId: iss.body.id });
- expect(r.status).toBe(400);
- });
-
- it('POST /series/:id/extract-bible runs the requested kinds and merges into the series', async () => {
- // Stub the bible extractor to skip the LLM call entirely.
- const extractor = await import('../lib/bibleExtractor.js');
- const spy = vi.spyOn(extractor, 'extractBible').mockImplementation(async ({ kind }) => ({
- extracted: kind === 'character'
- ? [{ name: 'Aria', physicalDescription: 'tall' }]
- : kind === 'setting'
- ? [{ slugline: 'INT. FOUNDRY — NIGHT', description: 'molten light' }]
- : [{ name: 'The Locket', significance: "mother's" }],
- runId: `run-${kind}`, providerId: 'mock', model: 'mock-model',
- }));
-
- const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
- const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
- // Seed prose
- await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({
- stages: { prose: { status: 'ready', output: 'Once upon a time...' } },
- });
-
- const r = await request(app)
- .post(`/api/pipeline/series/${ser.body.id}/extract-bible`)
- .send({ issueId: iss.body.id, kinds: ['character', 'setting'] });
-
- expect(r.status).toBe(200);
- expect(r.body.series.characters[0].name).toBe('Aria');
- expect(r.body.series.settings[0].slugline).toBe('INT. FOUNDRY — NIGHT');
- // Objects bible was not requested → still empty
- expect(r.body.series.objects).toEqual([]);
- expect(r.body.results.characters.runId).toBe('run-character');
- expect(spy).toHaveBeenCalledTimes(2);
- spy.mockRestore();
- });
-
- it('POST /series/:id/extract-bible with parallel:true fans all kinds out concurrently', async () => {
- // Track interleaving by recording per-call start + finish times. In
- // parallel mode all starts come before any finish; sequential mode has
- // finish[N] before start[N+1].
- const extractor = await import('../lib/bibleExtractor.js');
- const events = [];
- const spy = vi.spyOn(extractor, 'extractBible').mockImplementation(async ({ kind }) => {
- events.push({ kind, event: 'start' });
- await new Promise((r) => setTimeout(r, 30));
- events.push({ kind, event: 'finish' });
- return { extracted: [], runId: `run-${kind}`, providerId: 'mock', model: 'mock-model' };
- });
-
- const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
- const r = await request(app)
- .post(`/api/pipeline/series/${ser.body.id}/extract-bible`)
- .send({ corpus: 'x', parallel: true });
-
- expect(r.status).toBe(200);
- expect(spy).toHaveBeenCalledTimes(3);
- // Parallel guarantee: every start fired before the first finish.
- const firstFinishIdx = events.findIndex((e) => e.event === 'finish');
- const startsBeforeFirstFinish = events.slice(0, firstFinishIdx).filter((e) => e.event === 'start').length;
- expect(startsBeforeFirstFinish).toBe(3);
- spy.mockRestore();
- });
-
- it('POST /series/:id/extract-bible defaults to sequential (CLI-provider safe)', async () => {
- const extractor = await import('../lib/bibleExtractor.js');
- const events = [];
- const spy = vi.spyOn(extractor, 'extractBible').mockImplementation(async ({ kind }) => {
- events.push({ kind, event: 'start' });
- await new Promise((r) => setTimeout(r, 10));
- events.push({ kind, event: 'finish' });
- return { extracted: [], runId: `run-${kind}`, providerId: 'mock', model: 'mock-model' };
- });
-
- const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
- const r = await request(app)
- .post(`/api/pipeline/series/${ser.body.id}/extract-bible`)
- .send({ corpus: 'x' });
-
- expect(r.status).toBe(200);
- expect(spy).toHaveBeenCalledTimes(3);
- // Sequential: each kind finishes before the next one starts. The events
- // array must alternate start, finish, start, finish, start, finish.
- const eventTypes = events.map((e) => e.event);
- expect(eventTypes).toEqual(['start', 'finish', 'start', 'finish', 'start', 'finish']);
- spy.mockRestore();
- });
-
- it('POST /series/:id/extract-bible dedups duplicate kinds (no extra LLM calls)', async () => {
- const extractor = await import('../lib/bibleExtractor.js');
- const calls = [];
- const spy = vi.spyOn(extractor, 'extractBible').mockImplementation(async ({ kind }) => {
- calls.push(kind);
- return { extracted: [], runId: `run-${kind}`, providerId: 'mock', model: 'mock-model' };
- });
-
- const app = makeApp();
- const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
- const r = await request(app)
- .post(`/api/pipeline/series/${ser.body.id}/extract-bible`)
- .send({ corpus: 'x', kinds: ['character', 'character', 'setting'] });
-
- expect(r.status).toBe(200);
- // Duplicates collapsed before the LLM dispatch — 2 calls for 2 unique kinds.
- expect(spy).toHaveBeenCalledTimes(2);
- expect(calls.sort()).toEqual(['character', 'setting']);
- spy.mockRestore();
- });
-
// ---- storyboards/extract-scenes ----
it('POST /issues/:id/stages/storyboards/extract-scenes 400s when the source stage is empty', async () => {
@@ -643,9 +507,17 @@ describe('pipeline routes', () => {
runId: 'run-scenes-1', providerId: 'mock', model: 'mock-model',
});
+ // Phase B.4: canon lives on the linked universe. Seed a universe via
+ // the service layer (this test mounts only /api/pipeline, not the
+ // universe-builder router), link the series to it, then run extraction
+ // — the universe's canon should reach the extractor via getSeriesCanon.
const app = makeApp();
+ const uni = await universeSvc.createUniverse({
+ name: 'U',
+ characters: [{ name: 'Alice', physicalDescription: 'tall, freckles' }],
+ });
const ser = await request(app).post('/api/pipeline/series').send({
- name: 'S', characters: [{ name: 'Alice', physicalDescription: 'tall, freckles' }],
+ name: 'S', universeId: uni.id,
});
const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({
@@ -670,7 +542,7 @@ describe('pipeline routes', () => {
expect(r.body.stage.lastRunId).toBe('run-scenes-1');
expect(r.body.stage.status).toBe('ready');
- // Series characters were forwarded to the extractor for bible deference
+ // Universe canon was forwarded to the extractor for bible deference.
const firstCall = spy.mock.calls[0][0];
expect(firstCall.characters[0].name).toBe('Alice');
expect(firstCall.sourceKind).toBe('teleplay');
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index 6f5f550cbe..fc0308b4fd 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -97,6 +97,15 @@ const influencesSchema = z.object({
const legacyStylePromptField = z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional();
const legacyNegativePromptField = z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional();
+// Canon arrays go through `sanitizeBibleList` in the service layer where
+// each entry is validated structurally — accept them loosely here so
+// patch-the-whole-list flows (e.g. inline canon edits, render-ref hooks)
+// don't fail Zod for legitimately rich shapes. Cap at the bible-wide entry
+// limit so a malicious payload can't blow up memory.
+// Hard cap mirrors BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX (200) with headroom
+// — sanitizer truncates anyway, so this just protects the JSON-parse layer.
+const canonArrayField = z.array(z.record(z.unknown())).max(500).optional();
+
const createSchema = z.object({
name: z.string().trim().min(1).max(svc.NAME_MAX_LENGTH),
starterPrompt: z.string().trim().max(svc.STARTER_PROMPT_MAX).optional().default(''),
@@ -110,16 +119,13 @@ const createSchema = z.object({
influences: influencesSchema.optional(),
locked: lockedSchema.optional(),
llm: llmSchema,
+ // Canon registries on POST (Phase B.4): writers-room promote, share-bucket
+ // import, and tests can seed a universe with canon at create time instead
+ // of needing a second PATCH round-trip.
+ characters: canonArrayField,
+ settings: canonArrayField,
+ objects: canonArrayField,
});
-
-// Canon arrays go through `sanitizeBibleList` in the service layer where
-// each entry is validated structurally — accept them loosely here so
-// patch-the-whole-list flows (e.g. inline canon edits, render-ref hooks)
-// don't fail Zod for legitimately rich shapes. Cap at the bible-wide entry
-// limit so a malicious payload can't blow up memory.
-// Hard cap mirrors BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX (200) with headroom
-// — sanitizer truncates anyway, so this just protects the JSON-parse layer.
-const canonArrayField = z.array(z.record(z.unknown())).max(500).optional();
// `origin` is a share-bucket provenance block written by the importer + cleared
// to null by the user; structurally an object or null.
const originField = z.record(z.unknown()).nullable().optional();
diff --git a/server/services/pipeline/audio.js b/server/services/pipeline/audio.js
index 869eeba929..57e94d5d3a 100644
--- a/server/services/pipeline/audio.js
+++ b/server/services/pipeline/audio.js
@@ -81,29 +81,30 @@ export async function listAllVoices() {
* Walk an issue's already-extracted storyboard scenes and emit a flat
* `lines[]` ready to write onto `stages.audio.lines`. The scene extractor
* already parsed dialogue into `{ character, line }` per scene, so we don't
- * re-parse markdown here — we just flatten + bind each speaker to a series
+ * re-parse markdown here — we just flatten + bind each speaker to a canon
* character (by name, case-insensitive) so the per-line render can resolve
* a voice id.
*
- * Lines without a matching series character still get persisted (the user
+ * Lines without a matching canon character still get persisted (the user
* may want narrator / un-named-character lines synthesized via the project
* default voice); `characterId` stays null in that case.
*/
/**
* Voice resolution for a single VO line. Priority:
- * 1. `explicit` (per-request body override)
+ * 1. `explicit` (per-request body override)
* 2. `line.voiceIdOverride` (per-line override saved on the issue)
- * 3. `character.voiceId` (series character binding by line.characterId)
+ * 3. `character.voiceId` (canon character binding by line.characterId)
* 4. `null` (caller falls through to the configured default voice)
*
- * Pure function — no I/O — so the route, a future "render all" flow, and
- * unit tests all use the same priority logic.
+ * `canon` is `{ characters }` — typically loaded from the linked universe
+ * via `getSeriesCanon(series)`. Pure function — no I/O — so the route,
+ * a future "render all" flow, and unit tests all use the same priority.
*/
-export function resolveVoiceForLine(line, series, { explicit } = {}) {
+export function resolveVoiceForLine(line, canon, { explicit } = {}) {
if (typeof explicit === 'string' && explicit.trim()) return explicit.trim();
if (line?.voiceIdOverride) return line.voiceIdOverride;
if (line?.characterId) {
- const char = (series?.characters || []).find((c) => c?.id === line.characterId);
+ const char = (canon?.characters || []).find((c) => c?.id === line.characterId);
if (char?.voiceId) return char.voiceId;
}
return null;
@@ -123,7 +124,7 @@ function stripSpeakerParens(raw) {
.trim();
}
-export function extractDialogueLines(issue, series, { preserveFrom = [] } = {}) {
+export function extractDialogueLines(issue, canon, { preserveFrom = [] } = {}) {
const scenes = Array.isArray(issue?.stages?.storyboards?.scenes)
? issue.stages.storyboards.scenes
: [];
@@ -134,7 +135,7 @@ export function extractDialogueLines(issue, series, { preserveFrom = [] } = {})
const rememberKey = (key, c) => {
if (key && !charactersByKey.has(key)) charactersByKey.set(key, c);
};
- for (const c of (series?.characters || [])) {
+ for (const c of (canon?.characters || [])) {
if (!c || typeof c !== 'object') continue;
const name = typeof c.name === 'string' ? c.name.trim() : '';
if (!name) continue;
diff --git a/server/services/pipeline/nounRefine.js b/server/services/pipeline/nounRefine.js
deleted file mode 100644
index de6d114891..0000000000
--- a/server/services/pipeline/nounRefine.js
+++ /dev/null
@@ -1,79 +0,0 @@
-// Rewrite a character's `physicalDescription` so the rendered image differs
-// from every peer in the cast. Characters only (settings/objects need
-// different prompt fields — punt until there's a real need).
-
-import { getSeries, updateSeries } from './series.js';
-import { ServerError } from '../../lib/errorHandler.js';
-import { runPromptRefine } from './refineHelpers.js';
-import { joinInfluenceList } from '../universeBuilder.js';
-
-const peerForPrompt = (entry) => ({
- name: entry.name,
- aliases: Array.isArray(entry.aliases) ? entry.aliases : [],
- role: entry.role || '',
- physicalDescription: entry.physicalDescription || entry.description || '',
-});
-
-const targetForPrompt = (entry) => ({
- ...peerForPrompt(entry),
- evidence: Array.isArray(entry.evidence) ? entry.evidence : [],
- firstAppearance: entry.firstAppearance || null,
-});
-
-export async function refineCharacterDescription(seriesId, entryId, options = {}) {
- const series = await getSeries(seriesId);
-
- // Phase B.3 routing: if the series links to a universe, refine on the
- // universe (where canon actually lives post-Phase-B). Return a series-
- // shaped result so legacy callers — the per-series Nouns page when it
- // takes the orphan branch — don't fork.
- if (series.universeId) {
- // Dynamic import to avoid the universeCanon → series.js cycle on
- // module-init (universeCanon imports updateUniverse, which lives in
- // universeBuilder.js, but the indirect graph still trips).
- const { refineUniverseCharacter } = await import('../universeCanon.js');
- const result = await refineUniverseCharacter(series.universeId, entryId, options);
- return { series, entry: result.entry, rationale: result.rationale, changes: result.changes, runId: result.runId, providerId: result.providerId, model: result.model };
- }
-
- const list = Array.isArray(series.characters) ? series.characters : [];
- const idx = list.findIndex((e) => e.id === entryId);
- if (idx < 0) {
- throw new ServerError(`Character ${entryId} not found in series`, {
- status: 404, code: 'PIPELINE_NOUN_NOT_FOUND',
- });
- }
- const target = list[idx];
- const peers = list.filter((_, i) => i !== idx);
-
- const universe = null; // orphan-series path only — universeId branch returns early above
- const universeAesthetic = joinInfluenceList(universe?.influences?.embrace);
- const styleBits = [
- universeAesthetic ? `Universe aesthetic: ${universeAesthetic}` : null,
- series.styleNotes ? `Series notes: ${series.styleNotes}` : null,
- ].filter(Boolean);
- const styleClause = styleBits.length
- ? styleBits.join('\n')
- : '(none provided — pick choices that fit the character\'s role and genre)';
-
- const { refined, changes, rationale, runId, providerId, model } = await runPromptRefine({
- templateName: 'pipeline-character-refine',
- variables: {
- targetJson: JSON.stringify(targetForPrompt(target), null, 2),
- peersJson: JSON.stringify(peers.map(peerForPrompt), null, 2),
- styleClause,
- },
- options,
- source: 'pipeline-character-refine',
- logTag: `Pipeline character refine — series=${seriesId.slice(0, 8)} entry=${entryId.slice(0, 8)}`,
- resultField: 'physicalDescription',
- emptyError: { code: 'PIPELINE_NOUN_REFINE_EMPTY', message: 'LLM returned an empty physicalDescription' },
- changesLimit: 12,
- });
-
- const nextList = list.map((e, i) => i === idx ? { ...e, physicalDescription: refined } : e);
- const updated = await updateSeries(seriesId, { characters: nextList });
- const updatedEntry = (updated.characters || []).find((e) => e.id === entryId) || null;
-
- return { series: updated, entry: updatedEntry, rationale, changes, runId, providerId, model };
-}
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index ad13c455b5..dc45ddc2d2 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -13,14 +13,9 @@
import { join } from 'path';
import { randomUUID } from 'crypto';
import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';
-import {
- sanitizeBibleList, mergeExtractedBible,
- BIBLE_LIMITS, BIBLE_KIND, BIBLE_FIELD, BIBLE_KEYS, BIBLE_SOURCE,
- isStr, trimTo,
-} from '../../lib/storyBible.js';
+import { isStr, trimTo } from '../../lib/storyBible.js';
import { sanitizeArc, sanitizeSeasonList } from '../../lib/storyArc.js';
import { sanitizeVisualStyleRef } from '../../lib/visualStyles.js';
-import { extractBible } from '../../lib/bibleExtractor.js';
import { sanitizeOrigin } from '../../lib/sharingOrigin.js';
import { emitRecordUpdated, emitRecordDeleted } from '../sharing/recordEvents.js';
@@ -60,12 +55,6 @@ export const LOGLINE_MAX = 500;
export const PREMISE_MAX = 8000;
export const STYLE_NOTES_MAX = 4000;
export const STYLE_PROMPT_OVERRIDE_MAX = 1000;
-export const CHARACTER_NAME_MAX = BIBLE_LIMITS.NAME_MAX;
-export const CHARACTER_DESCRIPTION_MAX = BIBLE_LIMITS.PHYSICAL_DESCRIPTION_MAX;
-export const CHARACTERS_PER_SERIES_MAX = BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX;
-export const BIBLE_ENTRIES_PER_SERIES_MAX = BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX;
-export const IMAGE_REFS_PER_CHARACTER_MAX = BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX;
-export const IMAGE_REF_MAX = BIBLE_LIMITS.IMAGE_REF_MAX;
export const UNIVERSE_ID_MAX = 64;
export const WRITERS_ROOM_WORK_ID_MAX = 64;
export const TARGET_FORMATS = Object.freeze(['comic', 'tv', 'comic+tv']);
@@ -110,9 +99,6 @@ const sanitizeSeries = (raw) => {
// Bidirectional link to a Writers Room work (item 6 of the DRY
// unification). Set by the "Promote to pipeline" flow; never auto-cleared.
writersRoomWorkId: trimTo(raw.writersRoomWorkId, WRITERS_ROOM_WORK_ID_MAX) || null,
- characters: sanitizeBibleList(raw.characters, BIBLE_KIND.CHARACTER),
- settings: sanitizeBibleList(raw.settings, BIBLE_KIND.SETTING),
- objects: sanitizeBibleList(raw.objects, BIBLE_KIND.OBJECT),
// Phase 2 of Story Arc Planning: optional multi-season story spine + the
// ordered season list. Both default to empty so existing series.json
// files migrate forward without a writer pass — first save backfills.
@@ -177,9 +163,6 @@ export async function createSeries(input = {}) {
premise: input.premise || '',
universeId: input.universeId || null,
writersRoomWorkId: input.writersRoomWorkId || null,
- characters: input.characters || [],
- settings: input.settings || [],
- objects: input.objects || [],
arc: input.arc || null,
seasons: input.seasons || [],
locked: input.locked || {},
@@ -240,9 +223,6 @@ export async function updateSeries(id, patch = {}) {
...('premise' in patch ? { premise: patch.premise } : {}),
...('universeId' in patch ? { universeId: patch.universeId } : {}),
...('writersRoomWorkId' in patch ? { writersRoomWorkId: patch.writersRoomWorkId } : {}),
- ...('characters' in patch ? { characters: patch.characters } : {}),
- ...('settings' in patch ? { settings: patch.settings } : {}),
- ...('objects' in patch ? { objects: patch.objects } : {}),
...('arc' in patch ? { arc: patch.arc } : {}),
...('seasons' in patch ? { seasons: patch.seasons } : {}),
// Wholesale replace — `locked: {}` clears every lock; omission preserves.
@@ -304,124 +284,6 @@ export async function updateSeasonOnSeries(seriesId, seasonId, patchFn) {
});
}
-/**
- * Strip a filename from every `imageRefs[]` across every series's
- * characters/settings/objects. Called by the image-delete route so a noun
- * card stops pointing at a file the user just deleted from the gallery.
- *
- * Returns `{ removed }` — total references stripped across all series.
- * Skips the write when nothing matched, so a delete of a non-noun image
- * (the common case) is a cheap no-op read.
- */
-export async function purgeImageRefFromAllSeries(filename) {
- if (!filename || typeof filename !== 'string') return { removed: 0 };
- return queueSeriesWrite(async () => {
- const state = await readState();
- let removed = 0;
- const touchedIds = [];
- const nextSeries = state.series.map((s) => {
- let touched = false;
- const patched = { ...s };
- for (const key of BIBLE_KEYS) {
- const list = Array.isArray(s[key]) ? s[key] : null;
- if (!list) continue;
- const nextList = list.map((entry) => {
- const refs = Array.isArray(entry.imageRefs) ? entry.imageRefs : null;
- if (!refs || !refs.includes(filename)) return entry;
- const trimmed = refs.filter((f) => f !== filename);
- removed += refs.length - trimmed.length;
- touched = true;
- return { ...entry, imageRefs: trimmed };
- });
- if (touched) patched[key] = nextList;
- }
- if (touched) touchedIds.push(s.id);
- return touched ? { ...patched, updatedAt: new Date().toISOString() } : s;
- });
- if (removed > 0) {
- await writeState({ series: nextSeries });
- // Each touched series is a mutation any active subscription should
- // propagate to its bucket; otherwise recipients keep stale imageRefs.
- for (const id of touchedIds) emitRecordUpdated('series', id);
- }
- return { removed };
- });
-}
-
-/**
- * Run bible extraction across the requested kinds and merge results into a
- * series. The route layer used to thread extract → merge → patch itself,
- * which made `mergeExtractedBible` a route-layer concern. Lifting it here
- * gives the route a 3-line call and lets future consumers (re-sync from
- * Writers Room, batch bible refresh, etc) reuse the same orchestration.
- *
- * @param {string} seriesId
- * @param {object} opts
- * @param {string[]} opts.kinds BIBLE_KIND values to run (defaults to all three)
- * @param {string} opts.corpus prose body to extract from
- * @param {boolean} [opts.parallel] fan out the kinds concurrently (HTTP-API providers only)
- * @param {string} [opts.providerOverride]
- * @returns {Promise<{ series, results }>} results is keyed by BIBLE_FIELD (e.g. `characters`)
- */
-export async function extractAndMergeIntoSeries(seriesId, opts = {}) {
- const series = await getSeries(seriesId);
-
- // Phase B.3 routing: when the series links to a universe, extract into the
- // universe and return a compatible shape so every legacy caller keeps
- // working without a fork. New entries arrive auto-locked + tagged with this
- // series so a later refine/differentiate cannot silently rewrite them.
- if (series.universeId) {
- // Dynamic import avoids a circular dep through universeCanon → series.js.
- const { extractCanonFromProse } = await import('../universeCanon.js');
- const { universe, results } = await extractCanonFromProse(series.universeId, {
- ...opts,
- source: BIBLE_SOURCE.SERIES_EXTRACT,
- autoLock: true,
- sourceSeriesId: series.id,
- });
- return { series, universe, results };
- }
-
- // Dedup `kinds` — duplicates would run extra LLM calls AND last-write-wins
- // the merge for the same field, so the only observable effect of a repeat
- // is a wasted provider round-trip. Preserve first-seen order so callers
- // can rely on response key order in `results`.
- const rawKinds = (opts.kinds && opts.kinds.length)
- ? opts.kinds
- : [BIBLE_KIND.CHARACTER, BIBLE_KIND.SETTING, BIBLE_KIND.OBJECT];
- const kinds = [...new Set(rawKinds)];
- if (!isStr(opts.corpus) || !opts.corpus.trim()) {
- throw makeErr('extractAndMergeIntoSeries: corpus is required', ERR_VALIDATION);
- }
-
- const runOne = (kind) => extractBible({
- kind,
- corpus: opts.corpus,
- existing: series[BIBLE_FIELD[kind]] || [],
- context: { series: { id: series.id, name: series.name } },
- providerOverride: opts.providerOverride,
- source: `pipeline-bible-${kind}`,
- }).then((result) => ({ kind, result }));
-
- const completed = opts.parallel
- ? await Promise.all(kinds.map(runOne))
- : await kinds.reduce(async (acc, kind) => [...(await acc), await runOne(kind)], Promise.resolve([]));
-
- const results = {};
- const patch = {};
- for (const { kind, result } of completed) {
- const field = BIBLE_FIELD[kind];
- patch[field] = mergeExtractedBible(series[field] || [], result.extracted, kind);
- results[field] = {
- extracted: result.extracted, runId: result.runId,
- providerId: result.providerId, model: result.model,
- };
- }
-
- const updated = await updateSeries(series.id, patch);
- return { series: updated, results };
-}
-
export async function deleteSeries(id) {
return queueSeriesWrite(async () => {
const state = await readState();
diff --git a/server/services/pipeline/series.test.js b/server/services/pipeline/series.test.js
index c092177aa0..ba743e0682 100644
--- a/server/services/pipeline/series.test.js
+++ b/server/services/pipeline/series.test.js
@@ -27,7 +27,11 @@ describe('pipeline series service', () => {
expect(await svc.listSeries()).toEqual([]);
});
- it('createSeries assigns ser- prefixed id and persists the bible fields', async () => {
+ it('createSeries assigns ser- prefixed id and persists the basic fields', async () => {
+ // Phase B.4: canon (characters/settings/objects) no longer lives on the
+ // series — it lives on the linked universe. This test exercises only
+ // the series-owned fields; canon round-tripping is covered by
+ // universeBuilder.test.js + promoteToPipeline.test.js.
const s = await svc.createSeries({
name: 'Salt Run',
logline: 'A foundry city goes silent.',
@@ -36,10 +40,6 @@ describe('pipeline series service', () => {
styleNotes: 'moebius linework, washed sepia',
targetFormat: 'comic+tv',
issueCountTarget: 6,
- characters: [
- { name: 'Lina', description: 'A young foundry surveyor.' },
- { name: '', description: 'Skipped — no name' },
- ],
});
expect(s.id).toMatch(/^ser-/);
expect(s.name).toBe('Salt Run');
@@ -47,10 +47,9 @@ describe('pipeline series service', () => {
expect(s.universeId).toBe('world-123');
expect(s.targetFormat).toBe('comic+tv');
expect(s.issueCountTarget).toBe(6);
- // Empty-name character dropped; Lina gets a chr- id.
- expect(s.characters).toHaveLength(1);
- expect(s.characters[0].name).toBe('Lina');
- expect(s.characters[0].id).toMatch(/^chr-/);
+ expect(s.characters).toBeUndefined();
+ expect(s.settings).toBeUndefined();
+ expect(s.objects).toBeUndefined();
});
it('createSeries requires a non-empty name', async () => {
@@ -93,10 +92,20 @@ describe('pipeline series service', () => {
expect(s.targetFormat).toBe('comic+tv');
});
- it('caps characters at CHARACTERS_PER_SERIES_MAX', async () => {
- const many = Array.from({ length: svc.CHARACTERS_PER_SERIES_MAX + 10 }, (_, i) => ({ name: `c${i}` }));
- const s = await svc.createSeries({ name: 'X', characters: many });
- expect(s.characters).toHaveLength(svc.CHARACTERS_PER_SERIES_MAX);
+ it('silently drops legacy canon fields on create (Phase B.4: canon moved to universe)', async () => {
+ // A stale client that still sends `characters: [...]` on series create
+ // gets a 200 — the field is dropped server-side instead of 400'ing —
+ // so old browser tabs don't fail on a save. The actual canon round-
+ // trips through the linked universe now.
+ const s = await svc.createSeries({
+ name: 'X',
+ characters: [{ name: 'ignored' }],
+ settings: [{ name: 'ignored' }],
+ objects: [{ name: 'ignored' }],
+ });
+ expect(s.characters).toBeUndefined();
+ expect(s.settings).toBeUndefined();
+ expect(s.objects).toBeUndefined();
});
describe('insertSeriesWithId', () => {
diff --git a/server/services/pipeline/seriesCanon.js b/server/services/pipeline/seriesCanon.js
index 4e3139dab6..f2dd1a1481 100644
--- a/server/services/pipeline/seriesCanon.js
+++ b/server/services/pipeline/seriesCanon.js
@@ -1,85 +1,29 @@
-// 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.
+// Resolves a series's effective canon (characters, settings, objects) by
+// reading the linked universe. Series no longer carries canon arrays of its
+// own (Phase B.4) — every active series is universe-linked, so this is just
+// a thin async lookup that returns empty arrays when the series has no
+// `universeId` set.
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' };
+const EMPTY = Object.freeze({ characters: [], settings: [], objects: [] });
- 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' };
-}
+const pickCanon = (universe) => ({
+ characters: Array.isArray(universe?.characters) ? universe.characters : [],
+ settings: Array.isArray(universe?.settings) ? universe.settings : [],
+ objects: Array.isArray(universe?.objects) ? universe.objects : [],
+});
/**
- * 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`.
+ * Async canon read for text/arc-planning stages that don't already have the
+ * universe record in scope. Returns frozen-empty when the series is orphan
+ * (no universeId) or the linked universe is missing.
+ *
+ * @returns {Promise<{ characters, settings, objects }>}
*/
-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',
- };
+export async function getSeriesCanon(series) {
+ if (!series?.universeId) return EMPTY;
+ const universe = await getUniverse(series.universeId).catch(() => null);
+ if (!universe) return EMPTY;
+ return pickCanon(universe);
}
diff --git a/server/services/pipeline/textStages.js b/server/services/pipeline/textStages.js
index 511b2ddcc7..0bf2521101 100644
--- a/server/services/pipeline/textStages.js
+++ b/server/services/pipeline/textStages.js
@@ -15,7 +15,8 @@
*/
import { runStagedLLM } from '../../lib/stageRunner.js';
-import { getSeries, extractAndMergeIntoSeries } from './series.js';
+import { getSeries } from './series.js';
+import { extractCanonFromProse } from '../universeCanon.js';
import { getIssue, listIssues, updateStage, TEXT_STAGE_IDS } from './issues.js';
import { getSeriesCanon } from './seriesCanon.js';
import { compareIssuesByPosition } from './arcPlanner.js';
@@ -225,8 +226,12 @@ export async function generateStage(issueId, stageId, options = {}) {
// Only runs on `prose`: scripts derive from prose so new characters land here
// first; idea is too short to extract usefully. Non-fatal — prose succeeded,
// and a noisy extract shouldn't roll back the user's accepted draft.
- if (stageId === 'prose' && output) {
- await extractAndMergeIntoSeries(series.id, {
+ // Phase B.4: canon lives on the universe, so an orphan series (no
+ // universeId) silently skips extraction — the prose write still
+ // succeeds, the user just doesn't get the bible auto-populated until
+ // they link a universe.
+ if (stageId === 'prose' && output && series.universeId) {
+ await extractCanonFromProse(series.universeId, {
corpus: output,
providerOverride: options.providerId,
parallel: true,
diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.js
index a12674397a..04505e0b4e 100644
--- a/server/services/pipeline/visualStages.js
+++ b/server/services/pipeline/visualStages.js
@@ -42,7 +42,6 @@ import { resolveVisualStyle } from '../../lib/visualStyles.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 joinStyleParts = (...parts) =>
@@ -142,9 +141,15 @@ 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;
- // 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);
+ // Canon lives on the linked universe (Phase B.4). An orphan series (no
+ // universeId or a dangling reference) renders against empty canon arrays
+ // — the visual prompt still includes scene description, just without
+ // character/setting/object metadata.
+ const canon = {
+ characters: Array.isArray(world?.characters) ? world.characters : [],
+ settings: Array.isArray(world?.settings) ? world.settings : [],
+ objects: Array.isArray(world?.objects) ? world.objects : [],
+ };
return { issue, series, world, canon };
})();
const [chain, settings] = await Promise.all([issueChain, getSettings()]);
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index 7d6ab81c9c..982aee5d7d 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -52,6 +52,7 @@ const exporter = await import('./exporter.js');
const importer = await import('./importer.js');
const series = await import('../pipeline/series.js');
const issues = await import('../pipeline/issues.js');
+const universeSvc = await import('../universeBuilder.js');
// Rewrite a manifest's senderInstanceId on disk so the importer sees it as
// coming from a remote peer. The mocked `getInstanceId` returns the same
@@ -83,18 +84,23 @@ describe('sharing round-trip', () => {
it('exports a series, processes the manifest as inbox, then promotes — id + origin preserved', async () => {
const bucket = await buckets.createBucket({ name: 'Test', path: tempBucket, mode: 'inbox' });
- // Author a series + an issue locally.
+ // Author a series + an issue locally. Phase B.4: canon lives on the
+ // linked universe — seed a universe with the character + imageRef so
+ // the exporter (which walks linked-universe canon) finds the asset.
+ const uni = await universeSvc.createUniverse({
+ name: 'Salt Universe',
+ characters: [{ name: 'Vex', imageRefs: ['fakeasset.png'] }],
+ });
const s = await series.createSeries({
name: 'Salt Run', logline: 'A foundry city goes silent.', premise: 'The only survivor is a child.',
- // Add an imageRef on a character so the exporter has an asset to copy.
- characters: [{ name: 'Vex', imageRefs: ['fakeasset.png'] }],
+ universeId: uni.id,
});
const iss = await issues.createIssue({ seriesId: s.id, title: 'Issue 1' });
// Export.
const exp = await exporter.exportSeries(s.id, bucket.id);
expect(exp.manifestId).toBeTruthy();
- expect(exp.recordCount).toBe(2); // series + issue
+ expect(exp.recordCount).toBe(3); // series + issue + universe
expect(exp.assetCount).toBeGreaterThanOrEqual(1);
// Verify the bucket layout.
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index a0ff50262f..f02ef8d172 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -43,7 +43,12 @@ import { emitRecordUpdated, emitRecordDeleted } from './sharing/recordEvents.js'
// so there is a single token-list editing surface.
export const CURRENT_SCHEMA_VERSION = 3;
-const STATE_PATH = join(PATHS.data, 'universe-builder.json');
+// Lazy state-path resolution so test harnesses that swap PATHS.data
+// per-test (mkdtempSync + Proxy mock) see the right temp root. Computing
+// the path at module-load freezes whatever value PATHS.data held when
+// universeBuilder.js was first imported, which is `undefined` under the
+// proxy-mock pattern series.js's tests already use.
+const statePath = () => join(PATHS.data, 'universe-builder.json');
export const ERR_NOT_FOUND = 'NOT_FOUND';
export const ERR_VALIDATION = 'VALIDATION_ERROR';
@@ -515,7 +520,7 @@ const sanitizeRun = (raw) => {
async function readState() {
await ensureDir(PATHS.data);
- const raw = await readJSONFile(STATE_PATH, DEFAULT_STATE, { logError: false });
+ const raw = await readJSONFile(statePath(), DEFAULT_STATE, { logError: false });
const rawById = new Map(Array.isArray(raw.universes) ? raw.universes.filter((u) => u?.id).map((u) => [u.id, u]) : []);
const universes = Array.isArray(raw.universes) ? raw.universes.map(sanitizeTemplate).filter(Boolean) : [];
const runs = Array.isArray(raw.runs) ? raw.runs.map(sanitizeRun).filter(Boolean) : [];
@@ -531,7 +536,7 @@ async function readState() {
}
async function writeState(state) {
- await atomicWrite(STATE_PATH, state);
+ await atomicWrite(statePath(), state);
}
export async function listUniverses() {
@@ -565,6 +570,12 @@ export async function createUniverse(input = {}) {
compositeSheets: input.compositeSheets || [],
influences: input.influences || {},
locked: input.locked || {},
+ // Canon registries — let callers seed a universe at creation time
+ // (writers-room promote, share-bucket import). sanitizeTemplate runs
+ // each through sanitizeBibleList, so per-entry shape is enforced.
+ characters: input.characters || [],
+ settings: input.settings || [],
+ objects: input.objects || [],
llm: input.llm || {},
createdAt: now,
updatedAt: now,
diff --git a/server/services/writersRoom/promoteToPipeline.js b/server/services/writersRoom/promoteToPipeline.js
index 57c7728f55..80c8df2880 100644
--- a/server/services/writersRoom/promoteToPipeline.js
+++ b/server/services/writersRoom/promoteToPipeline.js
@@ -24,6 +24,7 @@ import { listObjects } from './objects.js';
import { getAnalysis } from './evaluator.js';
import * as seriesSvc from '../pipeline/series.js';
import * as issuesSvc from '../pipeline/issues.js';
+import { createUniverse } from '../universeBuilder.js';
export const ERR_NO_DRAFT_BODY = 'WR_PROMOTE_NO_DRAFT_BODY';
@@ -90,13 +91,25 @@ export async function promoteWorkToPipeline(workId, { force = false } = {}) {
loadScriptScenes(workId),
]);
- const series = await seriesSvc.createSeries({
+ // Phase B.4: canon now lives on the universe, never on the series. Mint a
+ // dedicated universe for this promoted work and seed it with the writers-
+ // room bibles. Naming follows the work title — the user can rename or
+ // re-link later via the Series page if they want to share an existing
+ // universe across crossover series. A fresh universe per work keeps the
+ // initial state predictable and avoids touching unrelated canon if the
+ // user re-promotes after destructive edits.
+ const universe = await createUniverse({
name: manifest.title,
- logline: '',
- premise: '',
characters,
settings,
objects,
+ });
+
+ const series = await seriesSvc.createSeries({
+ name: manifest.title,
+ logline: '',
+ premise: '',
+ universeId: universe.id,
styleNotes: '',
targetFormat: 'comic+tv',
issueCountTarget: 1,
diff --git a/server/services/writersRoom/promoteToPipeline.test.js b/server/services/writersRoom/promoteToPipeline.test.js
index c099b960d0..b21a2ae5b8 100644
--- a/server/services/writersRoom/promoteToPipeline.test.js
+++ b/server/services/writersRoom/promoteToPipeline.test.js
@@ -22,6 +22,7 @@ const { createSetting } = await import('./settings.js');
const { createObject } = await import('./objects.js');
const seriesSvc = await import('../pipeline/series.js');
const issuesSvc = await import('../pipeline/issues.js');
+const universeSvc = await import('../universeBuilder.js');
beforeEach(() => {
tempRoot = mkdtempSync(join(tmpdir(), 'wr-promote-test-'));
@@ -80,7 +81,7 @@ describe('promoteWorkToPipeline', () => {
expect(reloadedSeries.writersRoomWorkId).toBe(work.id);
});
- it('carries over characters / settings / objects bibles into the series', async () => {
+ it('carries over characters / settings / objects bibles into the linked universe (Phase B.4)', async () => {
const work = await seedWorkWithProse();
await createCharacter(work.id, { name: 'Aria', physicalDescription: 'tall, freckles' });
await createSetting(work.id, { name: 'The Foundry', slugline: 'INT. FOUNDRY — NIGHT', description: 'molten light' });
@@ -88,13 +89,19 @@ describe('promoteWorkToPipeline', () => {
const { series } = await promoteWorkToPipeline(work.id);
- expect(series.characters).toHaveLength(1);
- expect(series.characters[0].name).toBe('Aria');
- expect(series.characters[0].physicalDescription).toBe('tall, freckles');
- expect(series.settings).toHaveLength(1);
- expect(series.settings[0].slugline).toBe('INT. FOUNDRY — NIGHT');
- expect(series.objects).toHaveLength(1);
- expect(series.objects[0].name).toBe('The Locket');
+ // Phase B.4: canon lives on the universe, not the series. promote
+ // mints a fresh universe for the work and links the series via
+ // universeId; the series itself no longer carries the canon arrays.
+ expect(series.universeId).toBeTruthy();
+ const universe = await universeSvc.getUniverse(series.universeId);
+ expect(universe.name).toBe('Test Work');
+ expect(universe.characters).toHaveLength(1);
+ expect(universe.characters[0].name).toBe('Aria');
+ expect(universe.characters[0].physicalDescription).toBe('tall, freckles');
+ expect(universe.settings).toHaveLength(1);
+ expect(universe.settings[0].slugline).toBe('INT. FOUNDRY — NIGHT');
+ expect(universe.objects).toHaveLength(1);
+ expect(universe.objects[0].name).toBe('The Locket');
});
it('is idempotent: a second promote returns the same series/issue with reused=true', async () => {