Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: pipeline arc continuity + per-series provider/model picker
[._.]/ Adam Eivy5b55e5782c88
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 85e43d19c6..4254e2afcb 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,45 @@## Added+- **Pipeline Series — configurable per-series AI provider + model.** The arc+ header now has provider + model dropdowns (mirroring the World Builder+ expansion picker) bound to a new `series.llm = { provider, model }` field.+ The choice persists on the series and is threaded into every arc operation —+ Generate / Regenerate arc, Verify arc, Resolve, and per-season Generate+ episodes — so the whole arc workflow runs against one consistent provider.+ Defaults to the active system provider when unset.++- **Pipeline Series — granular continuity context for season generation and+ verification.** When generating volume N's episode breakdown, the LLM now+ receives the actual per-episode beats of all prior volumes (pulled from each+ issue's `stages.idea.input`), not just the season-level synopses. The+ Verify arc pass also sees those per-episode synopses, so it can finally+ catch contradictions like "S1E7 introduces a character never referenced+ again" or "S2E3 implies a state S1's final episode hasn't reached" — the+ prompt has always asked for these checks, but with only episode titles+ visible the LLM had to bluff.++- **Pipeline Series — automatic bible extraction after generation.** After a+ successful per-season *Generate episodes* run, the server now extracts new+ characters / settings / objects mentioned in the new episode loglines and+ synopses, deduplicates them against the existing bible, and merges them in.+ The same extraction also fires after every successful prose-stage+ generation (`stages.prose`). Result: characters introduced mid-writing flow+ back into the series bible automatically, so downstream visual stages+ render the same character consistently across issues. Toast on the+ episodes-generate flow now reads `"Generated 11 episodes (+3 chars, +2+ settings, +1 objects extracted)"`.++- **Pipeline Series — character physical descriptions reach image+ composers.** `composeComicPagePrompt` and `composeVisualPrompt` now receive+ the matched character profiles for everyone speaking on the page or named+ in a storyboard scene's description, and prepend a "Featuring — NAME:+ <physicalDescription>; ..." clause to the diffusion prompt. A new+ `matchCharactersInText` helper word-boundary-scans free-text scene+ descriptions for bible character names + aliases (the comic-page path uses+ the structured dialogue character field directly). Same character now+ renders the same way across panels, pages, and scenes.+- **Pipeline Series — auto-resolve verification findings.** The verify panelnow has a *Resolve all* button at the top and a per-finding *Resolve* buttonon each row. Each kicks off an LLM pass that rewrites the arc + volume@@ -34,6 +73,13 @@## Changed+- **Pipeline Series — Regenerate arc button no longer requires two clicks.**+ Dropped the `useArmedAction` two-click-arm pattern from the regenerate+ button; one click runs. The pattern was confusing — users didn't realize+ "Click again to replace" was an instruction rather than a status. The+ delete-season and delete-issue buttons keep the arm pattern since they're+ hover-revealed trash icons where misclick risk is real.+- **Pipeline Series — combined comic/TV terminology.** Every series now shipsin both formats by default — graphic novel (issues → volumes) AND TV(episodes → seasons). Dropped the *Target format* picker from the new-diff --git a/PLAN.md b/PLAN.mdindex 965d0fbcf8..69147139b9 100644--- a/PLAN.md+++ b/PLAN.md@@ -6,6 +6,18 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]## Next Up+### Pipeline continuity gaps — deferred from arc-planning rollout++Captured 2026-05-13 while landing layer-1 (prior episodes in season prompt), layer-2 (post-episode-generate extraction), prose-extraction, verify episode-synopsis context, and character descriptions in visual composers. These are the remaining audit gaps from `pipeline/arcPlanner.js` + `pipeline/visualStages.js` + `pipeline/textStages.js`:++- [ ] **Idea-stage character context.** `pipeline-idea-expansion` template (called from `textStages.js:92`) sees only character `name` in `series.characters`, not `physicalDescription` / `personality` / `background`. Idea-stage LLM has no anchor when expanding a prompt that names existing characters — it can invent contradictory traits. Trim long fields, send the full character shape (matching the prose stage's context shape).+- [ ] **Setting palette/era/weather plumbed to visual stages.** `storyBible.js` setting shape carries `palette`, `era`, `weather`, `recurringDetails`, but `composeVisualPrompt` / `composeComicPagePrompt` only consult `description`. The fields exist for image renderers — wire `matchSceneSetting`'s match through into a "Setting: <era> <palette> <recurring>" prefix on the rendered prompt.+- [ ] **World-entity name validation in text stages.** Arc-verify checks world drift (factions/characters/locations the arc names that don't exist in the World Builder world), but per-issue text stages (idea → prose → script) don't reference world entities at all. New world entities introduced in volumes 2/3 of a series aren't surfaced to the prose LLM. Add a `worldEntitiesSummary` prompt var to the prose stage, similar to how arc-overview gets `worldCategoriesText`.+- [ ] **Character voice / speech-pattern field.** Current character shape has `personality` + `background` but no dedicated `voice` / `speech patterns` field. Prose and script generation can't carry voice consistency across issues without an authored anchor. Either add a `voice` field to the bible schema (and bibleExtractor stage prompt) or document that voice should land in `personality`.+- [ ] **Extraction after comicScript / tvScript stages.** Layer-2 extraction now runs after prose. Scripts derive FROM prose so most new characters should already be in the bible, but minor characters introduced only at script time (named extras, throwaway villains) still slip through. Decide whether to also run extraction post-script or accept the gap.+- [ ] **Solidify character descriptions before visual render.** User asked: as the series progresses, characters accumulate descriptions across multiple extractions but may still have gaps. Add a "Solidify characters" action in the bible sidebar that runs an LLM pass synthesizing one canonical `physicalDescription` per character from all accumulated `firstAppearance` + `evidence` + existing text. Useful before kicking off the visual render passes for an issue.+- [ ] **Resolve-issues inherits verify gaps.** Verify and resolve share `buildVerifyContext` so the new episode-synopsis context is already wired into both. But double-check the resolve LLM prompt instructs it to USE episode synopses when patching the arc — otherwise it'll just rewrite season-level synopses and leave per-episode contradictions intact.+- [ ] **Fix `lib/creativeDirectorPrompts.test.js` imageStrength wording assertions.** 3 tests in `server/lib/creativeDirectorPrompts.test.js` (around line 210) fail on `expect(out).toContain('Image strength: default')` — the prompt template no longer emits that exact phrasing for unset/null imageStrength. Pre-existing on `main` (verified 2026-05-12 while landing world-bible → pipeline wiring; out of scope for that PR). Either re-add the wording in the prompt builder or update the test to match the new output.### v1.54.0 release-review deferred itemsdiff --git a/client/src/components/pipeline/ArcCanvas.jsx b/client/src/components/pipeline/ArcCanvas.jsxindex 77f928d445..8328f163a9 100644--- a/client/src/components/pipeline/ArcCanvas.jsx+++ b/client/src/components/pipeline/ArcCanvas.jsx@@ -23,7 +23,7 @@* responsive without a refetch.*/-import { useState } from 'react';+import { useEffect, useMemo, useState } from 'react';import { Link } from 'react-router-dom';import {Plus, Trash2, Loader2, Sparkles, ShieldCheck, ChevronRight, ChevronDown,@@ -38,6 +38,7 @@ import {generatePipelineArcOverview, generatePipelineSeasonEpisodes, verifyPipelineArc,resolvePipelineArcIssues,listPipelineIssues, updatePipelineSeries,+ getProviders,} from '../../services/api';const ISSUE_STATUS_COLORS = {@@ -114,10 +115,26 @@ function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {// Which finding indexes have an in-flight per-finding resolve. Lets the row// show its own spinner without blocking the rest of the page.const [resolvingIdx, setResolvingIdx] = useState(new Set());-- // Persist any pending bible edits BEFORE the LLM call reads from the server.- // Without this, typing "32" into the issue count and clicking Regenerate- // would run against the previously-saved value.+ const [providers, setProviders] = useState([]);+ const [activeProviderId, setActiveProviderId] = useState(null);++ useEffect(() => {+ getProviders()+ .then((data) => {+ setProviders(data?.providers || []);+ setActiveProviderId(data?.activeProvider || null);+ })+ .catch(() => { /* dropdowns just show "Active provider" fallback */ });+ }, []);++ const llmOverride = useMemo(() => ({+ providerOverride: series.llm?.provider || undefined,+ modelOverride: series.llm?.model || undefined,+ }), [series.llm?.provider, series.llm?.model]);++ // Persist pending bible edits BEFORE the LLM call reads from the server,+ // so typing "32" into the issue count and clicking Regenerate runs against+ // the on-screen value, not the previously-saved one.const withFlush = async (fn) => {if (onFlushPending) await onFlushPending();return fn();@@ -126,7 +143,7 @@ function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {const runGenerate = async () => {setRunning('generate');const result = await withFlush(() =>- generatePipelineArcOverview(series.id, { commit: true }).catch((err) => {+ generatePipelineArcOverview(series.id, { commit: true, ...llmOverride }).catch((err) => {toast.error(err.message || 'Failed to generate arc');return null;}),@@ -136,15 +153,10 @@ function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {onSeriesUpdate(result.series);toast.success('Arc generated and saved');};- // Two-click-arm pattern only applies when there's already an arc to clobber- // — first-time generation skips the confirm.- const [armReplace, armedGenerate] = useArmedAction(runGenerate);- const tryGenerate = () => (arc ? armedGenerate() : runGenerate());-const runVerify = async () => {setRunning('verify');const result = await withFlush(() =>- verifyPipelineArc(series.id).catch((err) => {+ verifyPipelineArc(series.id, llmOverride).catch((err) => {toast.error(err.message || 'Failed to verify arc');return null;}),@@ -166,6 +178,7 @@ function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {const result = await withFlush(() =>resolvePipelineArcIssues(series.id, {findings: findingsSubset,+ ...llmOverride,}).catch((err) => {toast.error(err.message || 'Auto-resolve failed');return null;@@ -206,24 +219,65 @@ function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {}};- const generateBtnLabel = !arc ? 'Generate arc'- : armReplace ? 'Click again to replace'- : 'Regenerate arc';+ const generateBtnLabel = arc ? 'Regenerate arc' : 'Generate arc';++ const providerLabel = (id) => providers.find((p) => p.id === id)?.name || id || '—';+ const providerModels = useMemo(() => {+ const p = providers.find((x) => x.id === series.llm?.provider)+ || providers.find((x) => x.id === activeProviderId);+ return p?.models || [];+ }, [providers, activeProviderId, series.llm?.provider]);++ // Save on change rather than waiting for a "Save" button — verify / resolve /+ // episode-gen all read series.llm at request time, so a delayed save would+ // run a generation against a stale choice.+ const saveLlm = async (next) => {+ const updated = await updatePipelineSeries(series.id, { llm: next }).catch((err) => {+ toast.error(err.message || 'Failed to save provider choice');+ return null;+ });+ if (updated) onSeriesUpdate(updated);+ };return (<section className="bg-port-card border border-port-border rounded-lg p-4 space-y-3"><div className="flex items-center justify-between flex-wrap gap-2"><h2 className="text-xs uppercase tracking-wider text-gray-500">Series arc</h2><div className="flex items-center gap-2 flex-wrap">+ {/* Bind to `?? ''` (NOT `|| activeProviderId || ''`) — unset must+ select the "Active provider" empty option, otherwise the dropdown+ would silently pin the active provider as if the user had chosen it. */}+ <select+ value={series.llm?.provider ?? ''}+ onChange={(e) => saveLlm({ provider: e.target.value || null, model: null })}+ disabled={!!running}+ title="AI provider for arc generate / verify / resolve / episode generation"+ className="bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-xs disabled:opacity-40"+ >+ <option value="">Active provider ({providerLabel(activeProviderId)})</option>+ {providers.map((p) => (+ <option key={p.id} value={p.id}>{p.name}</option>+ ))}+ </select>+ <select+ value={series.llm?.model || ''}+ onChange={(e) => saveLlm({ ...(series.llm || {}), model: e.target.value || null })}+ disabled={!!running || providerModels.length === 0}+ title="Model for arc operations"+ className="bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-xs disabled:opacity-40 max-w-[180px]"+ >+ <option value="">Default model</option>+ {providerModels.map((m) => {+ const id = typeof m === 'string' ? m : m.id;+ const label = typeof m === 'string' ? m : (m.name || m.id);+ return <option key={id} value={id}>{label}</option>;+ })}+ </select><buttontype="button"- onClick={tryGenerate}+ onClick={runGenerate}disabled={!!running}- className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded text-sm font-medium border transition-colors ${- armReplace- ? 'bg-port-warning/10 text-port-warning border-port-warning/40'- : 'bg-port-bg text-port-accent border-port-border hover:border-port-accent/40'- } disabled:opacity-40`}+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded text-sm font-medium border transition-colors bg-port-bg text-port-accent border-port-border hover:border-port-accent/40 disabled:opacity-40">{running === 'generate' ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}{generateBtnLabel}@@ -458,18 +512,26 @@ function SeasonRow({ series, season, seasons, issues, onSeriesUpdate, onIssuesUpreturn;}setGeneratingEpisodes(true);- const result = await generatePipelineSeasonEpisodes(series.id, season.id, { commit: true })+ const result = await generatePipelineSeasonEpisodes(series.id, season.id, {+ commit: true,+ providerOverride: series.llm?.provider || undefined,+ modelOverride: series.llm?.model || undefined,+ }).catch((err) => {toast.error(err.message || 'Failed to generate issues / episodes');return null;});setGeneratingEpisodes(false);if (!result) return;- // Refresh the issues list so the new ones land under this volume.const refreshed = await listPipelineIssues(series.id).catch(() => null);if (refreshed) onIssuesUpdate(refreshed);+ if (result.bibleExtracted?.series) onSeriesUpdate(result.bibleExtracted.series);const n = result.createdIssues?.length || 0;- toast.success(`Generated ${n} issue${n === 1 ? '' : 's'} / episode${n === 1 ? '' : 's'}`);+ const extracted = result.bibleExtracted;+ const extractedSummary = extracted+ ? ` (+${extracted.characters} chars, +${extracted.settings} settings, +${extracted.objects} objects extracted)`+ : '';+ toast.success(`Generated ${n} issue${n === 1 ? '' : 's'} / episode${n === 1 ? '' : 's'}${extractedSummary}`);};const runDeleteSeason = async () => {diff --git a/client/src/lib/scenePrompt.js b/client/src/lib/scenePrompt.jsindex 4da7309b0c..358088652d 100644--- a/client/src/lib/scenePrompt.js+++ b/client/src/lib/scenePrompt.js@@ -35,6 +35,28 @@ export function matchSceneCharacters(sceneCharacterNames = [], charByKey) {return matched;}+export function matchCharactersInText(text, allCharacters) {+ if (!text || !Array.isArray(allCharacters) || !allCharacters.length) return [];+ const haystack = String(text);+ const matched = [];+ const seen = new Set();+ const wordBoundary = (needle) => {+ if (!needle) return false;+ const escaped = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ return new RegExp(`\\b${escaped}\\b`, 'i').test(haystack);+ };+ for (const profile of allCharacters) {+ const key = profile.id || profile.name;+ if (!key || seen.has(key)) continue;+ const candidates = [profile.name, ...(profile.aliases || [])].filter(Boolean);+ if (candidates.some(wordBoundary)) {+ matched.push(profile);+ seen.add(key);+ }+ }+ return matched;+}+export function buildSettingByKey(allSettings) {const map = new Map();for (const setting of allSettings || []) {diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsxindex c4bf5d3439..f2e9e55215 100644--- a/client/src/pages/PipelineSeries.jsx+++ b/client/src/pages/PipelineSeries.jsx@@ -94,7 +94,8 @@ export default function PipelineSeries() {const saved = lastSavedRef.current || series;const fields = ['name', 'logline', 'premise', 'styleNotes', 'issueCountTarget', 'worldId'];const dirty = fields.some((k) => (series[k] ?? '') !== (saved[k] ?? ''))- || JSON.stringify(series.characters || []) !== JSON.stringify(saved.characters || []);+ || JSON.stringify(series.characters || []) !== JSON.stringify(saved.characters || [])+ || JSON.stringify(series.llm || {}) !== JSON.stringify(saved.llm || {});if (!dirty) return false;const updated = await updatePipelineSeries(series.id, {name: series.name,@@ -104,6 +105,7 @@ export default function PipelineSeries() {styleNotes: series.styleNotes,issueCountTarget: series.issueCountTarget,characters: series.characters,+ llm: series.llm || { provider: null, model: null },}).catch((err) => {toast.error(`Pre-flush save failed: ${err.message}`);return null;diff --git a/server/lib/scenePrompt.js b/server/lib/scenePrompt.jsindex 4bc509a312..51123c6928 100644--- a/server/lib/scenePrompt.js+++ b/server/lib/scenePrompt.js@@ -41,6 +41,35 @@ export function matchSceneCharacters(sceneCharacterNames = [], charByKey) {return matched;}+/**+ * Scan a free-form text blob (panel/scene description) for any character+ * names or aliases from the bible. Word-boundary matching, case-insensitive.+ * Used when the visual record doesn't carry a structured character list (e.g.+ * storyboard scenes only have a free-text description). Keeps the prompt+ * grounded in bible-canonical descriptions for everyone the LLM named.+ */+export function matchCharactersInText(text, allCharacters) {+ if (!text || !Array.isArray(allCharacters) || !allCharacters.length) return [];+ const haystack = String(text);+ const matched = [];+ const seen = new Set();+ const wordBoundary = (needle) => {+ if (!needle) return false;+ const escaped = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ return new RegExp(`\\b${escaped}\\b`, 'i').test(haystack);+ };+ for (const profile of allCharacters) {+ const key = profile.id || profile.name;+ if (!key || seen.has(key)) continue;+ const candidates = [profile.name, ...(profile.aliases || [])].filter(Boolean);+ if (candidates.some(wordBoundary)) {+ matched.push(profile);+ seen.add(key);+ }+ }+ return matched;+}+export function buildSettingByKey(allSettings) {const map = new Map();for (const setting of allSettings || []) {diff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex c17a4bf6ec..9f9e93e202 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -48,6 +48,7 @@ import { startEpisodeVideoForIssue, ERR_NO_STORYBOARDS } from '../services/pipelimport { ASPECT_RATIOS, QUALITIES } from '../lib/creativeDirectorPresets.js';import { extractScenes, SOURCE_KIND } from '../lib/sceneExtractor.js';import { parseComicScript } from '../lib/comicScriptParser.js';+import { llmSchema } from './worldBuilder.js';import { BIBLE_KIND } from '../lib/storyBible.js';import { ARC_LIMITS, ARC_STATUSES, SEASON_STATUSES } from '../lib/storyArc.js';@@ -140,6 +141,7 @@ const seriesCreateSchema = z.object({styleNotes: z.string().trim().max(seriesSvc.STYLE_NOTES_MAX).optional().default(''),targetFormat: z.enum(seriesSvc.TARGET_FORMATS).optional(),issueCountTarget: z.number().int().min(0).max(seriesSvc.ISSUE_COUNT_TARGET_MAX).optional(),+ llm: llmSchema,});const seriesPatchSchema = z.object({@@ -156,6 +158,7 @@ const seriesPatchSchema = z.object({styleNotes: z.string().trim().max(seriesSvc.STYLE_NOTES_MAX).optional(),targetFormat: z.enum(seriesSvc.TARGET_FORMATS).optional(),issueCountTarget: z.number().int().min(0).max(seriesSvc.ISSUE_COUNT_TARGET_MAX).optional(),+ llm: llmSchema,}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });// Season-resource schemas: dedicated CRUD on a sibling resource so the@@ -497,6 +500,7 @@ router.post('/series/:id/seasons/:seasonId/episodes/generate', asyncHandler(asyn.catch((err) => { throw mapServiceError(err); });const createdIssues = [];+ let bibleExtracted = null;if (body.commit) {// Create one issue per episode under this season. The issue sanitizer// already accepts `seasonId` + `arcPosition`, so we forward them in the@@ -521,6 +525,31 @@ router.post('/series/:id/seasons/:seasonId/episodes/generate', asyncHandler(asyn});createdIssues.push(created);}++ // Non-fatal: episode creation already succeeded, so a noisy extraction+ // failure must not invalidate the user's accepted breakdown.+ 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, {+ corpus,+ providerOverride: body.providerOverride,+ parallel: true,+ }).catch((err) => {+ console.warn(`⚠️ Continuity extraction failed for season ${req.params.seasonId}: ${err.message}`);+ return null;+ });+ if (extractRes) {+ bibleExtracted = {+ characters: extractRes.results.characters?.extracted?.length || 0,+ settings: extractRes.results.settings?.extracted?.length || 0,+ objects: extractRes.results.objects?.extracted?.length || 0,+ series: extractRes.series,+ };+ }+ }}res.json({@@ -531,6 +560,7 @@ router.post('/series/:id/seasons/:seasonId/episodes/generate', asyncHandler(asynmodel: result.model,committed: !!body.commit,createdIssues,+ bibleExtracted,});}));diff --git a/server/routes/worldBuilder.js b/server/routes/worldBuilder.jsindex 01b8afd2cf..381d854b76 100644--- a/server/routes/worldBuilder.js+++ b/server/routes/worldBuilder.js@@ -62,7 +62,7 @@ const categoriesSchema = z.record(message: `categories cannot exceed ${svc.WORLD_CATEGORY_COUNT_MAX} buckets`,});-const llmSchema = z.object({+export const llmSchema = z.object({provider: z.string().trim().max(80).nullable().optional(),model: z.string().trim().max(200).nullable().optional(),}).optional();diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.jsindex 4f103fb4ae..a87bee9df0 100644--- a/server/services/pipeline/arcPlanner.js+++ b/server/services/pipeline/arcPlanner.js@@ -34,6 +34,23 @@ const makeErr = (message, code) => Object.assign(new Error(message), { code });const VERIFY_SEVERITIES = new Set(['high', 'medium', 'low']);const ARC_ROLES = new Set(['pilot', 'complication', 'midpoint', 'b-plot', 'all-is-lost', 'finale']);+// Each prior season renders as its header (logline + synopsis) plus the+// committed per-episode beats from `stages.idea.input` — that field was+// seeded with the LLM's `logline + synopsis` at episode-generate time.+function renderPriorSeason(s, priorIssues) {+ const header = `### Season ${s.number} — ${s.title}\n\n${s.logline}\n\n${s.synopsis || '(no synopsis)'}`;+ const seasonEpisodes = priorIssues+ .filter((iss) => iss.seasonId === s.id)+ .sort((a, b) => (a.arcPosition ?? 9999) - (b.arcPosition ?? 9999));+ if (seasonEpisodes.length === 0) return header;+ const lines = seasonEpisodes.map((iss) => {+ const idea = (iss.stages?.idea?.input || '').trim();+ const ord = iss.arcPosition || '?';+ return idea ? `- E${ord} — ${iss.title}: ${idea}` : `- E${ord} — ${iss.title}`;+ }).join('\n');+ return `${header}\n\nEpisode beats:\n${lines}`;+}+// The world is the canonical source for factions, characters, environments,// etc. — without this, the arc planner would only see the series' own// characters/settings/objects which are usually empty pre-prose.@@ -163,17 +180,15 @@ export async function generateArcOverview(seriesId, options = {}) {/*** Build the context for one season's episode breakdown. `priorSeasonsContext`- * is a textual summary of the seasons BEFORE this one (synopsis + logline),- * so the LLM has continuity to work against without re-reading every season.+ * gives the LLM granular per-episode continuity — without it the verifier and+ * planner only see season-level synopses and can't catch beat-level contradictions.*/-async function buildSeasonEpisodesContext(series, season, priorSeasons, preloadedWorld) {+async function buildSeasonEpisodesContext(series, season, priorSeasons, priorIssues = [], preloadedWorld) {const arc = series.arc || {};const themesCsv = Array.isArray(arc.themes) ? arc.themes.join(', ') : '';const priorSeasonsContext = priorSeasons.length === 0? '(this is the first season — no prior context)'- : priorSeasons- .map((s) => `### Season ${s.number} — ${s.title}\n\n${s.logline}\n\n${s.synopsis || '(no synopsis)'}`)- .join('\n\n');+ : priorSeasons.map((s) => renderPriorSeason(s, priorIssues)).join('\n\n');const world = await resolveWorldContext(series, preloadedWorld);return {series: {@@ -261,7 +276,14 @@ export async function generateSeasonEpisodes(seriesId, seasonId, options = {}) {// sanitizer; this matches what the user is editing on screen.const priorSeasons = seasons.filter((s) => (s.number || 0) < (season.number || 0));- const ctx = await buildSeasonEpisodesContext(series, season, priorSeasons);+ let priorIssues = [];+ if (priorSeasons.length > 0) {+ const priorIds = new Set(priorSeasons.map((s) => s.id));+ const all = await listIssues({ seriesId });+ priorIssues = all.filter((iss) => iss.seasonId && priorIds.has(iss.seasonId));+ }++ const ctx = await buildSeasonEpisodesContext(series, season, priorSeasons, priorIssues);const { content, runId, providerId, model } = await runStagedLLM('pipeline-season-episodes',ctx,@@ -299,11 +321,15 @@ async function buildVerifyContext(series, preloadedWorld) {for (const iss of issues) {const key = iss.seasonId || null;if (!issuesBySeason.has(key)) issuesBySeason.set(key, []);+ // `synopsis` key (not `beats`) so it matches the prompt's existing+ // language; sourced from idea.input which carries the LLM's logline+synopsis.+ const synopsis = (iss.stages?.idea?.input || '').trim();issuesBySeason.get(key).push({number: iss.number,title: iss.title,status: iss.status,arcPosition: iss.arcPosition,+ synopsis: synopsis || null,});}for (const list of issuesBySeason.values()) {diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex b028ec2790..9916460929 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -55,6 +55,12 @@ const sanitizeSeries = (raw) => {const issueCountTarget = Number.isFinite(raw.issueCountTarget)? Math.max(0, Math.min(ISSUE_COUNT_TARGET_MAX, Math.floor(raw.issueCountTarget))): 0;+ const llm = raw.llm && typeof raw.llm === 'object'+ ? {+ provider: trimTo(raw.llm.provider, 80) || null,+ model: trimTo(raw.llm.model, 200) || null,+ }+ : { provider: null, model: null };const createdAt = isStr(raw.createdAt) ? raw.createdAt : new Date().toISOString();const updatedAt = isStr(raw.updatedAt) ? raw.updatedAt : createdAt;return {@@ -77,6 +83,7 @@ const sanitizeSeries = (raw) => {styleNotes: trimTo(raw.styleNotes, STYLE_NOTES_MAX),targetFormat,issueCountTarget,+ llm,createdAt,updatedAt,};@@ -125,6 +132,7 @@ export async function createSeries(input = {}) {styleNotes: input.styleNotes || '',targetFormat: input.targetFormat || 'comic+tv',issueCountTarget: input.issueCountTarget || 0,+ llm: input.llm || null,createdAt: now,updatedAt: now,});@@ -138,6 +146,10 @@ export async function updateSeries(id, patch = {}) {const idx = state.series.findIndex((s) => s.id === id);if (idx < 0) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);const cur = state.series[idx];+ // Per-field merge so `{ provider: 'codex' }` doesn't clobber an existing `model`.+ const mergedLlm = 'llm' in patch+ ? { ...(cur.llm || {}), ...(patch.llm || {}) }+ : cur.llm;const merged = sanitizeSeries({...cur,...('name' in patch ? { name: patch.name } : {}),@@ -153,6 +165,7 @@ export async function updateSeries(id, patch = {}) {...('styleNotes' in patch ? { styleNotes: patch.styleNotes } : {}),...('targetFormat' in patch ? { targetFormat: patch.targetFormat } : {}),...('issueCountTarget' in patch ? { issueCountTarget: patch.issueCountTarget } : {}),+ llm: mergedLlm,updatedAt: new Date().toISOString(),});if (!merged) throw makeErr('Invalid series payload', ERR_VALIDATION);diff --git a/server/services/pipeline/textStages.js b/server/services/pipeline/textStages.jsindex dc4c48b5ae..9f7bcc8184 100644--- a/server/services/pipeline/textStages.js+++ b/server/services/pipeline/textStages.js@@ -15,7 +15,7 @@*/import { runStagedLLM } from '../../lib/stageRunner.js';-import { getSeries } from './series.js';+import { getSeries, extractAndMergeIntoSeries } from './series.js';import { getIssue, updateStage, TEXT_STAGE_IDS } from './issues.js';const STAGE_TO_TEMPLATE = Object.freeze({@@ -111,6 +111,20 @@ export async function generateStage(issueId, stageId, options = {}) {});console.log(`✅ Pipeline stage — issue=${issueId.slice(0, 8)} stage=${stageId} runId=${result.runId} length=${output.length}`);++ // 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, {+ corpus: output,+ providerOverride: options.providerId,+ parallel: true,+ }).catch((err) => {+ console.warn(`⚠️ Prose extraction failed for issue ${issueId.slice(0, 8)}: ${err.message}`);+ });+ }+return { issue: updatedIssue, stage, runId: result.runId };}diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.jsindex 89ea90aa6c..1d2aa3c821 100644--- a/server/services/pipeline/visualStages.js+++ b/server/services/pipeline/visualStages.js@@ -29,7 +29,10 @@ import { getSeries } from './series.js';import { getIssue, updateStage, VISUAL_STAGE_IDS } from './issues.js';import { getWorld } from '../worldBuilder.js';import { ServerError } from '../../lib/errorHandler.js';-import { buildScenePrompt, buildSettingByKey, matchSceneSetting } from '../../lib/scenePrompt.js';+import {+ buildScenePrompt, buildSettingByKey, matchSceneSetting,+ buildCharByKey, matchSceneCharacters, matchCharactersInText,+} from '../../lib/scenePrompt.js';import { composeStyledPrompt } from '../../lib/composeStyledPrompt.js';import { getDefaultVideoModelId, getVideoModels } from '../../lib/mediaModels.js';import { runStagedLLM } from '../../lib/stageRunner.js';@@ -101,10 +104,18 @@ export function composeVisualPrompt({ series, description, slugline = '', extraSreturn applyWorldStyle(scenePrompt, world);}-export function composeComicPagePrompt({ series, world, page, pageNumber, extraStyle = '' }) {+export function composeComicPagePrompt({ series, world, page, pageNumber, extraStyle = '', matchedCharacters = [] }) {const panels = Array.isArray(page?.panels) ? page.panels : [];if (panels.length === 0) return '';+ // Placed AFTER the layout clause: diffusion models weight earlier tokens+ // more heavily, and the page-shape instruction has to claim that position.+ const featuring = (matchedCharacters || [])+ .map((c) => ({ name: c.name, desc: (c.physicalDescription || c.description || '').trim() }))+ .filter((c) => c.name && c.desc)+ .map((c) => `${c.name}: ${c.desc}`)+ .join('; ');+// Append a sentence-terminator unless the source text already ends in one —// prose extracted from a script often carries its own `.`, `!`, or `?`, and// double-punctuating like "...sunstreaming in.." is noisy in prompts. The@@ -140,8 +151,9 @@ export function composeComicPagePrompt({ series, world, page, pageNumber, extraSconst seriesClause = series?.name ? ` from the series "${series.name}"` : '';const layout = `A single full printable comic book page${seriesClause}, page ${pageNumber}. Render a balanced multi-panel comic page layout with ${panels.length} clearly bordered panel${panels.length === 1 ? '' : 's'} arranged for left-to-right, top-to-bottom reading. Include lettered speech balloons for dialogue, rectangular narration captions, and stylized SFX where indicated. Each panel must be visually distinct, with consistent character designs across panels.${styleClause}`;+ const featuringClause = featuring ? `\n\nFeaturing — ${featuring}` : '';- return applyWorldStyle(`${layout}\n\n${panelLines.join('\n\n')}`, world);+ return applyWorldStyle(`${layout}${featuringClause}\n\n${panelLines.join('\n\n')}`, world);}/**@@ -174,11 +186,19 @@ export async function enqueueVisualComicPage(issueId, options = {}) {}const mode = resolveMode(options, settings);+ // Dialogue carries structured CAPS names, so match via charByKey rather than+ // scanning panel description prose (cheaper and more reliable).+ const charByKey = buildCharByKey(series.characters || []);+ const dialogueNames = page.panels.flatMap((p) =>+ (p.dialogue || []).map((d) => d.character).filter(Boolean),+ );+ const matchedCharacters = matchSceneCharacters(dialogueNames, charByKey);// composeComicPagePrompt only returns '' when panels.length === 0, which is// already rejected above. The "(continuation of previous beat)" placeholder// covers panels with no description, so the prompt is non-empty by here.const prompt = composeComicPagePrompt({series, world, page, pageNumber: pageIndex + 1, extraStyle: options.extraStyle,+ matchedCharacters,});const jobId = enqueueImageJob({@@ -204,11 +224,13 @@ export async function enqueueVisualImage(issueId, stageId, options = {}) {}const { settings, series, world } = await loadBibleContext(issueId);const mode = resolveMode(options, settings);+ const matchedCharacters = matchCharactersInText(options.description || '', series.characters || []);const prompt = composeVisualPrompt({series,description: options.description,slugline: options.slugline,extraStyle: options.extraStyle,+ matchedCharacters,world,});if (!prompt) {@@ -266,11 +288,16 @@ export async function enqueueStoryboardSceneVideo(issueId, sceneIndex, options =});}+ const matchedCharacters = matchCharactersInText(+ `${scene.description || ''} ${scene.slugline || ''}`,+ series.characters || [],+ );const prompt = composeVisualPrompt({series,description: scene.description,slugline: scene.slugline || '',extraStyle: options.extraStyle,+ matchedCharacters,world,});