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([issue-2180]): multi-concept series ideation with anti-generic banlist (user/judge pick)
Adam Eivy32d209c79474
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 25ba60d59f..ab3c1a29ec 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -47,6 +47,8 @@## Creative Writing Quality Engine+- **[issue-2180] Series invention now generates several distinct concepts under an anti-generic banlist, then user-picks (interactive) or judge-picks (autonomous) the winner — concept diversity at the seed is the cheapest quality lever in the pipeline.** Autonomous series invention used to produce ONE concept with no anti-generic pressure; autonovel's seed stage generates many concepts under an explicit banlist ("no chosen-one prophecies, no dark lords, no medieval-Europe-with-elves, no magic academies, no love triangles"), then selects. The `pipeline-series-generate` stage now invents **N genuinely distinct candidate concepts** (default 5, clamped 2–8), each carrying craft facets — HOOK / WORLD / CONFLICT ENGINE + COST / TENSION (personal AND larger-scale) / THEME (genre-neutral, not every series has magic) — under an **anti-generic banlist** that merges a shipped default list with the universe's own `influences.avoid` (case-insensitive dedupe, so an author's "steer clear of X" gets a hard veto at the seed). **Interactive mode** (the "Generate with AI" button on the New Series form) now presents the candidates for **user pick** — a deep-linkable card selection (`?concept=` is the URL source of truth) that pre-fills the form; the rejected candidates stay in memory (and in run history) so the user can switch without regenerating. **Autonomous mode** (CoS-driven invention) **judge-picks** the winner via a new one-call forced-rank stage `pipeline-series-concept-judge` ("which concept would a reader who has seen a thousand pitches stop scrolling for?" — ties forbidden), reusing the writer/judge split (#2167) resolved from the generation stage's `judgeProvider`/`judgeModel`; it **falls back to the first candidate** when no judge is configured or the call fails, so invention never blocks. Seed-faithful expansion is untouched — when the user typed their own idea it's still expanded, never replaced with a "better" concept. Runs ONLY from an explicit user action or the already-consented autonomous path — never at boot (AI-provider policy). Candidate normalization, banlist merge, forced-rank parsing, and judge-pick fallback are unit-tested; the modified prompt ships a hash-keyed migration (customized prompts preserved + warned) and the new judge stage a seed migration. (`server/services/pipeline/seriesGenerate.js`, `data.reference/prompts/stages/pipeline-series-generate.md`, `data.reference/prompts/stages/pipeline-series-concept-judge.md`, `server/routes/pipeline/series.js`, `server/services/creative/tools/pipeline.js`, `scripts/migrations/179-series-multi-concept-ideation.js`, `scripts/migrations/180-series-concept-judge-stage.js`, `client/src/pages/Pipeline.jsx`, `client/src/services/apiPipeline.js`)+- **[issue-2169] Two comparative-quality mechanisms build on the calibrated judge — a multi-candidate draft gate, and head-to-head Elo ranking of a series' issues.** Both compose the Phase 3 judge (#2167) to escape autonovel's "rubric trap" (absolute 1-10 scores collapse into a 2-point band; comparison forces the discrimination the judge can't avoid). **(1) Multi-candidate draft gate** — a new opt-in per-stage config (`draftAttempts` 1–3, default **1 = off**; optional `draftGateThreshold`, schema parity added to `stageConfigUpdateSchema`) makes `generateStage` generate → judge → re-roll a FRESH draft while the composite `qualityScore` is below the threshold, up to the attempt cap, and keep the best-scoring attempt. Every attempt persists (rejected drafts stay recoverable in run history) and a per-attempt scorecard lands on `stage.draftGate` (`{ winner, threshold, attempts:[{ runId, qualityScore, rejected }] }`) — never silently discarded. Only the judgeable stages (prose/comicScript/teleplay) gate; the single-shot path is byte-for-byte unchanged when off. When run from Series Autopilot each re-roll bills one cos action and stops re-rolling when the daily budget is spent (keeping the best so far); a manual regenerate is never cos-billed. Canon extraction runs once, on the winning draft. **(2) Head-to-head Elo ranking** — a new `comparativeRank.js` + forced-pick `pipeline-judge-compare.md` stage prompt ("you are not allowed to call it a tie" — quote the deciding passage) runs a Swiss-style tournament (~4 rounds, K=32 Elo) across the series' drafted issues, each side truncated to a comparable budget via `contextBudget.js`. The ranking + per-match records persist at `data/pipeline-comparative-rank/{seriesId}.json`, content-hash-pinned for staleness (reuses `computeSourceContentHash`), with the weakest-N slice as the revision-priority order Phase 7 consumes. A tie/hedge/garbage pick from the judge falls through to a deterministic, balanced tiebreak. Surfaced as a new **Rankings** tab on the Reader Map page (`?tab=rank`) — an Elo table with the weakest issues flagged as revision priorities. Runs ONLY from the explicit "Rank issues" action or an autopilot step — never at boot (AI-provider policy). Pure Elo math + Swiss pairing + tie-refusal parsing + staleness are unit-tested. (`server/services/pipeline/editorial/comparativeRank.js`, `server/services/pipeline/textStages.js`, `server/services/pipeline/issues.js`, `server/services/pipeline/seriesAutopilot.js`, `server/lib/pipelineValidation.js`, `server/routes/pipeline/editorial.js`, `data.reference/prompts/stages/pipeline-judge-compare.md`, `client/src/components/pipeline/ComparativeRankView.jsx`, `client/src/pages/PipelineSeriesRoadmap.jsx`, `client/src/services/apiPipeline.js`)- **[issue-2167] A calibrated LLM quality judge now scores each drafted issue, with a writer/judge model split — `qualityScore = judge overall − deterministic slop penalty`.** PortOS had severity findings and a deterministic health score but no LLM quality *score* per issue — the keep/revert currency Phases 5 and 7 need. A new harsh, calibrated judge (`server/services/pipeline/pipelineJudge.js`, stage prompt `pipeline-judge-issue.md`) scores a drafted issue across **9 dimensions** (voice adherence, beat coverage, character voice, plants seeded, prose quality, continuity, canon compliance, lore integration, engagement) against the SAME contract the writer received — style guide, beat sheet, and **full canon** (no reveal-gating, so it can catch canon/continuity/premature-reveal issues the writer's horizon-filtered view hides). An anti-inflation **calibration ladder** ("the median competent AI-generated chapter is a 6; a 10 does not exist for a draft; err lower") plus a **QUOTE TEST** (3 strongest / 3 weakest exact sentences) and a scene-vs-summary ratio keep the judge honest. The composite `qualityScore = judgeOverall − computeSlopPenalty(text)` (the deterministic slop penalty from #2165, clamped ≥ 0) is the dual immune system — the mechanical layer catches what the LLM judge normalizes away. **Writer/judge split:** a new `resolveJudgeForStage()` (sibling of `resolveProviderForStage()` in `server/lib/stageRunner.js`) resolves a per-writer-stage `judgeProvider`/`judgeModel` pin (schema parity: added to `stageConfigUpdateSchema`), defaulting to the writer's own provider but with the UI encouraging a *different*, harsher judge model to avoid self-congratulation. Scores persist per issue+stage at `data/pipeline-judge/{issueId}.json` with a `sourceContentHash` so a later edit flips the score to `stale` (mirrors `editorialAnalysis.js`), and the judge run itself lands in run history via `runStagedLLM` (a malformed-JSON response is retried once). Surfaced as a score chip + dimension/quote/revision breakdown on the issue page (`IssueJudgePanel`) and a weakest-first quality column on the series Editorial Roadmap. Runs ONLY from an explicit user action or the already-consented autopilot — never at boot. (`server/services/pipeline/pipelineJudge.js`, `server/lib/stageRunner.js`, `server/routes/pipeline/editorial.js`, `data.reference/prompts/stages/pipeline-judge-issue.md`, `client/src/components/pipeline/IssueJudgePanel.jsx`, `client/src/pages/PipelineSeriesRoadmap.jsx`)diff --git a/client/src/pages/Pipeline.jsx b/client/src/pages/Pipeline.jsxindex 28e172ff2b..06ea6629f4 100644--- a/client/src/pages/Pipeline.jsx+++ b/client/src/pages/Pipeline.jsx@@ -7,9 +7,9 @@* drills into its detail page where issues are created and managed.*/-import { useEffect, useMemo, useState } from 'react';+import { useEffect, useMemo, useRef, useState } from 'react';import { useConfirmDelete } from '../hooks/useConfirmDelete';-import { Link, useNavigate } from 'react-router-dom';+import { Link, useNavigate, useSearchParams } from 'react-router-dom';import { Plus, Workflow as WorkflowIcon, Trash2, Loader2, Globe2, FileInput, Sparkles, BookOpen } from 'lucide-react';import toast from '../components/ui/Toast';import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';@@ -24,7 +24,7 @@ import {createPipelineSeries,deletePipelineSeries,generateSeriesTitleLogo,- generateSeriesConcept,+ generateSeriesConcepts,listUniverses,WORLD_LOGLINE_MAX,WORLD_PREMISE_MAX,@@ -58,6 +58,21 @@ export default function Pipeline() {const [generating, setGenerating] = useState(false);const [showForm, setShowForm] = useState(false);const [form, setForm] = useState(emptyForm);+ // Multi-concept ideation (#2180): the generated candidate concepts (kept in+ // memory so the user can switch without regenerating — they also persist in+ // run history server-side). The picked candidate index is the URL source of+ // truth (`?concept=`) so the selection is deep-linkable per convention.+ const [candidates, setCandidates] = useState([]);+ const [searchParams, setSearchParams] = useSearchParams();+ const pickedConcept = (() => {+ const raw = parseInt(searchParams.get('concept'), 10);+ return Number.isInteger(raw) && raw >= 0 && raw < candidates.length ? raw : null;+ })();+ // Live mirror of the selected universe so an in-flight concept-generate can+ // detect a mid-request universe switch (see handleGenerate). Synced from the+ // committed form value — covers every path that changes it (pick, reset, create).+ const universeIdRef = useRef(form.universeId);+ useEffect(() => { universeIdRef.current = form.universeId; }, [form.universeId]);useEffect(() => {Promise.all([@@ -79,7 +94,21 @@ export default function Pipeline() {// form fields that are currently empty so a user who's already typed a// logline doesn't lose it when they pick a world afterwards.const BIBLE_FIELDS = ['logline', 'premise', 'styleNotes'];++ // Drop any generated candidate concepts + the `?concept=` selection. Called+ // when the universe changes (stale candidates were seeded from the old world)+ // and after a series is created.+ const clearCandidates = () => {+ setCandidates([]);+ setSearchParams((prev) => {+ const next = new URLSearchParams(prev);+ next.delete('concept');+ return next;+ }, { replace: true });+ };+const handleWorldChange = (universeId) => {+ clearCandidates();if (!universeId) {setForm((f) => ({ ...f, universeId: '' }));return;@@ -98,12 +127,11 @@ export default function Pipeline() {});};- // Generate a fresh series concept from the selected universe and overwrite- // the form's story fields (name / logline / premise / shape) so the user can- // edit before creating. The user clicked "Generate" explicitly, so this- // replaces whatever's there — but an empty field from the LLM keeps the prior- // value as a fallback. styleNotes is left to the universe-pull (it's a- // world-level aesthetic, not a per-series story choice).+ // Invent several distinct candidate concepts (#2180) from the selected+ // universe under the anti-generic banlist, and present them for the user to+ // pick from. The user clicked "Generate" explicitly (satisfies the AI-provider+ // policy). Nothing is applied until they pick a candidate — the rejected ones+ // stay available so they can switch without regenerating.const handleGenerate = async () => {if (!form.universeId) {toast.error('Pick a universe first — the generator uses it as seed material');@@ -111,41 +139,58 @@ export default function Pipeline() {}const requestedUniverseId = form.universeId;setGenerating(true);- const concept = await generateSeriesConcept(requestedUniverseId, {}, { silent: true }).catch((err) => {- toast.error(err.message || 'Failed to generate a series concept');+ const result = await generateSeriesConcepts(requestedUniverseId, {}, { silent: true }).catch((err) => {+ toast.error(err.message || 'Failed to generate series concepts');return null;});setGenerating(false);- if (!concept) return;+ if (!result) return;// The request can outlive the selection: if the user switched universes- // while it was in flight, applying a concept seeded from the old universe- // would pair the new universeId with a mismatched story. Gate the merge on- // the LIVE state inside the functional updater (race-free — `f` is the- // committed value, unlike a passively-synced ref), and gate the toast on- // whether the merge actually applied.- let applied = false;- setForm((f) => {- if (f.universeId !== requestedUniverseId) return f;- applied = true;- return {- ...f,- name: concept.name || f.name,- logline: concept.logline || f.logline,- premise: concept.premise || f.premise,- // The generated concept owns the story shape — apply it verbatim,- // including null (LLM picked none), so a stale earlier pick can't- // misrepresent the freshly generated concept.- shape: concept.shape,- };- });- if (!applied) return;+ // while it was in flight (which cleared candidates), the arriving batch was+ // seeded from the OLD universe — drop it rather than showing mismatched+ // concepts. `universeIdRef` tracks the live selection race-free.+ if (universeIdRef.current !== requestedUniverseId) return;+ const list = Array.isArray(result.candidates) ? result.candidates : [];+ if (!list.length) {+ toast.error('The generator returned no usable concepts — try again');+ return;+ }+ setCandidates(list);+ // Clear any prior selection — the new batch is unpicked until the user chooses.+ setSearchParams((prev) => {+ const next = new URLSearchParams(prev);+ next.delete('concept');+ return next;+ }, { replace: true });toast.success(- concept.rationale- ? `Generated "${concept.name}" — ${concept.rationale}`- : `Generated "${concept.name}"`,+ result.rationale+ ? `${list.length} concepts — ${result.rationale}`+ : `${list.length} concepts ready — pick one to continue`,);};+ // Apply a picked candidate to the form's story fields (name / logline /+ // premise / shape) and record the selection in the URL (`?concept=`) so it's+ // deep-linkable. An empty field from the LLM keeps the prior value; the shape+ // is applied verbatim (including null) since the concept owns it. styleNotes+ // is left to the universe-pull (world-level aesthetic, not a story choice).+ const applyCandidate = (index) => {+ const concept = candidates[index];+ if (!concept) return;+ setForm((f) => ({+ ...f,+ name: concept.name || f.name,+ logline: concept.logline || f.logline,+ premise: concept.premise || f.premise,+ shape: concept.shape ?? null,+ }));+ setSearchParams((prev) => {+ const next = new URLSearchParams(prev);+ next.set('concept', String(index));+ return next;+ }, { replace: true });+ };+const handleCreate = async (e) => {e?.preventDefault();const name = form.name.trim();@@ -178,6 +223,7 @@ export default function Pipeline() {// Reactive insert — no full refetch (CLAUDE.md convention).setSeries((prev) => [created, ...prev]);setForm(emptyForm());+ clearCandidates();setShowForm(false);toast.success(`Created "${created.name}"`);// Fire-and-forget logo design when a universe is linked — the LLM brief@@ -317,9 +363,48 @@ export default function Pipeline() {{generating ? 'Generating…' : 'Generate with AI'}</button><span className="text-[11px] text-gray-500">- Invents a different story set in the chosen universe — name, logline, premise & story shape. Edit anything before creating.+ Invents several distinct stories set in the chosen universe under an anti-generic banlist — pick one to pre-fill the form. Edit anything before creating.</span></div>+ {candidates.length > 0 && (+ <div className="space-y-2">+ <p className="text-[11px] uppercase tracking-wider text-gray-500">+ {candidates.length} concepts — pick one to continue (you can switch without regenerating)+ </p>+ <div className="grid grid-cols-1 md:grid-cols-2 gap-2">+ {candidates.map((c, i) => {+ const selected = pickedConcept === i;+ return (+ <button+ type="button"+ key={`${c.name}-${i}`}+ onClick={() => applyCandidate(i)}+ aria-pressed={selected}+ className={`text-left p-3 rounded-lg border transition-colors ${+ selected+ ? 'border-port-accent bg-port-accent/10'+ : 'border-port-border bg-port-bg hover:border-port-accent/50'+ }`}+ >+ <div className="flex items-center justify-between gap-2 mb-1">+ <span className="text-sm font-semibold text-white truncate">{c.name || 'Untitled'}</span>+ {selected && <span className="text-[10px] text-port-accent font-medium flex-shrink-0">✓ picked</span>}+ </div>+ {c.logline && <p className="text-xs text-gray-300 mb-1 line-clamp-2">{c.logline}</p>}+ {c.hook && <p className="text-[11px] text-gray-400 italic line-clamp-2">Hook: {c.hook}</p>}+ {(c.conflictEngine || c.theme) && (+ <p className="text-[11px] text-gray-500 mt-1 line-clamp-2">+ {c.conflictEngine ? `Engine: ${c.conflictEngine}` : ''}+ {c.conflictEngine && c.theme ? ' · ' : ''}+ {c.theme ? `Theme: ${c.theme}` : ''}+ </p>+ )}+ </button>+ );+ })}+ </div>+ </div>+ )}<div className="grid grid-cols-1 sm:grid-cols-[1fr_240px] gap-3"><div><label htmlFor="series-logline" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex f7f352853c..d3aa319b95 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -102,10 +102,13 @@ export const generateSeriesTitleLogo = (id, opts = {}, requestOptions = {}) =>...requestOptions,});-// Generate a fresh series concept (name / logline / premise / story shape) from-// a universe, used as seed material. Returns the concept WITHOUT persisting —-// the New Series form pre-fills it for the user to edit before creating.-export const generateSeriesConcept = (universeId, opts = {}, requestOptions = {}) =>+// Multi-concept series ideation (#2180): invent SEVERAL distinct candidate+// concepts (name / logline / premise / shape + craft facets) from a universe+// under an anti-generic banlist. Returns `{ candidates: [...], banlist,+// rationale }` WITHOUT persisting — the New Series form presents the candidates+// for user pick; the chosen one pre-fills the form. `opts` may carry+// `{ count, providerId, model }`.+export const generateSeriesConcepts = (universeId, opts = {}, requestOptions = {}) =>request('/pipeline/series/generate-concept', {method: 'POST',body: JSON.stringify({ universeId, ...opts }),diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex 451c47661d..83da34d717 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -493,12 +493,19 @@"variables": []},"pipeline-series-generate": {- "name": "Pipeline — Generate Series Concept",- "description": "Invent a new series within a universe — returns a {name, logline, premise, shape} JSON concept that tells a different story from existing series in the same universe, using the universe premise / style / influences / canon as seed material. Drives the 'Generate with AI' button on the New Series form; the concept pre-fills the form for the user to edit before creating.",+ "name": "Pipeline — Generate Series Concepts",+ "description": "Multi-concept series ideation (#2180, CWQE Phase 15): invents SEVERAL genuinely distinct new series within a universe — each with a name / logline / premise / story shape PLUS craft facets (hook, world, conflict engine, cost, tension, theme) — under an anti-generic banlist that merges a shipped default list with the universe's own avoid-influences. Returns a {candidates:[...]} JSON payload. Interactive mode presents the candidates for user pick on the New Series form; autonomous invention judge-picks the winner via the forced-rank pipeline-series-concept-judge stage. Configure a judgeProvider/judgeModel here to drive the writer/judge split for the pick.","model": "default","returnsJson": true,"variables": []},+ "pipeline-series-concept-judge": {+ "name": "Pipeline — Series Concept Judge (forced pick)",+ "description": "Forced-pick ranker for autonomous multi-concept series ideation (#2180, CWQE Phase 15). Reads the candidate concepts and MUST pick the single one 'a reader who has seen a thousand pitches would stop scrolling for' — ties forbidden — rewarding freshness over the generic default, a generative conflict engine, real cost, and both scales of tension. Resolves via the pipeline-series-generate stage's judgeProvider/judgeModel (writer/judge split). Falls back to the first candidate when no judge is configured or the call fails.",+ "model": "heavy",+ "returnsJson": true,+ "variables": []+ },"pipeline-series-voice-discover": {"name": "Pipeline — Discover Series Voice","description": "Voice discovery (#2179, CWQE Phase 14): writes the SAME short scene beat in several distinct registers (spare / lyric / wry / close-psychic / cinematic) so the author picks the series voice by ear. Returns a {candidates:[{register, passage, note}]} JSON payload; the picked passage lands in the style guide's voiceExemplars, rejected ones can drop into voiceAntiExemplars. Explicit user-triggered action — does NOT persist and does NOT fire on boot.",diff --git a/data.reference/prompts/stages/pipeline-series-concept-judge.md b/data.reference/prompts/stages/pipeline-series-concept-judge.mdnew file mode 100644index 0000000000..2f3e9740aa--- /dev/null+++ b/data.reference/prompts/stages/pipeline-series-concept-judge.md@@ -0,0 +1,38 @@+# Pipeline — Series Concept Judge (forced pick)++You are a ruthless acquisitions editor who has read a thousand series pitches and is bored by almost all of them. You are handed **{{count}} candidate series concepts** invented for the same universe. Your one job: decide **which single concept a reader who has seen a thousand pitches would stop scrolling for** — the one with the freshest hook, the most generative conflict engine, the clearest cost, and the least whiff of the default, done-to-death version.++You are **not allowed to call it a tie.** Pick exactly one winner and rank the rest.++## The universe these concepts share++- **Name:** {{universe.name}}+- **Premise:** {{universe.premise}}+- **Embrace influences:** {{universe.embrace}}+- **Avoid influences:** {{universe.avoid}}++## Candidates (numbered 1..{{count}})++{{candidates}}++## How to judge++- **Freshness first.** Reward the concept that avoids the generic default and finds the specific, surprising version. Penalize anything that reads like a pitch you've seen many times.+- **Conflict engine.** Prefer the concept whose conflict keeps generating stories (an ongoing pressure), not one that burns out after a single event.+- **Cost.** A concept that charges its protagonist a real, painful price beats one where the goal is free.+- **Both scales of tension.** Reward a concept that lands a personal stake AND a larger one, pulling against each other.+- **Producibility.** It has to sustain a serialized arc, not a one-shot.++Ignore polish of wording — judge the *idea*, not the prose of the pitch.++## Output++Return ONLY valid JSON in this exact shape (`pick` and every entry of `ranking` are 1-based concept numbers):++```json+{+ "pick": <the winning concept number, 1..{{count}}>,+ "ranking": [<concept numbers best-to-worst>],+ "rationale": "<one or two sentences naming the deciding difference between the winner and the runner-up>"+}+```diff --git a/data.reference/prompts/stages/pipeline-series-generate.md b/data.reference/prompts/stages/pipeline-series-generate.mdindex 0f350dcdc8..76a4d7f957 100644--- a/data.reference/prompts/stages/pipeline-series-generate.md+++ b/data.reference/prompts/stages/pipeline-series-generate.md@@ -1,6 +1,8 @@-# Pipeline — Generate Series Concept+# Pipeline — Generate Series Concepts-You are a showrunner / series developer. Invent **one new series** that lives inside the universe described below — a self-contained story with its own protagonist, conflict, and arc. The universe is the shared world (its tone, rules, places, and cast); the series is *one story told within it*, not a retelling of the world itself.+You are a showrunner / series developer. Invent **{{count}} genuinely distinct new series**, each of which lives inside the universe described below — a self-contained story with its own protagonist, conflict, and arc. The universe is the shared world (its tone, rules, places, and cast); each series is *one story told within it*, not a retelling of the world itself.++The point of proposing several is **diversity of premise**: the concepts must not be minor variations of one idea. Push each into a different corner of the world, a different kind of protagonist, a different engine of conflict. Concept variety at the seed is the cheapest quality lever in the whole pipeline — everything downstream inherits it.## Universe (seed material)@@ -21,25 +23,40 @@ You are a showrunner / series developer. Invent **one new series** that lives in{{existingSeries}}-Your new series MUST tell a **different story** from the ones above — a different protagonist, a different central conflict, or a different corner of the world. Do not duplicate an existing premise or logline. It is fine to share canon (the same city, a recurring character), but the spine of the story must be new.+Each new series MUST tell a **different story** from the ones above AND from each other — a different protagonist, a different central conflict, or a different corner of the world. Do not duplicate an existing premise or logline. It is fine to share canon (the same city, a recurring character), but the spine of each story must be new and the {{count}} concepts must be distinct from one another.++## Anti-generic banlist (do NOT reach for these)++The following are exhausted, default-mode ideas a reader who has seen a thousand pitches will scroll right past. Do not build a concept on any of them; if the universe's own avoid-influences appear here they are doubly forbidden:++{{banlist}}++Steering clear of a banned trope does not mean avoiding the genre — it means finding the fresh, specific version instead of the tired default.-## Story shapes (choose the one that best fits the arc you're proposing)+## Story shapes (choose the one that best fits each arc you propose){{shapes}}-## What to write+## What to write — for EACH of the {{count}} concepts1. **name** — a distinctive series title (not the universe's name). Short, evocative, 1–5 words.2. **logline** — one sentence: protagonist + their goal + the obstacle/stakes. Concrete, not abstract.3. **premise** — 1–3 short paragraphs: the setting within the universe, the central conflict, the stakes, the tone. This is the elevator pitch a reader sees on the series page.4. **shape** — the single best-fitting story-shape id from the list above (e.g. `man-in-hole`). Pick the one whose emotional curve matches the arc your premise implies.+5. **hook** — one sentence that makes someone pick this up over everything else on the shelf.+6. **world** — what is genuinely new or specific here, beyond the shared universe (the angle no other pitch would take).+7. **conflictEngine** — the situation that keeps generating stories issue after issue (not a single event — an ongoing pressure).+8. **cost** — what that conflict *charges* the protagonist: the price, the trade-off, what pursuing the goal takes away.+9. **tension** — the stakes at BOTH scales: a personal, intimate stake AND a larger (societal / cosmic / systemic) one, and how they pull against each other.+10. **theme** — the question the series is really about, under the plot.## Rules-- Stay inside the universe's tone and rules — honor the embrace influences, steer clear of the avoid influences.-- Make it producible as a serialized comic / TV series (an ongoing arc, not a one-shot).-- Don't restate the universe premise back as the series premise — the series is one story, narrower and more specific than the world.+- Stay inside the universe's tone and rules — honor the embrace influences, steer clear of the avoid influences and the banlist above.+- Make each producible as a serialized comic / TV series (an ongoing arc, not a one-shot).+- Don't restate the universe premise back as a series premise — each series is one story, narrower and more specific than the world.- `shape` must be exactly one of the ids listed above. If genuinely unsure, pick the closest fit rather than omitting it.+- Return exactly {{count}} concepts, each meaningfully different from the others.## Output@@ -47,10 +64,20 @@ Return ONLY valid JSON in this exact shape:```json{- "name": "<series title, 1–5 words>",- "logline": "<one-sentence logline>",- "premise": "<1–3 paragraph premise>",- "shape": "<one story-shape id from the list>",- "rationale": "<one short sentence on why this story + shape fits the universe — for the user, not stored>"+ "candidates": [+ {+ "name": "<series title, 1–5 words>",+ "logline": "<one-sentence logline>",+ "premise": "<1–3 paragraph premise>",+ "shape": "<one story-shape id from the list>",+ "hook": "<one sentence that makes someone pick this up>",+ "world": "<what's genuinely new/specific here>",+ "conflictEngine": "<the ongoing situation that generates stories>",+ "cost": "<what the conflict charges the protagonist>",+ "tension": "<personal stake AND larger-scale stake, in tension>",+ "theme": "<the question under the plot>"+ }+ ],+ "rationale": "<one short sentence for the user on which concept you'd lean toward and why — not stored>"}```diff --git a/scripts/migrations/179-series-multi-concept-ideation.js b/scripts/migrations/179-series-multi-concept-ideation.jsnew file mode 100644index 0000000000..f6ba2c8dc5--- /dev/null+++ b/scripts/migrations/179-series-multi-concept-ideation.js@@ -0,0 +1,55 @@+/**+ * CWQE Phase 15 — multi-concept series ideation (#2180).+ *+ * `pipeline-series-generate.md` changed from inventing ONE series concept to+ * inventing SEVERAL genuinely distinct candidate concepts (each with craft+ * facets: hook / world / conflict engine / cost / tension / theme) under an+ * anti-generic banlist, returning a `{candidates:[...]}` JSON payload. The New+ * Series form presents the candidates for user pick; autonomous invention+ * judge-picks the winner via the new `pipeline-series-concept-judge` stage+ * (seeded by the sibling migration 180).+ *+ * `scripts/setup-data.js` only copies *missing* prompt files, so existing+ * installs keep their old single-concept `pipeline-series-generate.md` until+ * this migration rewrites it — and the service's `content.candidates` gate would+ * throw "no usable series concepts" against the old template's single-object+ * output. This hash-driven replace upgrades only installs whose copy still+ * hashes to the prior shipped version; customized prompts are left intact and+ * warned about.+ *+ * Strategy: hash-driven prompt-replace via `./_lib.js`. Idempotent.+ */++import { makePromptReplaceMigration } from './_lib.js';++// Pre-change shipped hash (the single-concept body seeded by migration 088).+export const ACCEPTED_OLD_MD5 = {+ 'pipeline-series-generate.md': ['bc72731124a2bd6304362f4402c6305d'],+};++// Post-change shipped hash (multi-concept + banlist + facets).+export const NEW_SHIPPED_MD5 = {+ 'pipeline-series-generate.md': '21352c21ed6d4edb7a4b7c32704eff55',+};++const { applyMigration, up } = makePromptReplaceMigration({+ accepted: ACCEPTED_OLD_MD5,+ current: NEW_SHIPPED_MD5,+ label: 'multi-concept series ideation',+ customizedHint: (filename) =>+ ` To upgrade it manually, diff:\n` ++ ` data.reference/prompts/stages/${filename}\n` ++ ` against your current:\n` ++ ` data/prompts/stages/${filename}\n` ++ ` and switch it to emit a {"candidates":[...]} array of concepts under the\n` ++ ` anti-generic banlist ({{count}} / {{banlist}} variables).`,+ skipFooter: (count) =>+ `⚠️ ${count} series-concept prompt(s) could not be auto-updated because they\n` ++ ` were customized. "Generate with AI" on the New Series form will keep\n` ++ ` returning a single concept and the multi-candidate picker will be empty\n` ++ ` until you merge the new shape from\n` ++ ` data.reference/prompts/stages/pipeline-series-generate.md.`,+});++export { applyMigration };+export default { up };diff --git a/scripts/migrations/180-series-concept-judge-stage.js b/scripts/migrations/180-series-concept-judge-stage.jsnew file mode 100644index 0000000000..88ab423eb5--- /dev/null+++ b/scripts/migrations/180-series-concept-judge-stage.js@@ -0,0 +1,17 @@+/**+ * Seed the `pipeline-series-concept-judge` stage into existing installs+ * (CWQE Phase 15, #2180).+ *+ * The forced-pick ranker that autonomous multi-concept series ideation uses to+ * judge-pick the winning concept. Boot runs migrations (server/index.js) but NOT+ * `setup-data.js`, so an upgrade that pulls + `pm2 restart`s (rather than running+ * `update.sh`) would otherwise leave this new stage unseeded and+ * `judgePickConcept` would fail to resolve the stage — falling back to the first+ * candidate every time instead of actually judging. Copies the `.md` template+ * from `data.reference/prompts/stages/` and merges the stage-config entry when+ * absent (never clobbering a customized file/entry).+ */++import { makeSeedMigration } from './_seedStageHelpers.js';++export default makeSeedMigration('pipeline-series-concept-judge');diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.jsindex c5501e7820..25b7403766 100644--- a/scripts/setup-data-drift.test.js+++ b/scripts/setup-data-drift.test.js@@ -48,6 +48,7 @@ const EXPECTED_STAGE_OLD = {'pipeline-editorial-on-the-nose.md': ['48182b49149e6b5829fbed71b3ffc242'],'pipeline-tv-script.md': ['3f6fecc25573ed054b47db392250034a'],'cd-treatment.md': ['2ffa482e7bfb6fe8b7224505fedbf712', '16d0ef6a7fd2533719a846019122ebee', '95b7685690ecfee4f682b0293b790277'],+ 'pipeline-series-generate.md': ['bc72731124a2bd6304362f4402c6305d'],};const EXPECTED_STAGE_NEW = {'pipeline-idea-expansion.md': 'd6fa86a435f978336661dcabca67258f',@@ -74,6 +75,7 @@ const EXPECTED_STAGE_NEW = {'pipeline-editorial-on-the-nose.md': 'e5786fb019e5bf19c7aa6ed0c8b35cda','pipeline-tv-script.md': '376f779f4687b598f1c92ca4e770fd5a','cd-treatment.md': 'd940eadfb406ce584f0e244032f33382',+ 'pipeline-series-generate.md': '21352c21ed6d4edb7a4b7c32704eff55',};const EXPECTED_PARTIAL_OLD = {'bible-deference.md': ['218f0e85643609ed85a12b1ccc7b5a8d'],diff --git a/server/routes/pipeline/series.js b/server/routes/pipeline/series.jsindex 50ac749b1b..c3c0d75d7a 100644--- a/server/routes/pipeline/series.js+++ b/server/routes/pipeline/series.js@@ -16,7 +16,7 @@ import { findDuplicateSeriesGroups, findSameNameSeries } from '../../services/duimport { mergeSeries } from '../../services/recordMerge.js';import { mergeFieldsWithAI } from '../../services/recordMergeAI.js';import { generateSeriesTitleLogo } from '../../services/pipeline/seriesTitleLogo.js';-import { generateSeriesConcept } from '../../services/pipeline/seriesGenerate.js';+import { generateSeriesConcepts, CANDIDATE_COUNT_MIN, CANDIDATE_COUNT_MAX } from '../../services/pipeline/seriesGenerate.js';import { discoverSeriesVoice } from '../../services/pipeline/seriesVoiceDiscover.js';import {LENGTH_PROFILE_NAMES,@@ -417,18 +417,20 @@ router.post('/series/merge/ai-resolve', asyncHandler(async (req, res) => {res.json(result);}));-// Generate a fresh series concept (name / logline / premise / story shape)-// from a universe, used as seed material. Returns the concept WITHOUT-// persisting it — the New Series form pre-fills these for the user to edit-// before creating. Static path: keep BEFORE `/series/:id`.+// Multi-concept series ideation (#2180, CWQE Phase 15): invent SEVERAL distinct+// candidate concepts from a universe, under an anti-generic banlist, WITHOUT+// persisting — the New Series form presents them for the user to pick (deep-+// linkable selection). The rejected candidates live in run history so the user+// can switch without regenerating. Static path: keep BEFORE `/series/:id`.const seriesGenerateSchema = z.object({universeId: z.string().trim().min(1).max(seriesSvc.UNIVERSE_ID_MAX),+ count: z.number().int().min(CANDIDATE_COUNT_MIN).max(CANDIDATE_COUNT_MAX).optional(),providerId: z.string().trim().max(80).optional(),model: z.string().trim().max(200).optional(),});router.post('/series/generate-concept', asyncHandler(async (req, res) => {const body = validateRequest(seriesGenerateSchema, req.body ?? {});- const result = await generateSeriesConcept(body.universeId, body)+ const result = await generateSeriesConcepts(body.universeId, body).catch((err) => { throw mapServiceError(err); });res.json(result);}));diff --git a/server/services/creative/tools/pipeline.js b/server/services/creative/tools/pipeline.jsindex 9c745e8c67..dce8ef9d3b 100644--- a/server/services/creative/tools/pipeline.js+++ b/server/services/creative/tools/pipeline.js@@ -134,7 +134,7 @@ export const PIPELINE_TOOLS = [},{name: 'pipeline_generateSeriesConcept',- description: 'Generate a series concept (name, logline, premise, shape) for a universe via the LLM.',+ description: 'Invent several distinct series concepts (name, logline, premise, shape + craft facets) for a universe under an anti-generic banlist, then judge-pick the strongest via a forced rank. Returns the winning concept plus the rejected candidates.',costClass: COST_LLM,schema: z.object({ universeId: z.string().min(1), options: z.record(z.any()).optional() }),parameters: {diff --git a/server/services/pipeline/seriesGenerate.js b/server/services/pipeline/seriesGenerate.jsindex 940ebed4d0..7a8498e883 100644--- a/server/services/pipeline/seriesGenerate.js+++ b/server/services/pipeline/seriesGenerate.js@@ -1,28 +1,118 @@/**- * Pipeline — Series Concept Generator.+ * Pipeline — Series Concept Generator (multi-concept ideation, CWQE Phase 15, #2180).*- * Given a universe, asks the configured LLM to invent a NEW series that lives- * in that world but tells a different story from any series already in it — a- * fresh name, logline, premise, and a recommended Vonnegut story shape. The- * universe (premise, style, influences, canon) is the seed; the universe's- * existing series (names + loglines) are passed so the model deliberately- * diverges from them.+ * Given a universe, asks the configured LLM to invent SEVERAL genuinely distinct+ * new series that live in that world — each a different story from any series+ * already in it and from each other. Every concept carries a fresh name /+ * logline / premise / recommended Vonnegut shape PLUS craft facets (hook, world,+ * conflict engine, cost, tension, theme), generated under an anti-generic+ * banlist that merges a shipped default list with the universe's own+ * `influences.avoid`. Concept diversity at the seed is the cheapest quality lever+ * in the whole pipeline — everything downstream inherits it (autonovel's seed+ * stage generated 10 concepts under an explicit banlist, then selected).*- * Unlike `generateSeriesTitleLogo` this does NOT persist anything — it returns- * a concept that the New Series form pre-fills so the user can edit before- * committing. Throws ServerError(502, PIPELINE_SERIES_CONCEPT_EMPTY) on- * unusable output — matches the other refine helpers' error shape so the UI- * surfaces a uniform "try again" toast.+ * Two selection modes, per the AI-provider policy (this fires ONLY from an+ * explicit user action or the already-consented autonomous invention path —+ * never at boot):+ * - `generateSeriesConcepts()` — interactive: returns ALL candidates for the+ * user to pick from (the New Series form presents them). Nothing is+ * persisted here; the rejected candidates live in run history so the user+ * can switch without regenerating.+ * - `generateSeriesConcept()` — autonomous (CoS-driven invention / Series+ * Autopilot): judge-picks the winner via a one-call forced-rank (reusing the+ * writer/judge split, #2167) and returns the single winning concept in the+ * legacy `{ name, logline, premise, shape }` shape (backward-compatible),+ * plus the rejected candidates. Falls back to the first candidate when no+ * judge is configured / the judge call fails.+ *+ * Sampling note: the issue asks concept generation to run "hot" (high+ * temperature) where the provider path supports it. The shared stage runner /+ * toolkit provider path does NOT currently plumb sampling params (mirrors the+ * sibling CWQE phases — pipelineJudge / voice-discover — which punted on it too),+ * so diversity is driven by the prompt's explicit banlist + "make each concept+ * distinct" mandate rather than a temperature knob. CLI providers would ignore+ * a temperature anyway. When the provider path grows sampling support this is+ * the natural first caller to opt in.+ *+ * Throws ServerError(502, PIPELINE_SERIES_CONCEPT_EMPTY) on unusable output —+ * matches the other refine helpers' error shape so the UI surfaces a uniform+ * "try again" toast.*/import { getUniverse, joinInfluenceList, ERR_NOT_FOUND as UNIVERSE_ERR_NOT_FOUND } from '../universeBuilder.js';import { listSeries, NAME_MAX, LOGLINE_MAX, PREMISE_MAX } from './series.js';import { ARC_SHAPES, ARC_SHAPE_IDS } from '../../lib/storyArc.js';import { runPromptRefineRaw } from './refineHelpers.js';+import { runStagedLLM, resolveJudgeForStage } from '../../lib/stageRunner.js';+import { getStage } from '../promptService.js';import { ServerError } from '../../lib/errorHandler.js';const CANON_LIST_MAX = 24; // cap per canon kind in the brief — keeps the prompt tightconst EXISTING_SERIES_MAX = 30;+const FACET_MAX = 1000; // per-facet char cap (hook / world / conflictEngine / cost / tension / theme)++// How many candidate concepts to generate. Default 5 (mid of the issue's 4–6);+// clamped so a stray option can't spawn a wall of concepts or a single one.+export const CANDIDATE_COUNT_DEFAULT = 5;+export const CANDIDATE_COUNT_MIN = 2;+export const CANDIDATE_COUNT_MAX = 8;++// Shipped, genre-neutral anti-generic banlist — the exhausted default-mode ideas+// a reader who has seen a thousand pitches scrolls past. Merged with the+// universe's own `influences.avoid` before rendering into the prompt. Kept+// genre-spanning (not every series has magic) so it steers ideation across the+// whole catalog, per the issue's "adapt facet names to be genre-neutral" note.+export const ANTI_GENERIC_BANLIST = Object.freeze([+ 'a chosen one / prophesied savior destined to save the world',+ 'a Dark Lord or ultimate evil whose defeat is the whole plot',+ 'medieval-Europe-with-a-reskin as the default setting',+ 'a secret magic/training academy the protagonist enrolls in',+ 'a love triangle as the primary engine of tension',+ 'an amnesiac protagonist who slowly recovers who they were',+ '"it was all a simulation / dream / afterlife" as the central twist',+ 'a scrappy band of misfits who are the only hope',+ 'an ancient prophecy that foretells the events of the story',+ 'a mentor who dies to motivate the hero',+]);++const str = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');++const rangeIndices = (n) => Array.from({ length: n }, (_, i) => i);++// Clamp a caller-supplied concept count into [MIN, MAX], defaulting when absent+// or non-numeric.+export function clampCandidateCount(v) {+ if (v == null) return CANDIDATE_COUNT_DEFAULT;+ const n = Math.trunc(Number(v));+ if (!Number.isFinite(n)) return CANDIDATE_COUNT_DEFAULT;+ return Math.min(CANDIDATE_COUNT_MAX, Math.max(CANDIDATE_COUNT_MIN, n));+}++/**+ * Merge the shipped anti-generic banlist with the universe's own avoid-influences+ * into one deduped list (case-insensitive; shipped entries win their slot). This+ * is what gives the universe author's "steer clear of X" a hard veto at the seed.+ * Exported for the route/UI + unit tests.+ */+export function mergeAntiGenericBanlist(universe) {+ const merged = [...ANTI_GENERIC_BANLIST];+ const seen = new Set(ANTI_GENERIC_BANLIST.map((s) => s.toLowerCase()));+ const avoid = Array.isArray(universe?.influences?.avoid) ? universe.influences.avoid : [];+ for (const raw of avoid) {+ const t = typeof raw === 'string' ? raw.trim() : '';+ if (!t) continue;+ const key = t.toLowerCase();+ if (seen.has(key)) continue;+ seen.add(key);+ merged.push(t);+ }+ return merged;+}++// Render the merged banlist as a bullet block for the prompt.+const renderBanlist = (list) => (Array.isArray(list) && list.length+ ? list.map((b) => `- ${b}`).join('\n')+ : '- (no banlist configured)');// Render a universe canon list (characters / places / objects) as a compact// "Name — role; Name — role" string the LLM can scan. Entries with no@@ -78,11 +168,34 @@ function buildContext(universe, existingSeries) {};}-export async function generateSeriesConcept(universeId, options = {}) {- // getUniverse throws the universe service's generic NOT_FOUND code, which the- // pipeline route's mapServiceError doesn't translate — leaving a stale/deleted- // universeId to surface as a 500. Translate it here to a proper 404 so bad- // user input reads as bad input, not a server fault.+// Normalize one LLM candidate concept. Drops a candidate with no usable name (the+// create form needs a title); clamps every string to its cap; keeps only a+// recognized story-shape id (unknown → null, the create path treats that as "no+// shape picked"). The facet fields are advisory craft context — surfaced in the+// picker UI and fed to the judge, not persisted on the series record.+function normalizeCandidate(raw) {+ if (raw == null || typeof raw !== 'object') return null;+ const name = str(raw.name, NAME_MAX);+ if (!name) return null;+ const shapeRaw = typeof raw.shape === 'string' ? raw.shape.trim() : '';+ return {+ name,+ logline: str(raw.logline, LOGLINE_MAX),+ premise: str(raw.premise, PREMISE_MAX),+ shape: ARC_SHAPE_IDS.includes(shapeRaw) ? shapeRaw : null,+ hook: str(raw.hook, FACET_MAX),+ world: str(raw.world, FACET_MAX),+ conflictEngine: str(raw.conflictEngine, FACET_MAX),+ cost: str(raw.cost, FACET_MAX),+ tension: str(raw.tension, FACET_MAX),+ theme: str(raw.theme, FACET_MAX),+ };+}++// Load the shared seed context both entry points need — the universe (404-mapped)+// and the same-universe existing series (storage failure propagates so a+// silently-empty list can't weaken duplicate-avoidance while reporting success).+async function loadSeedContext(universeId) {const universe = await getUniverse(universeId).catch((err) => {if (err?.code === UNIVERSE_ERR_NOT_FOUND) {throw new ServerError(`Universe not found: ${universeId} — pick an existing universe.`, {@@ -91,41 +204,201 @@ export async function generateSeriesConcept(universeId, options = {}) {}throw err;});- // Let a storage failure propagate (→ 500) rather than swallowing it: a- // silently-empty list would feed the model a "no existing series" brief for a- // universe that actually has some, weakening duplicate-avoidance while still- // reporting success.const all = await listSeries();const existingSeries = all.filter((s) => s.universeId === universeId);+ return { universe, existingSeries };+}++// The one LLM call that invents the candidate concepts. Shared by both entry+// points. Returns the normalized candidate list plus the merged banlist and run+// metadata.+async function runConceptGeneration(universe, existingSeries, options = {}) {+ const count = clampCandidateCount(options.count);+ const banlist = mergeAntiGenericBanlist(universe);const emptyError = {code: 'PIPELINE_SERIES_CONCEPT_EMPTY',- message: 'LLM returned an empty series concept — try again or pick a different provider.',+ message: 'LLM returned no usable series concepts — try again or pick a different provider.',};const { content, rationale, runId, providerId, model } = await runPromptRefineRaw({templateName: 'pipeline-series-generate',- variables: buildContext(universe, existingSeries),+ variables: { ...buildContext(universe, existingSeries), count, banlist: renderBanlist(banlist) },options,source: 'pipeline-series-generate',- logTag: `Series concept — universe=${universeId.slice(0, 8)}`,+ logTag: `Series concepts — universe=${(universe.id || '').slice(0, 8)} count=${count}`,emptyError,- // A concept with no name is unusable — the create form needs a title. The- // other fields are clamped/defaulted below, so name is the only hard gate.+ // A response with no candidates array is unusable — hard gate before the+ // per-candidate normalization below.validateContent: (c) => {- const name = typeof c?.name === 'string' ? c.name.trim() : '';- if (!name) {- throw new ServerError('LLM returned a series concept with no name — try again.', {- status: 502, code: emptyError.code,- });+ if (!Array.isArray(c?.candidates)) {+ throw new ServerError(emptyError.message, { status: 502, code: emptyError.code });}},});- const name = content.name.trim().slice(0, NAME_MAX);- const logline = typeof content.logline === 'string' ? content.logline.trim().slice(0, LOGLINE_MAX) : '';- const premise = typeof content.premise === 'string' ? content.premise.trim().slice(0, PREMISE_MAX) : '';- // Trim before the allow-list check so a valid id with incidental whitespace- // (e.g. "man-in-hole\n") isn't discarded; drop an unrecognized shape rather- // than poison the form — the create path treats `null` as "no shape picked."- const shapeRaw = typeof content.shape === 'string' ? content.shape.trim() : '';- const shape = ARC_SHAPE_IDS.includes(shapeRaw) ? shapeRaw : null;- return { name, logline, premise, shape, rationale, runId, providerId, model };+ const candidates = content.candidates.map(normalizeCandidate).filter(Boolean);+ if (!candidates.length) {+ throw new ServerError(emptyError.message, { status: 502, code: emptyError.code });+ }+ return { candidates, banlist, rationale, runId, providerId, model };+}++/**+ * Interactive multi-concept generation. Returns ALL candidates for user pick —+ * nothing is persisted (the New Series form pre-fills from the chosen candidate;+ * the rest live in run history so the user can switch without regenerating).+ *+ * @param {string} universeId+ * @param {object} [options] — { count, providerId, model }+ * @returns {Promise<{ candidates, banlist, rationale, runId, providerId, model }>}+ */+export async function generateSeriesConcepts(universeId, options = {}) {+ const { universe, existingSeries } = await loadSeedContext(universeId);+ return runConceptGeneration(universe, existingSeries, options);+}++// Render the candidate concepts (numbered 1..N) for the forced-rank judge prompt.+function renderCandidatesForJudge(candidates) {+ return candidates.map((c, i) => {+ const lines = [`### Concept ${i + 1}: ${c.name}`];+ if (c.logline) lines.push(`- Logline: ${c.logline}`);+ if (c.hook) lines.push(`- Hook: ${c.hook}`);+ if (c.world) lines.push(`- World: ${c.world}`);+ if (c.conflictEngine) lines.push(`- Conflict engine: ${c.conflictEngine}`);+ if (c.cost) lines.push(`- Cost: ${c.cost}`);+ if (c.tension) lines.push(`- Tension: ${c.tension}`);+ if (c.theme) lines.push(`- Theme: ${c.theme}`);+ if (c.premise) lines.push(`- Premise: ${c.premise.slice(0, 800)}`);+ return lines.join('\n');+ }).join('\n\n');+}++// Parse the forced-rank judge response into a 0-based pick + ranking. Returns+// null when the pick is missing/out-of-range so the caller falls back to the+// first candidate (the "no usable judge decision" path). `n` is the candidate+// count — a pick must be a 1-based number in [1, n].+export function parseConceptPick(content, n) {+ if (!content || typeof content !== 'object') return null;+ const pickNum = Math.trunc(Number(content.pick));+ if (!Number.isFinite(pickNum) || pickNum < 1 || pickNum > n) return null;+ const index = pickNum - 1;+ const rankingRaw = Array.isArray(content.ranking) ? content.ranking : [];+ const seen = new Set();+ const ranking = [];+ for (const r of rankingRaw) {+ const num = Math.trunc(Number(r));+ if (!Number.isFinite(num) || num < 1 || num > n) continue;+ const idx = num - 1;+ if (seen.has(idx)) continue;+ seen.add(idx);+ ranking.push(idx);+ }+ // Ensure the winner leads the ranking, and every candidate appears once.+ const ordered = [index, ...ranking.filter((i) => i !== index)];+ for (const i of rangeIndices(n)) if (!ordered.includes(i)) ordered.push(i);+ const rationale = str(content.rationale, 600);+ return { index, ranking: ordered, rationale };+}++/**+ * Judge-pick the strongest concept via a one-call forced rank ("which concept+ * would a reader who has seen a thousand pitches stop scrolling for?"), reusing+ * the writer/judge split (#2167) resolved from the concept-generation stage's+ * judge pin. Degrades gracefully: with ≤1 candidate, no resolvable judge, or an+ * unusable judge response, it falls back to the FIRST candidate rather than+ * blocking autonomous invention.+ *+ * @param {Array} candidates+ * @param {object} [opts] — { universe, providerId, model }+ * @returns {Promise<{ index, ranking, rationale, judged }>}+ */+export async function judgePickConcept(candidates, opts = {}) {+ const list = Array.isArray(candidates) ? candidates : [];+ const n = list.length;+ if (n <= 1) {+ return { index: 0, ranking: n === 1 ? [0] : [], rationale: '', judged: false };+ }+ const { universe, providerId, model } = opts;++ // Resolve the judge provider from the concept-generation stage's judge pin+ // (writer/judge split), honoring an explicit override. Resolution failure+ // ("no judge configured" / provider unavailable) degrades to the first+ // candidate — this is the specified fallback, not a swallowed error.+ const stage = getStage('pipeline-series-generate');+ const resolved = await resolveJudgeForStage(stage, {+ providerOverride: providerId,+ modelOverride: model,+ }).catch(() => null);+ if (!resolved) {+ return { index: 0, ranking: rangeIndices(n), rationale: '', judged: false };+ }++ const variables = {+ count: n,+ candidates: renderCandidatesForJudge(list),+ universe: {+ name: (universe?.name || '').slice(0, 200),+ premise: (universe?.premise || '').slice(0, 4000),+ embrace: joinInfluenceList(universe?.influences?.embrace) || '(none)',+ avoid: joinInfluenceList(universe?.influences?.avoid) || '(none)',+ },+ };+ const result = await runStagedLLM('pipeline-series-concept-judge', variables, {+ returnsJson: true,+ providerOverride: resolved.provider.id,+ modelOverride: resolved.model,+ source: 'pipeline-series-concept-judge',+ }).catch(() => null);++ const parsed = parseConceptPick(result?.content, n);+ if (!parsed) {+ return { index: 0, ranking: rangeIndices(n), rationale: '', judged: false };+ }+ console.log(`⚖️ concept judge: picked #${parsed.index + 1}/${n} via ${resolved.provider.id}/${resolved.model || '(default)'}`);+ return { ...parsed, judged: true };+}++/**+ * Autonomous single-concept generation (CoS-driven invention / Series Autopilot).+ * Generates the candidate concepts, judge-picks the winner (or first-candidate+ * fallback), and returns the winning concept in the legacy+ * `{ name, logline, premise, shape, rationale }` shape — backward-compatible with+ * every existing caller — plus `candidates` (all), `rejected` (the losers),+ * `pickIndex`, and `judged`.+ *+ * @param {string} universeId+ * @param {object} [options] — { count, providerId, model }+ */+export async function generateSeriesConcept(universeId, options = {}) {+ const { universe, existingSeries } = await loadSeedContext(universeId);+ const { candidates, banlist, rationale, runId, providerId, model } =+ await runConceptGeneration(universe, existingSeries, options);++ const pick = await judgePickConcept(candidates, {+ universe,+ providerId: options.providerId,+ model: options.model,+ });+ const index = candidates[pick.index] ? pick.index : 0;+ const chosen = candidates[index];+ const rejected = candidates.filter((_, i) => i !== index);++ return {+ // Legacy concept shape (unchanged for backward compatibility).+ name: chosen.name,+ logline: chosen.logline,+ premise: chosen.premise,+ shape: chosen.shape,+ // Judge's deciding rationale when it picked; otherwise the generator's.+ rationale: pick.rationale || rationale,+ // New multi-concept context.+ candidates,+ rejected,+ banlist,+ pickIndex: index,+ judged: pick.judged,+ runId,+ providerId,+ model,+ };}++export const __testing = { normalizeCandidate, renderCandidatesForJudge, renderBanlist, buildContext };diff --git a/server/services/pipeline/seriesGenerate.test.js b/server/services/pipeline/seriesGenerate.test.jsindex bfd98b9c31..c6f74141bc 100644--- a/server/services/pipeline/seriesGenerate.test.js+++ b/server/services/pipeline/seriesGenerate.test.js@@ -1,12 +1,13 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-// Mock the three dependencies generateSeriesConcept reaches out to: the universe-// store, the series list, and the LLM runner. We control `runPromptRefineRaw`'s-// returned `content` so we can assert the post-processing (clamps, shape-// validation, name gate) without a real DB or provider.+// Mock the dependencies the generator reaches out to: the universe store, the+// series list, the refine runner, and (for judge-pick) the stage runner ++// prompt service. We control the LLM content so we can assert post-processing+// (candidate normalization, banlist merge, judge pick + fallback) without a real+// DB or provider.vi.mock('../universeBuilder.js', () => ({getUniverse: vi.fn(),- joinInfluenceList: (a) => (Array.isArray(a) ? a.filter(Boolean).join(', ') : ''),+ joinInfluenceList: (a) => (Array.isArray(a) ? a.filter((t) => typeof t === 'string' && t.trim()).join(', ') : ''),ERR_NOT_FOUND: 'NOT_FOUND',}));vi.mock('./series.js', async (importOriginal) => {@@ -14,12 +15,28 @@ vi.mock('./series.js', async (importOriginal) => {return { ...actual, listSeries: vi.fn(async () => []) };});vi.mock('./refineHelpers.js', () => ({ runPromptRefineRaw: vi.fn() }));+vi.mock('../../lib/stageRunner.js', () => ({+ runStagedLLM: vi.fn(),+ resolveJudgeForStage: vi.fn(),+}));+vi.mock('../promptService.js', () => ({ getStage: vi.fn(() => ({ judgeProvider: null })) }));-import { generateSeriesConcept } from './seriesGenerate.js';+import {+ generateSeriesConcept,+ generateSeriesConcepts,+ judgePickConcept,+ parseConceptPick,+ mergeAntiGenericBanlist,+ clampCandidateCount,+ ANTI_GENERIC_BANLIST,+ CANDIDATE_COUNT_DEFAULT,+ CANDIDATE_COUNT_MAX,+ CANDIDATE_COUNT_MIN,+} from './seriesGenerate.js';import { getUniverse } from '../universeBuilder.js';-import { listSeries } from './series.js';+import { listSeries, NAME_MAX, LOGLINE_MAX, PREMISE_MAX } from './series.js';import { runPromptRefineRaw } from './refineHelpers.js';-import { NAME_MAX, LOGLINE_MAX, PREMISE_MAX } from './series.js';+import { runStagedLLM, resolveJudgeForStage } from '../../lib/stageRunner.js';const baseUniverse = {id: 'uni-1',@@ -33,9 +50,17 @@ const baseUniverse = {objects: [],};-function mockLLM(content, meta = {}) {+const candidate = (over = {}) => ({+ name: 'Salt Run', logline: 'A child survives.', premise: 'p', shape: 'man-in-hole',+ hook: 'a hook', world: 'new world', conflictEngine: 'ongoing pressure',+ cost: 'a price', tension: 'personal vs cosmic', theme: 'survival', ...over,+});++// runPromptRefineRaw returns the concept-generation content. `candidates` is the+// array the multi-concept prompt emits.+function mockGen(candidates, meta = {}) {runPromptRefineRaw.mockResolvedValue({- content,+ content: { candidates },rationale: meta.rationale || 'fits the world',runId: 'run-1',providerId: 'p1',@@ -47,111 +72,200 @@ beforeEach(() => {vi.clearAllMocks();getUniverse.mockResolvedValue(baseUniverse);listSeries.mockResolvedValue([]);+ // Default judge: resolves to a provider and forced-picks concept #1.+ resolveJudgeForStage.mockResolvedValue({ provider: { id: 'jp' }, model: 'jm' });+ runStagedLLM.mockResolvedValue({ content: { pick: 1, ranking: [1], rationale: 'winner' } });});-describe('generateSeriesConcept', () => {- it('returns a clean concept with a valid shape', async () => {- mockLLM({ name: 'Salt Run', logline: 'A child survives.', premise: 'p', shape: 'man-in-hole' });- const out = await generateSeriesConcept('uni-1');- expect(out).toMatchObject({- name: 'Salt Run',- logline: 'A child survives.',- premise: 'p',- shape: 'man-in-hole',- rationale: 'fits the world',- providerId: 'p1',- model: 'm1',- });+describe('clampCandidateCount', () => {+ it('defaults when absent or non-numeric', () => {+ expect(clampCandidateCount(undefined)).toBe(CANDIDATE_COUNT_DEFAULT);+ expect(clampCandidateCount(null)).toBe(CANDIDATE_COUNT_DEFAULT);+ expect(clampCandidateCount('nope')).toBe(CANDIDATE_COUNT_DEFAULT);+ });+ it('clamps into [MIN, MAX]', () => {+ expect(clampCandidateCount(1)).toBe(CANDIDATE_COUNT_MIN);+ expect(clampCandidateCount(999)).toBe(CANDIDATE_COUNT_MAX);+ expect(clampCandidateCount(4)).toBe(4);});+});- it('trims a valid shape with incidental whitespace before validating', async () => {- mockLLM({ name: 'X', logline: 'l', premise: 'p', shape: ' man-in-hole\n' });- const out = await generateSeriesConcept('uni-1');- expect(out.shape).toBe('man-in-hole');+describe('mergeAntiGenericBanlist', () => {+ it('merges the shipped default list with the universe avoid-influences', () => {+ const merged = mergeAntiGenericBanlist({ influences: { avoid: ['camp', 'grimdark'] } });+ expect(merged).toEqual(expect.arrayContaining(ANTI_GENERIC_BANLIST));+ expect(merged).toContain('camp');+ expect(merged).toContain('grimdark');+ expect(merged.length).toBe(ANTI_GENERIC_BANLIST.length + 2);+ });+ it('dedupes case-insensitively and tolerates a missing avoid list', () => {+ const dupe = ANTI_GENERIC_BANLIST[0].toUpperCase();+ const merged = mergeAntiGenericBanlist({ influences: { avoid: [dupe, ' ', 42] } });+ // The duplicate (case-folded) + the blank + the non-string are all dropped.+ expect(merged.length).toBe(ANTI_GENERIC_BANLIST.length);+ expect(mergeAntiGenericBanlist(null)).toEqual([...ANTI_GENERIC_BANLIST]);+ expect(mergeAntiGenericBanlist({})).toEqual([...ANTI_GENERIC_BANLIST]);});+});- it('drops an unrecognized story shape to null', async () => {- mockLLM({ name: 'X', logline: 'l', premise: 'p', shape: 'not-a-real-shape' });- const out = await generateSeriesConcept('uni-1');- expect(out.shape).toBeNull();+describe('parseConceptPick', () => {+ it('maps a 1-based pick to a 0-based index and completes the ranking', () => {+ const out = parseConceptPick({ pick: 2, ranking: [2, 3], rationale: 'r' }, 3);+ expect(out.index).toBe(1);+ // winner leads; every candidate index appears once.+ expect(out.ranking).toEqual([1, 2, 0]);+ expect(out.rationale).toBe('r');+ });+ it('returns null for a missing / out-of-range pick (fallback signal)', () => {+ expect(parseConceptPick({ ranking: [1] }, 3)).toBeNull();+ expect(parseConceptPick({ pick: 0 }, 3)).toBeNull();+ expect(parseConceptPick({ pick: 4 }, 3)).toBeNull();+ expect(parseConceptPick(null, 3)).toBeNull();+ expect(parseConceptPick('nope', 3)).toBeNull();});+});- it('clamps overlong fields to their series caps', async () => {- mockLLM({- name: 'N'.repeat(NAME_MAX + 50),- logline: 'L'.repeat(LOGLINE_MAX + 50),- premise: 'P'.repeat(PREMISE_MAX + 50),- shape: 'tragedy',- });- const out = await generateSeriesConcept('uni-1');- expect(out.name).toHaveLength(NAME_MAX);- expect(out.logline).toHaveLength(LOGLINE_MAX);- expect(out.premise).toHaveLength(PREMISE_MAX);+describe('generateSeriesConcepts (interactive / user pick)', () => {+ it('returns all normalized candidates + the merged banlist', async () => {+ mockGen([candidate({ name: 'A' }), candidate({ name: 'B', shape: 'tragedy' })]);+ const out = await generateSeriesConcepts('uni-1');+ expect(out.candidates).toHaveLength(2);+ expect(out.candidates[0]).toMatchObject({ name: 'A', shape: 'man-in-hole', hook: 'a hook' });+ expect(out.candidates[1].shape).toBe('tragedy');+ expect(out.banlist).toEqual(expect.arrayContaining(ANTI_GENERIC_BANLIST));+ // The universe avoid-influence is merged into the banlist.+ expect(out.banlist).toContain('camp');+ expect(out.providerId).toBe('p1');});- it('coerces non-string logline/premise to empty strings', async () => {- mockLLM({ name: 'OK', logline: 42, premise: { a: 1 }, shape: null });- const out = await generateSeriesConcept('uni-1');- expect(out.logline).toBe('');- expect(out.premise).toBe('');- expect(out.shape).toBeNull();+ it('passes count + rendered banlist into the prompt variables', async () => {+ mockGen([candidate()]);+ await generateSeriesConcepts('uni-1', { count: 3 });+ const call = runPromptRefineRaw.mock.calls[0][0];+ expect(call.templateName).toBe('pipeline-series-generate');+ expect(call.variables.count).toBe(3);+ expect(call.variables.banlist).toContain('chosen one');+ expect(call.variables.banlist).toContain('camp');+ expect(call.variables.universe.name).toBe('Saltworks');+ expect(call.variables.characters).toContain('Ash — survivor');+ });++ it('drops candidates with no name and clamps overlong fields', async () => {+ mockGen([+ { logline: 'no name here' },+ candidate({+ name: 'N'.repeat(NAME_MAX + 50),+ logline: 'L'.repeat(LOGLINE_MAX + 50),+ premise: 'P'.repeat(PREMISE_MAX + 50),+ }),+ ]);+ const out = await generateSeriesConcepts('uni-1');+ expect(out.candidates).toHaveLength(1);+ expect(out.candidates[0].name).toHaveLength(NAME_MAX);+ expect(out.candidates[0].logline).toHaveLength(LOGLINE_MAX);+ expect(out.candidates[0].premise).toHaveLength(PREMISE_MAX);+ });++ it('drops an unrecognized story shape to null', async () => {+ mockGen([candidate({ shape: 'not-a-real-shape' })]);+ const out = await generateSeriesConcepts('uni-1');+ expect(out.candidates[0].shape).toBeNull();});- it('throws PIPELINE_SERIES_CONCEPT_EMPTY when the name is missing', async () => {- // The empty-name gate runs inside the validateContent hook we pass to- // runPromptRefineRaw — invoke it the way the real runner would.+ it('throws PIPELINE_SERIES_CONCEPT_EMPTY when no candidates array is present', async () => {runPromptRefineRaw.mockImplementation(async ({ validateContent }) => {- validateContent({ logline: 'l', premise: 'p' });- return { content: { logline: 'l', premise: 'p' }, rationale: '', runId: 'r', providerId: 'p', model: 'm' };+ validateContent({ notCandidates: true });+ return { content: {}, rationale: '', runId: 'r', providerId: 'p', model: 'm' };});- await expect(generateSeriesConcept('uni-1')).rejects.toMatchObject({+ await expect(generateSeriesConcepts('uni-1')).rejects.toMatchObject({code: 'PIPELINE_SERIES_CONCEPT_EMPTY',});});- it('renders slugline-only places (no name) into the canon context', async () => {- getUniverse.mockResolvedValue({- ...baseUniverse,- places: [{ slugline: 'INT. FOUNDRY — NIGHT' }, { name: 'The Docks', role: 'port' }],+ it('throws PIPELINE_SERIES_CONCEPT_EMPTY when every candidate is unusable', async () => {+ mockGen([{ logline: 'no name' }, { name: '' }]);+ await expect(generateSeriesConcepts('uni-1')).rejects.toMatchObject({+ code: 'PIPELINE_SERIES_CONCEPT_EMPTY',});- mockLLM({ name: 'X', logline: 'l', premise: 'p', shape: 'tragedy' });- await generateSeriesConcept('uni-1');- const call = runPromptRefineRaw.mock.calls[0][0];- expect(call.variables.places).toContain('INT. FOUNDRY — NIGHT');- expect(call.variables.places).toContain('The Docks — port');});- it('maps a missing universe to a 404 (not a 500)', async () => {- getUniverse.mockRejectedValue(Object.assign(new Error('Universe not found: uni-x'), { code: 'NOT_FOUND' }));- await expect(generateSeriesConcept('uni-x')).rejects.toMatchObject({- status: 404,- code: 'PIPELINE_SERIES_CONCEPT_UNIVERSE_NOT_FOUND',+ it('maps a missing universe to a 404 (not a 500) without calling the LLM', async () => {+ getUniverse.mockRejectedValue(Object.assign(new Error('nope'), { code: 'NOT_FOUND' }));+ await expect(generateSeriesConcepts('uni-x')).rejects.toMatchObject({+ status: 404, code: 'PIPELINE_SERIES_CONCEPT_UNIVERSE_NOT_FOUND',});- // The LLM must never be invoked when the seed universe is missing.expect(runPromptRefineRaw).not.toHaveBeenCalled();});it('propagates a listSeries storage failure instead of swallowing it', async () => {listSeries.mockRejectedValue(new Error('db unavailable'));- await expect(generateSeriesConcept('uni-1')).rejects.toThrow('db unavailable');- // No generation off an incomplete duplicate-avoidance brief.+ await expect(generateSeriesConcepts('uni-1')).rejects.toThrow('db unavailable');expect(runPromptRefineRaw).not.toHaveBeenCalled();});+});- it('passes the universe and existing-series context into the prompt', async () => {- listSeries.mockResolvedValue([- { id: 'ser-a', universeId: 'uni-1', name: 'First Tale', logline: 'an old story' },- { id: 'ser-b', universeId: 'uni-other', name: 'Elsewhere', logline: 'different world' },- ]);- mockLLM({ name: 'Fresh', logline: 'l', premise: 'p', shape: 'icarus' });- await generateSeriesConcept('uni-1');- const call = runPromptRefineRaw.mock.calls[0][0];- expect(call.templateName).toBe('pipeline-series-generate');- expect(call.variables.universe.name).toBe('Saltworks');- expect(call.variables.characters).toContain('Ash — survivor');- expect(call.variables.places).toContain('The Foundry');- // Only the same-universe series is listed; the other-universe one is excluded.- expect(call.variables.existingSeries).toContain('First Tale');- expect(call.variables.existingSeries).not.toContain('Elsewhere');+describe('judgePickConcept (autonomous / forced rank)', () => {+ it('skips the judge for a single candidate', async () => {+ const out = await judgePickConcept([candidate()], { universe: baseUniverse });+ expect(out).toMatchObject({ index: 0, judged: false });+ expect(resolveJudgeForStage).not.toHaveBeenCalled();+ expect(runStagedLLM).not.toHaveBeenCalled();+ });++ it('picks the judge-selected concept', async () => {+ runStagedLLM.mockResolvedValue({ content: { pick: 2, ranking: [2, 1], rationale: 'B wins' } });+ const out = await judgePickConcept([candidate({ name: 'A' }), candidate({ name: 'B' })], { universe: baseUniverse });+ expect(out).toMatchObject({ index: 1, judged: true, rationale: 'B wins' });+ });++ it('falls back to the first candidate when no judge resolves', async () => {+ resolveJudgeForStage.mockRejectedValue(new Error('no judge provider'));+ const out = await judgePickConcept([candidate({ name: 'A' }), candidate({ name: 'B' })], { universe: baseUniverse });+ expect(out).toMatchObject({ index: 0, judged: false });+ expect(runStagedLLM).not.toHaveBeenCalled();+ });++ it('falls back to the first candidate when the judge call fails', async () => {+ runStagedLLM.mockRejectedValue(new Error('provider down'));+ const out = await judgePickConcept([candidate({ name: 'A' }), candidate({ name: 'B' })], { universe: baseUniverse });+ expect(out).toMatchObject({ index: 0, judged: false });+ });++ it('falls back to the first candidate when the judge pick is unparseable', async () => {+ runStagedLLM.mockResolvedValue({ content: { pick: 'tie' } });+ const out = await judgePickConcept([candidate({ name: 'A' }), candidate({ name: 'B' })], { universe: baseUniverse });+ expect(out).toMatchObject({ index: 0, judged: false });+ });+});++describe('generateSeriesConcept (backward-compatible single concept)', () => {+ it('returns the judge-picked concept in the legacy shape + rejected candidates', async () => {+ mockGen([candidate({ name: 'A' }), candidate({ name: 'B' })]);+ runStagedLLM.mockResolvedValue({ content: { pick: 2, ranking: [2, 1], rationale: 'B wins' } });+ const out = await generateSeriesConcept('uni-1');+ // Legacy fields point at the judge-picked winner (concept #2 = 'B').+ expect(out).toMatchObject({ name: 'B', logline: 'A child survives.', shape: 'man-in-hole' });+ expect(out.rationale).toBe('B wins');+ expect(out.pickIndex).toBe(1);+ expect(out.judged).toBe(true);+ expect(out.rejected).toHaveLength(1);+ expect(out.rejected[0].name).toBe('A');+ expect(out.candidates).toHaveLength(2);+ });++ it('returns the only candidate (judge skipped) for a single-concept response', async () => {+ mockGen([candidate({ name: 'Solo' })]);+ const out = await generateSeriesConcept('uni-1');+ expect(out).toMatchObject({ name: 'Solo', shape: 'man-in-hole', judged: false, pickIndex: 0 });+ expect(out.rejected).toHaveLength(0);+ expect(runStagedLLM).not.toHaveBeenCalled();+ });++ it('falls back to the first candidate when the judge fails, keeping the generator rationale', async () => {+ mockGen([candidate({ name: 'First' }), candidate({ name: 'Second' })], { rationale: 'gen rationale' });+ runStagedLLM.mockRejectedValue(new Error('provider down'));+ const out = await generateSeriesConcept('uni-1');+ expect(out).toMatchObject({ name: 'First', pickIndex: 0, judged: false });+ expect(out.rationale).toBe('gen rationale');});});