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([extraction-after-comicscript-teleplay-stages]): manual canon extraction from script stages
[._.]/ Adam Eivy132ff5b83a09
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 86846c6e6f..790f461755 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -27,6 +27,10 @@- **Removed duplicate Universe Builder tab.** The MediaGen tab strip no longer shows a Universe Builder entry — the Create sidebar already links straight to `/universe-builder`. Legacy `/media/universe-builder/*` URLs redirect to the top-level routes so bookmarks keep working.- **Image Gen — multi-reference editing for FLUX.2 (UI + server contract).** A 4-slot reference-image picker appears under the Init Image block whenever a FLUX.2 model is selected. Each slot accepts a PNG/JPG/WebP upload with a 0..1 strength slider; populated slots are packed in submit order and posted as `referenceImage1`…`referenceImage4` multipart fields with a parallel `referenceStrengths` array. New `optionalUploadFields` helper in `server/lib/multipart.js`; the Image Gen route extends `generateSchema` with `referenceStrengths` (max 4 entries, 0..1 each), copies each upload into a sibling `data/image-refs/` directory (NOT the gallery) so refs never surface in the flat `.png` listing, and threads the paths + strengths through `local.js` → `buildArgs` → the FLUX.2 Python runner via `--reference-images`/`--reference-strengths`. The UI shows an "Experimental — no-op today" banner above the slot grid: the Python runner currently ignores these flags pending the `FLUX.2-klein-9B-kv` model swap (see PLAN.md `[flux2-multi-reference-python-runner]`), but accepts them as no-op argparse stubs so single-init renders still work. The route resolves the effective backend (`local` / `external` / `codex`) BEFORE staging any uploads and rejects refs with `REFERENCE_IMAGES_LOCAL_ONLY` for non-local backends + `REFERENCE_IMAGES_FLUX2_ONLY` for non-FLUX.2 models — both gates also unlink the multer-staged temp files before throwing, so a rejected request doesn't leak under `os.tmpdir()`.+### Pipeline++- **Manual canon extraction from comicScript / teleplay stages.** Auto-extract still runs only after `prose`, but a new "Extract canon" button on both script stages lets writers pull characters/places/objects that surface only in panel directions or dialogue cues (a barkeep in a stage direction, a recurring location named only in the script) into the linked universe on demand. New route `POST /api/pipeline/issues/:id/stages/:stageId/extract-canon` (`stageId` must be `comicScript` or `teleplay`) reads the stage's `output` as the corpus and reuses the generic `extractCanonFromProse` with the same `parallel: true` + `autoLock: true` + `sourceSeriesId` stamping as the prose auto-extract, so script-derived entries survive later AI refines and stay attributable. Returns the merged universe + per-kind counts so the UI toast can summarize the merge. Three precondition errors: `PIPELINE_CANON_EXTRACT_BAD_STAGE`, `PIPELINE_CANON_EXTRACT_NO_CORPUS`, `PIPELINE_CANON_EXTRACT_NO_UNIVERSE`. New shared component `ExtractCanonButton.jsx` (gated on stage content + linked universe; tooltip explains the specific blocker when disabled); wired into `TeleplayStage` via `TextStagePanel.extraActions` and `ComicScriptStage` directly in its header. Client helper `extractPipelineCanonFromScript` in `apiPipeline.js`. 5 new vitest cases cover all precondition guards + happy path for both stage IDs.+### Sharing- **"🔄 live" badge on inbox subscription rows.** Sharing → Inbox now flags subscription rows whose latest manifest was queued within the last 5 minutes with a small green pill (spinning RefreshCw icon + "live" label). Re-exports fire on every record edit with a 3s server-side debounce and propagate via chokidar in <1s, so a recently-received subscription is a real-time "sender is editing right now" signal. Pure `isLiveSubscription(item, now)` helper exported from `client/src/pages/Sharing.jsx` (handles null inputs + unparseable `receivedAt` + one-shot non-subscription shares without throwing); 5 new vitest cases in `Sharing.test.jsx`. Freshness is computed on render so the badge naturally decays as the page re-renders past the 5-min mark.diff --git a/DONE.md b/DONE.mdindex 184e7c5d33..7c9be9568a 100644--- a/DONE.md+++ b/DONE.md@@ -10,6 +10,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./### 2026-05-18+- **[extraction-after-comicscript-teleplay-stages] Extraction after comicScript / teleplay stages.** Resolves the deferred decision in favor of an opt-in, manually-triggered extraction: auto-extract stays prose-only (so the auto-pipeline isn't paying an extra LLM call per script stage on every issue), but writers can now pull canon from a script stage on demand. New route `POST /api/pipeline/issues/:id/stages/:stageId/extract-canon` (stageId must be `comicScript` or `teleplay`) reads `issue.stages[stageId].output` as the corpus and calls the existing generic `extractCanonFromProse` with the same `parallel: true` + `autoLock: true` + `sourceSeriesId` stamping the prose auto-extract uses, so script-derived entries survive later AI refines and stay attributable to the triggering series. Schema `extractCanonFromScriptSchema` accepts an optional `providerOverride`; the route also returns the merged universe plus `{ characters, places, objects }` counts so the UI toast can summarize the merge. Three precondition guards: `PIPELINE_CANON_EXTRACT_BAD_STAGE` (400) for any stage other than the two script stages, `PIPELINE_CANON_EXTRACT_NO_CORPUS` (400) when the script stage has no output, `PIPELINE_CANON_EXTRACT_NO_UNIVERSE` (400) when the series isn't linked to a universe. New shared component `client/src/components/pipeline/stages/ExtractCanonButton.jsx` (BookOpen icon + "Extract canon" label) is gated on stage content + linked universe and surfaces a tooltip explaining the specific blocker when disabled. Wired into both script stages: `TeleplayStage.jsx` passes it through `TextStagePanel`'s `extraActions` slot; `ComicScriptStage.jsx` mounts it directly in its header actions next to the Image-gen settings button. Client helper `extractPipelineCanonFromScript(issueId, stageId, body, options)` in `apiPipeline.js` follows the project's silent/toast convention (helper passes `{ silent: true }` since the button owns its own error toast). 5 new vitest cases in `server/routes/pipeline.test.js` cover all three precondition guards plus the happy path for both stage IDs, asserting the corpus is forwarded and the autoLock/sourceSeriesId stamping matches the prose auto-extract semantics. All 5570 server tests + 92 client tests pass; client build clean.- **[solidify-character-descriptions-before-visual] Solidify character descriptions before visual render.** Closed as superseded by the character bible expansion + artist reference sheet work (PR #310). The original spec called for a "Solidify characters" sidebar action running an LLM pass to synthesize one canonical `physicalDescription` from accumulated evidence. The underlying goal — solid, render-ready character descriptions before visual stages — is now met via a different mechanism: `sanitizeCharacter` carries 15 prose fields + 5 structured lists (`stats`, `colorPalette`, `props`, `expressions`, `handGestures`); `POST /api/universe-builder/:id/characters/:entryId/expand` runs an LLM no-clobber fill-blanks pass over the extended fields; `POST .../render-reference-sheet` produces a single dense artist reference sheet image that becomes the visual canonical anchor (`character.referenceSheetImageRef`); and downstream pipeline stages already read `physicalDescription` via `canonPrompt`'s shared field-precedence helper. The accumulated-evidence synthesis primitive itself was not built; if it's needed later (e.g. multi-issue prose extraction starts drifting per-character `physicalDescription` and a one-click "consolidate" pass becomes valuable), it should be a fresh PLAN item against the post-#310 baseline, not this one.- **[bible-kind-setting-rename-to-place] Bible `SETTING` kind rename to `PLACE`.** Completes the rename deferred from migration 018 (PR #265, 2026-05-17): renames the bible-domain "setting" entity to "place" everywhere it's an identifier. Server: `BIBLE_KIND.SETTING` → `PLACE` (value `'place'`), `BIBLE_FIELD[PLACE]` → `'places'`, `sanitizeSetting` → `sanitizePlace`, `matchSettingsInText` → `matchPlacesInText`, `PLACE_INT_EXT`/`PLACE_TIME_OF_DAY`/`PLACE_DESCRIPTION_MAX` constants, `CATEGORY_KINDS` plural `'settings'` → `'places'`, writers-room route `/works/:id/settings` → `/works/:id/places`, service file `writersRoom/settings.js` → `places.js` with `listPlaces/createPlace/updatePlace/deletePlace/mergeExtractedPlaces` exports and `wr-place-` id prefix, validation schemas (`writersRoomPlaceCreateSchema`/`UpdateSchema`/`placeBibleCreateSchema`/`UpdateSchema`), `canonPrompt` SHORT_SPEC/RICH_SPEC keys (server + client mirror), `seriesCanon.pickCanon` returns `places`, `canonUsage` keys on `places`, importer KIND_MAP, `universeBuilder.compilePrompts` CANON_TRUNKS, `universeBuilderExpand` LLM prompt + envelope key `parsed.places`. Persisted state migrated by `scripts/migrations/022-rename-bible-setting-to-place.js`: walks `data/universe-builder.json` (renames `state.universes[].settings[]` → `places[]`, `categories[k].kind 'settings'` → `'places'`), `data/pipeline-series.json` (legacy `settings[]` → `places[]`), and `data/writers-room/works/<id>/settings.json` → `places.json` with the inner `settings` key rewritten to `places`. The migration also patches `data/prompts/stages/writers-room-places.md` + `_partials/bible-deference.md` to use `{{existingPlacesJson}}` + `"places": [` when they match the OLD shipped MD5; customized templates are left alone (the drift surfaces in `setup-data.js`'s hash-check warning, which now treats the post-022 hash as the new shipped baseline with the pre-022 hash auto-updatable alongside migration 007's pre-007 hash). Client UI flips to the new vocabulary: `UniverseBuilder.jsx` `TRUNK_TABS` `kind: 'places'`, `mergeCanonByName(..., 'place')`, `pendingCanonAdditionsRef.places`, `bucketsByKind.places`, `groupBucketsByKind` returns `{ characters, places, objects, other }`, `WORLD_CATEGORY_DEFAULT_KINDS` `landscapes/environments/structures → 'places'`. Component updates: `NounsStage.jsx` (key/singular/match), `CanonCard.jsx` (`kind.key === 'places'`), `UniverseCanonSection.jsx` (key/apiKind), `StoryboardPanel.jsx` (`places` prop, `onPlacesChange`, `onRunPlaces`, `placesCount`, `BIBLE_KINDS.world.propName: 'places'`), `WorkEditor.jsx` (`ANALYSIS_KIND.PLACES`, `places` state, `listWritersRoomPlaces`), `ProseReader.jsx` + `proseTokenizer.jsx` (`places` prop), `ProseTokenPopover.jsx` (`places` prop), `apiWritersRoom.js` (`listWritersRoomPlaces`/`createWritersRoomPlace`/`updateWritersRoomPlace`/`deleteWritersRoomPlace`), `SettingsBible.jsx` imports updated. Non-goals stay untouched: `data/settings.json`, the Settings page, `/api/settings` routes, app-level user-prefs — all keep "settings" terminology. Existing pipeline canon entry id prefix `set-` is preserved (ids are opaque after creation; changing the prefix would force a second migration over per-entry records — pure churn). All 5499 server tests pass; 77 client tests pass. ~30 files touched.- **[tabpills-pipelineissue-status-dot-trailing-slot] Extend `<TabPills>` with a `trailing` slot to migrate `PipelineIssue.jsx`.** Added an optional `t.trailing` ReactNode to the tab shape, rendered after the count in both `underline` and `pills` variants of `client/src/components/ui/TabPills.jsx`. Migrated `client/src/pages/PipelineIssue.jsx`'s previously-inlined stage tab row (the 11th outlier — its per-tab `STATUS_DOT[status]` indicator didn't fit the prior contract) onto `<TabPills>`, with the status dot supplied via `trailing`. Net 22-line bespoke `<button>` block collapsed onto the shared primitive; the row also picks up the standard mobile touch-target (`min-h-[44px]`) and icon size (16 vs 14) used elsewhere. +1 vitest case in `TabPills.test.jsx` pins the DOM-order contract (`trailing` follows `count`) in both variants; all 78 client tests pass.diff --git a/PLAN.md b/PLAN.mdindex 1aceafabde..a950c15c54 100644--- a/PLAN.md+++ b/PLAN.md@@ -44,7 +44,6 @@ _Nothing currently parked — pick the next item from the Backlog._### Pipeline continuity / approval-- [ ] [extraction-after-comicscript-teleplay-stages] **Extraction after comicScript / teleplay stages.** Decide whether to also run extraction post-script or accept the gap for minor characters introduced only at script time.- [ ] [resolve-issues-inherits-verify-gaps-verify-the] **Resolve-issues inherits verify gaps.** Verify the resolve prompt USES episode synopses when patching the arc.- [ ] [per-season-and-per-field-locks-extend-arc-lock] **Per-season + per-field locks.** Arc-level lock shipped (`LOCKABLE_STAGES = ['arc']` in `server/services/pipeline/series.js:59`, enforced at `server/services/pipeline/arcPlanner.js:231`); extend to seasons and per-field. Gate bulk runners (`bulkReassignSeason` at `server/services/pipeline/issues.js:418` has no lock check today). Surface a stage-progress strip in `client/src/pages/PipelineIssue.jsx`.- [ ] [pipeline-idea-stage-character-detail-plumbing] **Plumb character `physicalDescription`/`personality`/`background` into idea-stage prompt.** Today `data.sample/prompts/stages/pipeline-idea-expansion.md:16` iterates `{{#series.characters}}` with `name`/`description` only — richer bible fields are dropped.diff --git a/client/src/components/pipeline/stages/ComicScriptStage.jsx b/client/src/components/pipeline/stages/ComicScriptStage.jsxindex da3257adf8..20259dda3c 100644--- a/client/src/components/pipeline/stages/ComicScriptStage.jsx+++ b/client/src/components/pipeline/stages/ComicScriptStage.jsx@@ -32,6 +32,7 @@ import MediaPreview from '../../media/MediaPreview';import VisualStylePicker from '../VisualStylePicker';import Drawer from '../../Drawer';import ImageGenSettingsForm from '../../imageGen/ImageGenSettingsForm';+import ExtractCanonButton from './ExtractCanonButton';import { deriveAvailableBackends } from '../../../lib/imageGenBackends';import {PIPELINE_IMAGE_DEFAULTS,@@ -491,6 +492,12 @@ export default function ComicScriptStage({ issue, series, onStageUpdate, actions><SettingsIcon size={12} /> Image gen</button>+ <ExtractCanonButton+ issue={issue}+ series={series}+ stageId="comicScript"+ gated={actionsGated}+ />{hasScript && pages.length === 0 ? (<buttontype="button"diff --git a/client/src/components/pipeline/stages/ExtractCanonButton.jsx b/client/src/components/pipeline/stages/ExtractCanonButton.jsxnew file mode 100644index 0000000000..99abe66a0c--- /dev/null+++ b/client/src/components/pipeline/stages/ExtractCanonButton.jsx@@ -0,0 +1,56 @@+import { useState } from 'react';+import { Loader2, BookOpen } from 'lucide-react';+import toast from '../../ui/Toast';+import { extractPipelineCanonFromScript } from '../../../services/apiPipeline';++// Manual canon-extraction trigger for the comicScript / teleplay stages.+// Auto-extract runs only after `prose` (server/services/pipeline/textStages.js),+// so characters/places/objects introduced only in panel directions or+// dialogue cues never make it into the bible until the writer clicks this.+function getTooltip({ gated, hasContent, hasUniverse, busy, stageId }) {+ if (gated) return 'Saving settings…';+ if (!hasContent) return `Generate the ${stageId} stage first`;+ if (!hasUniverse) return 'Link a universe to the series first — extraction needs a target bible.';+ if (busy) return 'Extraction in progress…';+ return 'Extract characters / places / objects from this script and merge into the linked universe.';+}++export default function ExtractCanonButton({ issue, series, stageId, gated = false }) {+ const [busy, setBusy] = useState(false);+ const hasContent = !!(issue.stages?.[stageId]?.output || '').trim();+ const hasUniverse = !!series?.universeId;+ const disabled = busy || gated || !hasContent || !hasUniverse;+ const tooltip = getTooltip({ gated, hasContent, hasUniverse, busy, stageId });++ const handleClick = async () => {+ setBusy(true);+ const result = await extractPipelineCanonFromScript(issue.id, stageId, {}, { silent: true })+ .catch((err) => {+ toast.error(err.message || 'Canon extraction failed');+ return null;+ });+ setBusy(false);+ if (!result) return;+ const c = result.extracted?.characters || 0;+ const p = result.extracted?.places || 0;+ const o = result.extracted?.objects || 0;+ toast.success(+ `Extracted ${c} character${c === 1 ? '' : 's'}, ${p} place${p === 1 ? '' : 's'}, ${o} object${o === 1 ? '' : 's'} into the universe`,+ );+ };++ return (+ <button+ type="button"+ onClick={disabled ? undefined : handleClick}+ aria-disabled={disabled || undefined}+ title={tooltip}+ className={`inline-flex items-center gap-1 px-2 py-1.5 rounded-lg text-xs border bg-port-card text-gray-300 hover:border-port-accent/50 hover:text-white border-port-border ${+ disabled ? 'opacity-40 cursor-not-allowed' : ''+ }`}+ >+ {busy ? <Loader2 size={12} className="animate-spin" /> : <BookOpen size={12} />}+ Extract canon+ </button>+ );+}diff --git a/client/src/components/pipeline/stages/TeleplayStage.jsx b/client/src/components/pipeline/stages/TeleplayStage.jsxindex 942912bd40..02a9c7d35c 100644--- a/client/src/components/pipeline/stages/TeleplayStage.jsx+++ b/client/src/components/pipeline/stages/TeleplayStage.jsx@@ -1,4 +1,5 @@import TextStagePanel from './TextStagePanel';+import ExtractCanonButton from './ExtractCanonButton';export default function TeleplayStage(props) {return (@@ -7,6 +8,14 @@ export default function TeleplayStage(props) {stageId="teleplay"generateLabel="Adapt to teleplay"outputPlaceholder="Slugline → action → dialogue. Standard TV format with act breaks. Generated from the prose stage; iterates independently of the comic script."+ extraActions={(+ <ExtractCanonButton+ issue={props.issue}+ series={props.series}+ stageId="teleplay"+ gated={props.actionsGated}+ />+ )}/>);}diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex 93bfdc02f8..7ecac4cc40 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -157,6 +157,18 @@ export const extractPipelineComicPages = (issueId, { force } = {}) =>body: JSON.stringify({ force }),});+// Run canon extraction (characters/places/objects) against an issue's+// comicScript or teleplay stage output and merge the result into the series'+// linked universe. Auto-extract only fires after prose; this lets the writer+// pull in minor entities introduced only in script-stage panel directions or+// dialogue cues. Returns { universe, extracted: { characters, places, objects }, sourceStage }.+export const extractPipelineCanonFromScript = (issueId, stageId, { providerOverride } = {}, options = {}) =>+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/${encodeURIComponent(stageId)}/extract-canon`, {+ method: 'POST',+ body: JSON.stringify({ providerOverride }),+ ...options,+ });+// Render a full comic page (multi-panel layout in one image) — the default// for cloud image models (Codex / Google), draft-quality for local models.// Server persists the returned jobId on stages.comicPages.pages[pageIndex].diff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex a043c9c8de..1b5673720f 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -449,6 +449,18 @@ const extractComicPagesSchema = z.object({force: z.boolean().optional(),});+const extractCanonFromScriptSchema = z.object({+ providerOverride: z.string().trim().max(80).optional(),+});++// Collapses the `extractCanonFromProse` result-shape trio used by both the+// season-episodes continuity extract and the manual script-stage extract.+const countExtractedCanon = (results) => ({+ characters: results.characters?.extracted?.length || 0,+ places: results.places?.extracted?.length || 0,+ objects: results.objects?.extracted?.length || 0,+});+const comicPagePatchSchema = z.object({rawText: z.string().max(40000),});@@ -979,9 +991,7 @@ router.post('/series/:id/seasons/:seasonId/episodes/generate', asyncHandler(asyn});if (extractRes) {bibleExtracted = {- characters: extractRes.results.characters?.extracted?.length || 0,- places: extractRes.results.places?.extracted?.length || 0,- objects: extractRes.results.objects?.extracted?.length || 0,+ ...countExtractedCanon(extractRes.results),universe: extractRes.universe,};}@@ -1360,6 +1370,50 @@ router.post('/issues/:id/stages/comicPages/extract-pages', asyncHandler(async (r});}));+// Auto-extract runs only after `prose` (textStages.js:233); this endpoint+// lets the writer pull canon from a script stage on demand so characters+// introduced only in panel directions or dialogue cues land in the bible.+// Same autoLock + sourceSeriesId stamping as prose extraction so script-+// derived entries survive later AI refines.+router.post('/issues/:id/stages/:stageId/extract-canon', asyncHandler(async (req, res) => {+ const { id, stageId } = req.params;+ if (stageId !== 'comicScript' && stageId !== 'teleplay') {+ throw new ServerError(+ `Stage "${stageId}" does not support canon extraction — supported: comicScript, teleplay`,+ { status: 400, code: 'PIPELINE_CANON_EXTRACT_BAD_STAGE' },+ );+ }+ const body = validateRequest(extractCanonFromScriptSchema, req.body ?? {});+ const issue = await issuesSvc.getIssue(id).catch((err) => { throw mapServiceError(err); });+ const corpus = (issue.stages?.[stageId]?.output || '').trim();+ if (!corpus) {+ throw new ServerError(+ `Cannot extract canon — issue's ${stageId} stage is empty`,+ { status: 400, code: 'PIPELINE_CANON_EXTRACT_NO_CORPUS' },+ );+ }+ const series = await seriesSvc.getSeries(issue.seriesId).catch((err) => { throw mapServiceError(err); });+ if (!series.universeId) {+ throw new ServerError(+ `Cannot extract canon — series has no linked universe. Link a universe in the series settings first.`,+ { status: 400, code: 'PIPELINE_CANON_EXTRACT_NO_UNIVERSE' },+ );+ }+ const result = await extractCanonFromProse(series.universeId, {+ corpus,+ providerOverride: body.providerOverride,+ parallel: true,+ autoLock: true,+ sourceSeriesId: series.id,+ }).catch((err) => { throw mapServiceError(err); });++ res.json({+ universe: result.universe,+ extracted: countExtractedCanon(result.results),+ sourceStage: stageId,+ });+}));+// Per-page rawText patch — re-parses panels from the edited markdown so a// subsequent render still gets a structured prompt. Page's `imageJobId` is// preserved so the user doesn't lose an in-flight render after a save.diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.jsindex bdd33eb96b..b9f918e0e3 100644--- a/server/routes/pipeline.test.js+++ b/server/routes/pipeline.test.js@@ -769,6 +769,114 @@ describe('pipeline routes', () => {expect(r.body.issue.stages.comicPages.cover.script).toBe('user edit');});+ // ---- :stageId/extract-canon (manual canon extraction from comicScript / teleplay) ----++ it('POST /issues/:id/stages/:stageId/extract-canon 400s when stage is not comicScript or teleplay', 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/issues/${iss.body.id}/stages/prose/extract-canon`)+ .send({});+ expect(r.status).toBe(400);+ expect(r.body.code).toBe('PIPELINE_CANON_EXTRACT_BAD_STAGE');+ });++ it('POST /issues/:id/stages/:stageId/extract-canon 400s when the script stage is empty', 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/issues/${iss.body.id}/stages/comicScript/extract-canon`)+ .send({});+ expect(r.status).toBe(400);+ expect(r.body.code).toBe('PIPELINE_CANON_EXTRACT_NO_CORPUS');+ });++ it('POST /issues/:id/stages/:stageId/extract-canon 400s when series has no linked universe', 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' });+ await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({+ stages: { comicScript: { status: 'ready', output: '## Page 1\n\n### Panel 1\n**Description:** A barkeep slides a glass.' } },+ });+ const r = await request(app)+ .post(`/api/pipeline/issues/${iss.body.id}/stages/comicScript/extract-canon`)+ .send({});+ expect(r.status).toBe(400);+ expect(r.body.code).toBe('PIPELINE_CANON_EXTRACT_NO_UNIVERSE');+ });++ it('POST /issues/:id/stages/comicScript/extract-canon merges into the linked universe and returns counts', async () => {+ const canonSvc = await import('../services/universeCanon.js');+ const spy = vi.spyOn(canonSvc, 'extractCanonFromProse').mockImplementation(async (universeId, opts) => ({+ universe: { id: universeId, name: 'U', characters: [{ id: 'c1', name: 'Barkeep' }], places: [], objects: [] },+ results: {+ characters: { extracted: [{ name: 'Barkeep' }], runId: 'run-c' },+ places: { extracted: [], runId: 'run-p' },+ objects: { extracted: [], runId: 'run-o' },+ },+ _spiedOpts: opts,+ }));++ const app = makeApp();+ const uni = await universeSvc.createUniverse({ name: 'U' });+ const ser = await request(app).post('/api/pipeline/series').send({ 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({+ stages: {+ comicScript: { status: 'ready', output: '## Page 1\n\n### Panel 1\n**Description:** A barkeep slides a glass to Lina.' },+ },+ });+ const r = await request(app)+ .post(`/api/pipeline/issues/${iss.body.id}/stages/comicScript/extract-canon`)+ .send({});+ expect(r.status).toBe(200);+ expect(r.body.sourceStage).toBe('comicScript');+ expect(r.body.extracted).toEqual({ characters: 1, places: 0, objects: 0 });+ expect(r.body.universe.id).toBe(uni.id);++ // Service was called with the script's output as corpus + stamp opts.+ expect(spy).toHaveBeenCalledTimes(1);+ const [calledUniverseId, calledOpts] = spy.mock.calls[0];+ expect(calledUniverseId).toBe(uni.id);+ expect(calledOpts.corpus).toContain('A barkeep slides a glass to Lina.');+ expect(calledOpts.parallel).toBe(true);+ expect(calledOpts.autoLock).toBe(true);+ expect(calledOpts.sourceSeriesId).toBe(ser.body.id);+ spy.mockRestore();+ });++ it('POST /issues/:id/stages/teleplay/extract-canon reads the teleplay stage output', async () => {+ const canonSvc = await import('../services/universeCanon.js');+ const spy = vi.spyOn(canonSvc, 'extractCanonFromProse').mockResolvedValue({+ universe: { id: 'u-mock', characters: [], places: [], objects: [] },+ results: {+ characters: { extracted: [{ name: 'Hostess' }, { name: 'Bouncer' }] },+ places: { extracted: [{ name: 'The Velvet Room' }] },+ objects: { extracted: [] },+ },+ });++ const app = makeApp();+ const uni = await universeSvc.createUniverse({ name: 'U' });+ const ser = await request(app).post('/api/pipeline/series').send({ 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({+ stages: {+ teleplay: { status: 'ready', output: 'INT. VELVET ROOM - NIGHT\n\nHOSTESS greets the BOUNCER at the door.' },+ },+ });+ const r = await request(app)+ .post(`/api/pipeline/issues/${iss.body.id}/stages/teleplay/extract-canon`)+ .send({});+ expect(r.status).toBe(200);+ expect(r.body.sourceStage).toBe('teleplay');+ expect(r.body.extracted).toEqual({ characters: 2, places: 1, objects: 0 });+ expect(spy.mock.calls[0][1].corpus).toContain('VELVET ROOM');+ spy.mockRestore();+ });+// ---- comicPages/pages/:pageIndex/render ----it('POST /issues/:id/stages/comicPages/pages/:pageIndex/render 400s for a non-integer pageIndex', async () => {