Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(pipeline): LLM-driven arc + season + verify planner

Adam Eivy4f536d0f792b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 5d36880ccb..eeca533303 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,7 @@
## Added
+- **Pipeline — LLM-driven series-arc planning.** Three new staged-LLM passes that plan and verify a multi-season series: (1) `POST /api/pipeline/series/:id/arc/generate` proposes the top-level arc — series-level logline, summary, themes, protagonist arc — plus a 2–5 season breakdown with per-season loglines, ending hooks, and episode-count targets, default `model: 'heavy'`. (2) `POST /api/pipeline/series/:id/seasons/:seasonId/episodes/generate` proposes the episode-by-episode breakdown for one season, taking the whole-arc protagonist trajectory and prior seasons' synopses as continuity context. (3) `POST /api/pipeline/series/:id/arc/verify` runs a cross-season continuity pass that surfaces character contradictions, dropped subplots, episode-count/arc-weight mismatch, unresolved finale hooks, arc-role imbalance, and theme drift as actionable `{ severity, location, problem, suggestion }` issues. All three calls accept `{ providerOverride, modelOverride }` and routes 1 + 2 also accept `commit: true` to persist the proposal in one shot (default returns a preview the UI can confirm before writing). Backed by `server/services/pipeline/arcPlanner.js` (~280 LOC) on top of the shared `stageRunner.js` + new stage prompts in `data.sample/prompts/stages/pipeline-arc-{overview,verify}.md` + `pipeline-season-episodes.md`, all three reusing the `_partials/bible-deference.md` block for character/setting consistency. Phase 3 of the Story Arc Planning initiative — no UI yet (Phase 4 builds the arc canvas on top of these endpoints).
- **Pipeline — series-arc + season schema.** Series records gain two new optional fields: `series.arc` (logline, summary, themes, protagonistArc, status) for the overall multi-season story spine, and `series.seasons[]` for the ordered season/volume list. Issues gain optional `seasonId` + `arcPosition` pointers so an issue can be slotted into a specific season at a specific ordinal. Backed by a new `server/lib/storyArc.js` (canonical shapes + sanitizers, sibling to `storyBible.js`) and a new `server/services/pipeline/seasons.js` service that handles delete-with-reassign so removing a season cleanly re-points or un-groups child issues. Routes: `GET / POST /series/:id/seasons`, `PATCH / DELETE /series/:id/seasons/:seasonId`. Pure additive — existing series files round-trip unchanged. Phase 2 of the Story Arc Planning initiative; no UI yet (Phase 4 builds the arc canvas on top of this).
## Changed
diff --git a/data.sample/prompts/stage-config.json b/data.sample/prompts/stage-config.json
index c263825f96..d7be903525 100644
--- a/data.sample/prompts/stage-config.json
+++ b/data.sample/prompts/stage-config.json
@@ -220,6 +220,27 @@
"model": "default",
"returnsJson": true,
"variables": []
+ },
+ "pipeline-arc-overview": {
+ "name": "Pipeline — Series Arc Overview",
+ "description": "Plan the top-level multi-season story spine for a series from its bible: a series-level logline, summary, themes, protagonist arc, and a 2–5 season breakdown with per-season loglines, ending hooks, and episode-count targets. Runs at `heavy` tier — most expensive single call in the pipeline.",
+ "model": "heavy",
+ "returnsJson": true,
+ "variables": []
+ },
+ "pipeline-season-episodes": {
+ "name": "Pipeline — Season Episode Breakdown",
+ "description": "Plan the episode-by-episode breakdown for one season of a multi-season series. Slots N episodes between the season's pickup state and ending hook, respecting prior seasons' continuity, the protagonist's whole-series arc, and a balanced mix of pilot / complication / midpoint / b-plot / all-is-lost / finale arc roles.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
+ },
+ "pipeline-arc-verify": {
+ "name": "Pipeline — Arc Verification",
+ "description": "Cross-season continuity pass over an authored arc: catches character contradictions, dropped subplots, episode-count vs arc-weight mismatch, unresolved finale hooks, arc-role imbalance, and theme drift. Returns actionable { severity, location, problem, suggestion } issues — empty list means clean.",
+ "model": "heavy",
+ "returnsJson": true,
+ "variables": []
}
}
}
diff --git a/data.sample/prompts/stages/pipeline-arc-overview.md b/data.sample/prompts/stages/pipeline-arc-overview.md
new file mode 100644
index 0000000000..8817915c61
--- /dev/null
+++ b/data.sample/prompts/stages/pipeline-arc-overview.md
@@ -0,0 +1,61 @@
+# Pipeline — Series Arc Overview
+
+You are a senior story editor sketching the **top-level multi-season story spine** for a new series. The user has a series bible (name, logline, premise, characters, target format, target issue count) but no decided arc shape — you propose one. The output gets persisted as `series.arc` + `series.seasons[]` and feeds every downstream per-season + per-episode prompt.
+
+This is the most expensive single call in the pipeline (you reason over the full series scope) so be deliberate.
+
+## Series bible
+
+- **Name:** {{series.name}}
+- **Target format:** {{series.targetFormat}} (`comic`, `tv`, or `comic+tv` — when both, the arc must work as a single TV season but also slice cleanly into comic issues)
+- **Logline:** {{series.logline}}
+- **Premise:**
+
+```
+{{series.premise}}
+```
+
+- **Style notes (tone / aesthetic):**
+
+```
+{{series.styleNotes}}
+```
+
+- **Target total episode count (rough budget across all seasons):** {{series.issueCountTarget}}
+
+{{> bible-deference }}
+
+## How to shape the arc
+
+1. **Logline (one sentence).** Pitch the whole multi-season arc — not the pilot. Should answer "what is this *show* about" if you only get 20 seconds in an elevator.
+2. **Summary (~500 words).** Act structure across the whole series. Hit the rough turning points: where does the protagonist start, where do they pivot at the end of each season, where do they land at the series finale. Be specific enough that someone writing season 2 can tell whether their idea fits.
+3. **Themes (2–5 short tags).** The recurring concerns — `betrayal`, `legacy`, `the cost of memory`, `class & inheritance`. Keep each tag short (≤80 chars).
+4. **Protagonist arc.** Character growth across all seasons. Where does the protagonist start morally / emotionally, and where do they end. This is the spine for later character-consistency checks.
+5. **Season outlines.** Break the arc into 2–5 seasons. Default to **3 seasons** if `issueCountTarget` is large enough; collapse to 2 if the premise is tight. For each season write:
+ - **`number`** — 1-indexed, contiguous.
+ - **`title`** — short noun phrase (e.g. *The Choir Awakens*, *Diaspora*, *Salt at the Root*). Avoid generic ones like "Pilot" or "Season 1".
+ - **`logline`** — one sentence; what changes in this season.
+ - **`endingHook`** — the image or line that pulls the audience into season N+1. Skippable for the final season (leave empty).
+ - **`episodeCountTarget`** — integer. Divide `issueCountTarget` across the seasons roughly proportionally to season weight. Sum of all `episodeCountTarget`s should approximately equal `issueCountTarget`.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:
+
+```json
+{
+ "logline": "string (the whole-series pitch, one sentence)",
+ "summary": "string (~500 words, multi-paragraph plain text — escape newlines as \\n)",
+ "themes": ["string", "..."],
+ "protagonistArc": "string (character growth across all seasons)",
+ "seasonOutlines": [
+ {
+ "number": 1,
+ "title": "string",
+ "logline": "string",
+ "endingHook": "string",
+ "episodeCountTarget": 8
+ }
+ ]
+}
+```
diff --git a/data.sample/prompts/stages/pipeline-arc-verify.md b/data.sample/prompts/stages/pipeline-arc-verify.md
new file mode 100644
index 0000000000..e67c77ce10
--- /dev/null
+++ b/data.sample/prompts/stages/pipeline-arc-verify.md
@@ -0,0 +1,74 @@
+# Pipeline — Series Arc Verification
+
+You are a continuity editor doing a cross-season pass on a planned series. The user has authored an arc, seasons, and (at least some) per-episode breakdowns — your job is to surface **structural problems before the production pipeline burns LLM + GPU minutes on broken material**. This is NOT a creative critique — don't suggest "what if we made it darker"; only flag continuity and structural breaks.
+
+## Series bible
+
+- **Name:** {{series.name}}
+- **Target format:** {{series.targetFormat}}
+- **Logline:** {{series.logline}}
+- **Premise:**
+
+```
+{{series.premise}}
+```
+
+{{> bible-deference }}
+
+## Full arc
+
+- **Whole-series logline:** {{arc.logline}}
+- **Themes:** {{arc.themesCsv}}
+- **Protagonist arc:**
+
+```
+{{arc.protagonistArc}}
+```
+
+- **Arc summary:**
+
+```
+{{arc.summary}}
+```
+
+## Seasons + episodes
+
+```json
+{{seasonsTreeJson}}
+```
+
+## What to look for
+
+Walk the seasons in order. Score each season + each episode against the arc. Specifically check:
+
+1. **Character contradictions.** Did the protagonist (or a major character) end season N in a state that contradicts season N+1's opening? Did a character die in episode 4 but get dialogue in episode 7?
+2. **Dropped subplots.** A subplot introduced in an early season's `endingHook` or episode `synopsis` that never gets resolved in a later season's `summary` or episode list.
+3. **Episode-count vs. arc-weight mismatch.** A season with `episodeCountTarget: 12` whose synopsis is summarizable in 3 beats. A season with `episodeCountTarget: 4` carrying the weight of a 12-episode arc.
+4. **Unresolved hooks at the series finale.** The final season ends without paying off the whole-arc logline, protagonist arc, or any of the major themes.
+5. **Arc-role imbalance.** A season with 8 episodes and zero `pilot` / `finale` `arcRole` entries (or two `pilot`s / two `finale`s).
+6. **Theme drift.** A theme is named in `arc.themes` but doesn't appear in any season synopsis or episode logline.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary. Each `issues[]` entry must be **actionable** — name the season and (if applicable) the episode that's broken, name the rule it breaks, and propose a concrete fix the user can apply by editing the offending record:
+
+```json
+{
+ "issues": [
+ {
+ "severity": "high",
+ "location": "season:2 / episode:5",
+ "problem": "string (what's wrong, with the specific evidence)",
+ "suggestion": "string (the smallest edit that resolves it)"
+ }
+ ]
+}
+```
+
+`severity` must be one of `high` / `medium` / `low`:
+
+- **`high`** — would break a viewer's understanding of the story (dead character speaking, contradictory protagonist state).
+- **`medium`** — would make the story feel sloppy (dropped subplot, unbalanced season).
+- **`low`** — opportunity to tighten (under-used theme, missing arc-role variety).
+
+Return `{ "issues": [] }` if everything checks out. Do NOT pad with low-confidence "consider also..." entries.
diff --git a/data.sample/prompts/stages/pipeline-season-episodes.md b/data.sample/prompts/stages/pipeline-season-episodes.md
new file mode 100644
index 0000000000..b450256f85
--- /dev/null
+++ b/data.sample/prompts/stages/pipeline-season-episodes.md
@@ -0,0 +1,84 @@
+# Pipeline — Season Episode Breakdown
+
+You are a writers-room showrunner planning the **episode-by-episode breakdown for one season** of a multi-season series. The series arc is already decided; you slot {{season.episodeCountTarget}} episodes into this season such that they (a) honor the season's logline + ending hook, (b) move the protagonist's whole-series arc forward, and (c) don't contradict the prior seasons' synopses.
+
+## Series bible
+
+- **Name:** {{series.name}}
+- **Logline:** {{series.logline}}
+- **Premise:**
+
+```
+{{series.premise}}
+```
+
+- **Style notes:** {{series.styleNotes}}
+
+## Full-arc context
+
+- **Whole-series logline:** {{arc.logline}}
+- **Protagonist arc across all seasons:**
+
+```
+{{arc.protagonistArc}}
+```
+
+- **Themes:** {{arc.themesCsv}}
+
+{{> bible-deference }}
+
+## Prior seasons (continuity — do not contradict)
+
+```
+{{priorSeasonsContext}}
+```
+
+## This season — the one you are planning
+
+- **Number:** {{season.number}}
+- **Title:** {{season.title}}
+- **Logline:** {{season.logline}}
+- **Synopsis:**
+
+```
+{{season.synopsis}}
+```
+
+- **Ending hook (where this season has to land):** {{season.endingHook}}
+- **Episode count target:** {{season.episodeCountTarget}}
+
+## How to shape the season
+
+Plan an arc *within* the season that bends from "pickup state" (the natural starting point given prior seasons + the protagonist arc) to the **ending hook** in exactly `episodeCountTarget` beats. Common shapes:
+
+- **5-act season** — pilot, complication, midpoint pivot, all-is-lost, finale.
+- **8-episode arc** — pilot, complication, complication, midpoint, complication, complication, all-is-lost, finale.
+- **12+** — add B-plot episodes between the structural beats; don't waste the count on filler.
+
+For each episode write:
+
+- **`number`** — 1-indexed within this season (NOT cumulative across the whole series). Sequential.
+- **`title`** — short, evocative noun phrase. No generic "Pilot" / "Finale" unless it earns the irony.
+- **`logline`** — one sentence; the question / image this episode opens with → resolves to.
+- **`synopsis`** — 2–3 sentences. What *happens* in this episode at the arc level. Don't write scene blocking — keep it at the level a season planner needs.
+- **`primaryCharacters`** — array of CAPS character names from the bible who carry the episode. Usually 1–3; never empty for a main character series.
+- **`arcRole`** — single token describing the episode's structural job in this season. Pick one of: `pilot` / `complication` / `midpoint` / `b-plot` / `all-is-lost` / `finale`. Used downstream to verify the season has balanced shape.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:
+
+```json
+{
+ "episodes": [
+ {
+ "number": 1,
+ "title": "string",
+ "logline": "string",
+ "synopsis": "string",
+ "primaryCharacters": ["NAME", "..."],
+ "arcRole": "pilot"
+ }
+ ]
+}
+```
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index f2bbfcc6d9..899df4c90d 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -34,6 +34,7 @@ import {
import * as seriesSvc from '../services/pipeline/series.js';
import * as issuesSvc from '../services/pipeline/issues.js';
import * as seasonsSvc from '../services/pipeline/seasons.js';
+import * as arcPlanner from '../services/pipeline/arcPlanner.js';
import { generateStage } from '../services/pipeline/textStages.js';
import * as autoRunner from '../services/pipeline/autoRunner.js';
import { enqueueVisualImage } from '../services/pipeline/visualStages.js';
@@ -53,6 +54,7 @@ const SERVICE_ERROR_STATUS = {
[seasonsSvc.ERR_NOT_FOUND]: 404,
[seasonsSvc.ERR_VALIDATION]: 400,
[seasonsSvc.ERR_REASSIGN_TARGET]: 400,
+ [arcPlanner.ERR_VALIDATION]: 400,
[ERR_NO_STORYBOARDS]: 400,
};
@@ -261,6 +263,30 @@ const extractBibleSchema = z.object({
parallel: z.boolean().optional(),
}).refine((p) => p.issueId || p.corpus, { message: 'extract requires either `issueId` or `corpus`' });
+// Arc / season-episodes / verify — Phase 3 of Story Arc Planning. All three
+// LLM calls share a tiny schema: provider override + model override. The
+// service layer pulls everything else from the persisted series record.
+const arcGenerateSchema = z.object({
+ providerOverride: z.string().trim().max(80).optional(),
+ modelOverride: z.string().trim().max(200).optional(),
+ // commit:true persists the LLM output to the series record in one shot
+ // (arc + seasons). Default false returns a preview the UI can confirm
+ // before writing — matches the storyboards-extract two-click pattern.
+ commit: z.boolean().optional(),
+});
+
+const seasonEpisodesGenerateSchema = z.object({
+ providerOverride: z.string().trim().max(80).optional(),
+ modelOverride: z.string().trim().max(200).optional(),
+ // commit:true creates one issue per episode under this season.
+ commit: z.boolean().optional(),
+});
+
+const arcVerifySchema = z.object({
+ providerOverride: z.string().trim().max(80).optional(),
+ modelOverride: z.string().trim().max(200).optional(),
+});
+
const autoRunSchema = z.object({
providerId: z.string().trim().max(80).optional(),
model: z.string().trim().max(200).optional(),
@@ -386,6 +412,92 @@ router.delete('/series/:id/seasons/:seasonId', asyncHandler(async (req, res) =>
res.json(result);
}));
+// =====================
+// Arc planning routes — Phase 3 of Story Arc Planning. Three LLM-driven
+// passes that propose (and optionally commit) arc-level metadata + season
+// outlines + per-episode breakdowns.
+// =====================
+
+// Top-of-arc generation: proposes `series.arc` + `series.seasons[]` from the
+// series bible. With `commit: true` persists the result in one shot; default
+// returns a preview the UI can confirm before writing.
+router.post('/series/:id/arc/generate', asyncHandler(async (req, res) => {
+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const body = validateRequest(arcGenerateSchema, req.body ?? {});
+ const result = await arcPlanner.generateArcOverview(req.params.id, body)
+ .catch((err) => { throw mapServiceError(err); });
+ let series = null;
+ if (body.commit) {
+ series = await seriesSvc.updateSeries(req.params.id, {
+ arc: result.arc,
+ seasons: result.seasons,
+ }).catch((err) => { throw mapServiceError(err); });
+ }
+ res.json({
+ arc: result.arc,
+ seasons: result.seasons,
+ runId: result.runId,
+ providerId: result.providerId,
+ model: result.model,
+ committed: !!body.commit,
+ series,
+ });
+}));
+
+// Per-season episode generation. Proposes (and optionally commits) the
+// per-episode breakdown for one season. With `commit: true`, creates one
+// issue per episode with the season pointer + arcPosition pre-filled.
+router.post('/series/:id/seasons/:seasonId/episodes/generate', asyncHandler(async (req, res) => {
+ const body = validateRequest(seasonEpisodesGenerateSchema, req.body ?? {});
+ const result = await arcPlanner.generateSeasonEpisodes(req.params.id, req.params.seasonId, body)
+ .catch((err) => { throw mapServiceError(err); });
+
+ const createdIssues = [];
+ if (body.commit) {
+ // Create one issue per episode under this season. The issue sanitizer
+ // already accepts `seasonId` + `arcPosition`, so we forward them in the
+ // create payload. The episode's `synopsis` lands in `stages.idea.input`
+ // so the downstream auto-run-text chain has a seed to expand against.
+ for (const ep of result.episodes) {
+ const created = await issuesSvc.createIssue({
+ seriesId: req.params.id,
+ title: ep.title,
+ // Issue `number` is series-scoped (the existing canonical counter);
+ // `arcPosition` is the season-scoped ordinal the LLM gave us. We let
+ // `createIssue` pick the series number so existing issues' numbers
+ // don't collide.
+ seasonId: req.params.seasonId,
+ arcPosition: ep.number,
+ stages: {
+ idea: {
+ status: ep.synopsis ? 'edited' : 'empty',
+ input: [ep.logline, ep.synopsis].filter(Boolean).join('\n\n'),
+ },
+ },
+ });
+ createdIssues.push(created);
+ }
+ }
+
+ res.json({
+ season: result.season,
+ episodes: result.episodes,
+ runId: result.runId,
+ providerId: result.providerId,
+ model: result.model,
+ committed: !!body.commit,
+ createdIssues,
+ });
+}));
+
+router.post('/series/:id/arc/verify', asyncHandler(async (req, res) => {
+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const body = validateRequest(arcVerifySchema, req.body ?? {});
+ const result = await arcPlanner.verifyArc(req.params.id, body)
+ .catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
// =====================
// Issue routes
// =====================
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
index 8e26b8b9a9..e0b159a2e1 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -34,6 +34,20 @@ vi.mock('../services/pipeline/textStages.js', async () => {
};
});
+// Stub the arc-planner LLM calls so route tests don't hit a provider.
+let arcGenerateSpy;
+let seasonEpisodesSpy;
+let arcVerifySpy;
+vi.mock('../services/pipeline/arcPlanner.js', async () => {
+ const actual = await vi.importActual('../services/pipeline/arcPlanner.js');
+ return {
+ ...actual,
+ generateArcOverview: vi.fn((...args) => arcGenerateSpy(...args)),
+ generateSeasonEpisodes: vi.fn((...args) => seasonEpisodesSpy(...args)),
+ verifyArc: vi.fn((...args) => arcVerifySpy(...args)),
+ };
+});
+
// Stub the auto-runner so the test doesn't have to wait for real SSE traffic.
vi.mock('../services/pipeline/autoRunner.js', () => ({
startAutoRunTextStages: vi.fn(async () => ({ runId: 'auto-run-1', alreadyRunning: false })),
@@ -585,4 +599,126 @@ describe('pipeline routes', () => {
status: 'draft',
});
});
+
+ // -----------------------
+ // Arc planning routes (Phase 3 of Story Arc Planning)
+ // -----------------------
+
+ it('POST /series/:id/arc/generate returns preview without committing by default', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'Salt Run' });
+ arcGenerateSpy = vi.fn(async () => ({
+ arc: { logline: 'Whole-arc pitch', summary: 'sum', themes: ['legacy'], protagonistArc: 'P', status: 'draft' },
+ seasons: [{ id: 'sea-1', number: 1, title: 'Pilot' }],
+ runId: 'run-1',
+ providerId: 'claude',
+ model: 'opus-4',
+ }));
+ const r = await request(app).post(`/api/pipeline/series/${ser.body.id}/arc/generate`).send({});
+ expect(r.status).toBe(200);
+ expect(r.body.arc.logline).toBe('Whole-arc pitch');
+ expect(r.body.seasons).toHaveLength(1);
+ expect(r.body.committed).toBe(false);
+ expect(r.body.series).toBe(null);
+
+ // Confirm the series wasn't actually mutated.
+ const reloaded = await request(app).get(`/api/pipeline/series/${ser.body.id}`);
+ expect(reloaded.body.arc).toBe(null);
+ expect(reloaded.body.seasons).toEqual([]);
+ });
+
+ it('POST /series/:id/arc/generate with commit:true persists arc + seasons', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'Salt Run' });
+ arcGenerateSpy = vi.fn(async () => ({
+ arc: { logline: 'Pitch', summary: 'sum', themes: [], protagonistArc: '', status: 'draft' },
+ seasons: [
+ { id: 'sea-1', number: 1, title: 'Pilot', createdAt: '2026-05-10T00:00:00.000Z', updatedAt: '2026-05-10T00:00:00.000Z' },
+ ],
+ runId: 'run-1', providerId: 'claude', model: 'opus-4',
+ }));
+ const r = await request(app).post(`/api/pipeline/series/${ser.body.id}/arc/generate`).send({ commit: true });
+ expect(r.status).toBe(200);
+ expect(r.body.committed).toBe(true);
+ expect(r.body.series.arc.logline).toBe('Pitch');
+ expect(r.body.series.seasons).toHaveLength(1);
+
+ // Confirm the persisted series reads back the same way.
+ const reloaded = await request(app).get(`/api/pipeline/series/${ser.body.id}`);
+ expect(reloaded.body.arc.logline).toBe('Pitch');
+ expect(reloaded.body.seasons[0].title).toBe('Pilot');
+ });
+
+ it('POST /series/:id/seasons/:seasonId/episodes/generate returns preview without committing', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const sea = await request(app).post(`/api/pipeline/series/${ser.body.id}/seasons`).send({
+ title: 'Pilot', synopsis: 'season synopsis',
+ });
+ seasonEpisodesSpy = vi.fn(async () => ({
+ season: sea.body,
+ episodes: [
+ { number: 1, title: 'Ep 1', logline: 'L', synopsis: 'S', primaryCharacters: ['LINA'], arcRole: 'pilot' },
+ { number: 2, title: 'Ep 2', logline: 'L2', synopsis: 'S2', primaryCharacters: ['LINA'], arcRole: 'complication' },
+ ],
+ runId: 'run-1', providerId: 'p', model: 'm',
+ }));
+ const r = await request(app)
+ .post(`/api/pipeline/series/${ser.body.id}/seasons/${sea.body.id}/episodes/generate`)
+ .send({});
+ expect(r.status).toBe(200);
+ expect(r.body.episodes).toHaveLength(2);
+ expect(r.body.committed).toBe(false);
+ expect(r.body.createdIssues).toEqual([]);
+
+ // No issues actually created.
+ const issues = await request(app).get(`/api/pipeline/series/${ser.body.id}/issues`);
+ expect(issues.body).toEqual([]);
+ });
+
+ it('POST /series/:id/seasons/:seasonId/episodes/generate with commit:true creates one issue per episode', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const sea = await request(app).post(`/api/pipeline/series/${ser.body.id}/seasons`).send({
+ title: 'Pilot', synopsis: 'season synopsis',
+ });
+ seasonEpisodesSpy = vi.fn(async () => ({
+ season: sea.body,
+ episodes: [
+ { number: 1, title: 'Ep 1', logline: 'L1', synopsis: 'Pilot synopsis', primaryCharacters: ['LINA'], arcRole: 'pilot' },
+ { number: 2, title: 'Ep 2', logline: 'L2', synopsis: 'Comp synopsis', primaryCharacters: ['LINA'], arcRole: 'complication' },
+ ],
+ runId: 'run-2', providerId: 'p', model: 'm',
+ }));
+ const r = await request(app)
+ .post(`/api/pipeline/series/${ser.body.id}/seasons/${sea.body.id}/episodes/generate`)
+ .send({ commit: true });
+ expect(r.status).toBe(200);
+ expect(r.body.committed).toBe(true);
+ expect(r.body.createdIssues).toHaveLength(2);
+ expect(r.body.createdIssues[0].seasonId).toBe(sea.body.id);
+ expect(r.body.createdIssues[0].arcPosition).toBe(1);
+ expect(r.body.createdIssues[0].title).toBe('Ep 1');
+ // Synopsis lands in stages.idea.input so auto-run-text has a seed.
+ expect(r.body.createdIssues[0].stages.idea.input).toContain('Pilot synopsis');
+ expect(r.body.createdIssues[1].arcPosition).toBe(2);
+
+ const issues = await request(app).get(`/api/pipeline/series/${ser.body.id}/issues`);
+ expect(issues.body.map((i) => i.title)).toEqual(['Ep 1', 'Ep 2']);
+ });
+
+ it('POST /series/:id/arc/verify forwards to the planner and returns issues', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ arcVerifySpy = vi.fn(async () => ({
+ issues: [
+ { severity: 'high', location: 'season:2/episode:5', problem: 'character is dead in S1', suggestion: 'remove from S2' },
+ ],
+ runId: 'r', providerId: 'p', model: 'm',
+ }));
+ const r = await request(app).post(`/api/pipeline/series/${ser.body.id}/arc/verify`).send({});
+ expect(r.status).toBe(200);
+ expect(r.body.issues).toHaveLength(1);
+ expect(r.body.issues[0].severity).toBe('high');
+ });
});
diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.js
new file mode 100644
index 0000000000..eb7251582b
--- /dev/null
+++ b/server/services/pipeline/arcPlanner.js
@@ -0,0 +1,348 @@
+/**
+ * Pipeline — Series Arc Planning Service
+ *
+ * Phase 3 of the Story Arc Planning initiative. Owns the three LLM-driven
+ * planning passes that populate `series.arc` and `series.seasons[]`:
+ *
+ * generateArcOverview(seriesId) → seeds series.arc + series.seasons[]
+ * generateSeasonEpisodes(seriesId, seasonId, { force? })
+ * → seeds issues under a season
+ * verifyArc(seriesId) → cross-season continuity pass
+ *
+ * Each function returns `{ result, runId, providerId, model }` so the caller
+ * can react to a successful run (persisted via `updateSeries` / `createSeason`
+ * / `createIssue` chains as appropriate) and surface the runId in /runs.
+ *
+ * Extraction-only; mirrors how `bibleExtractor.js` and `sceneExtractor.js`
+ * are split — the caller decides whether to persist. The two-step shape
+ * keeps the LLM call replayable and lets the UI preview the plan before
+ * committing it (Phase 4's confirm-before-seeding pattern).
+ */
+
+import { runStagedLLM } from '../../lib/stageRunner.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { getSeries } from './series.js';
+import { listIssues } from './issues.js';
+import { sanitizeArc, sanitizeSeasonList, sanitizeSeason, buildSeason } from '../../lib/storyArc.js';
+
+export const ERR_VALIDATION = 'PIPELINE_ARC_VALIDATION';
+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']);
+
+/**
+ * Pull only the fields the arc-overview prompt cares about from the series
+ * bible, so a verbose series record doesn't blow the prompt budget.
+ */
+function buildArcOverviewContext(series) {
+ return {
+ series: {
+ name: series.name,
+ logline: series.logline,
+ premise: series.premise,
+ styleNotes: series.styleNotes,
+ targetFormat: series.targetFormat,
+ issueCountTarget: series.issueCountTarget,
+ },
+ existingCharactersJson: JSON.stringify(series.characters || [], null, 2),
+ existingSettingsJson: JSON.stringify(series.settings || [], null, 2),
+ existingObjectsJson: JSON.stringify(series.objects || [], null, 2),
+ };
+}
+
+/**
+ * Coerce the LLM's `seasonOutlines[]` into a list of canonical Season records.
+ * Reuses `buildSeason` so the new seasons get fresh sea-uuid ids + timestamps
+ * + run through the sanitizer. Defensive — drops malformed entries silently
+ * so a partial response doesn't crash the route layer.
+ */
+function shapeSeasonOutlines(rawOutlines) {
+ if (!Array.isArray(rawOutlines)) return [];
+ const out = [];
+ for (const raw of rawOutlines) {
+ const season = buildSeason({
+ number: raw?.number,
+ title: raw?.title,
+ logline: raw?.logline,
+ endingHook: raw?.endingHook,
+ episodeCountTarget: raw?.episodeCountTarget,
+ });
+ if (season) out.push(season);
+ }
+ return out;
+}
+
+export async function generateArcOverview(seriesId, options = {}) {
+ const series = await getSeries(seriesId);
+ const ctx = buildArcOverviewContext(series);
+ const { content, runId, providerId, model } = await runStagedLLM(
+ 'pipeline-arc-overview',
+ ctx,
+ {
+ providerOverride: options.providerOverride,
+ modelOverride: options.modelOverride,
+ returnsJson: true,
+ source: 'pipeline-arc-overview',
+ },
+ );
+ // Build the canonical arc + seasons shape from the LLM payload. We send
+ // both back to the caller so the route can persist in one updateSeries
+ // call (or hand the user a preview before committing).
+ const arc = sanitizeArc({
+ logline: content?.logline || '',
+ summary: content?.summary || '',
+ themes: content?.themes,
+ protagonistArc: content?.protagonistArc || '',
+ status: 'draft',
+ });
+ const seasons = shapeSeasonOutlines(content?.seasonOutlines);
+ return {
+ arc,
+ seasons,
+ raw: content,
+ runId,
+ providerId,
+ model,
+ };
+}
+
+/**
+ * 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.
+ */
+function buildSeasonEpisodesContext(series, season, priorSeasons) {
+ 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');
+ return {
+ series: {
+ name: series.name,
+ logline: series.logline,
+ premise: series.premise,
+ styleNotes: series.styleNotes,
+ },
+ arc: {
+ logline: arc.logline || '',
+ protagonistArc: arc.protagonistArc || '',
+ themesCsv,
+ },
+ priorSeasonsContext,
+ season: {
+ number: season.number,
+ title: season.title,
+ logline: season.logline,
+ synopsis: season.synopsis,
+ endingHook: season.endingHook,
+ episodeCountTarget: season.episodeCountTarget,
+ },
+ existingCharactersJson: JSON.stringify(series.characters || [], null, 2),
+ existingSettingsJson: JSON.stringify(series.settings || [], null, 2),
+ existingObjectsJson: JSON.stringify(series.objects || [], null, 2),
+ };
+}
+
+/**
+ * Shape `episodes[]` from the LLM into the canonical issue-like preview
+ * shape. We do NOT persist here — the route layer creates the issues via
+ * `createIssue` so a preview/confirm flow can land in Phase 4.
+ *
+ * Drops entries with no title, clamps `number` >= 1, and validates `arcRole`
+ * against the controlled vocab the prompt promised. An invalid `arcRole`
+ * collapses to `null` rather than the entry being rejected — the rest of the
+ * episode metadata is still useful.
+ */
+function shapeEpisodes(rawEpisodes) {
+ if (!Array.isArray(rawEpisodes)) return [];
+ const out = [];
+ let nextNumber = 1;
+ for (const raw of rawEpisodes) {
+ const title = typeof raw?.title === 'string' ? raw.title.trim().slice(0, 300) : '';
+ if (!title) continue;
+ const number = Number.isFinite(raw?.number) && raw.number > 0
+ ? Math.floor(raw.number)
+ : nextNumber;
+ nextNumber = number + 1;
+ const arcRole = ARC_ROLES.has(raw?.arcRole) ? raw.arcRole : null;
+ const primaryCharacters = Array.isArray(raw?.primaryCharacters)
+ ? raw.primaryCharacters.filter((c) => typeof c === 'string' && c.trim()).map((c) => c.trim().slice(0, 200)).slice(0, 12)
+ : [];
+ out.push({
+ number,
+ title,
+ logline: typeof raw?.logline === 'string' ? raw.logline.trim().slice(0, 500) : '',
+ synopsis: typeof raw?.synopsis === 'string' ? raw.synopsis.trim().slice(0, 4000) : '',
+ primaryCharacters,
+ arcRole,
+ });
+ }
+ return out;
+}
+
+export async function generateSeasonEpisodes(seriesId, seasonId, options = {}) {
+ const series = await getSeries(seriesId);
+ const seasons = series.seasons || [];
+ const season = seasons.find((s) => s.id === seasonId);
+ if (!season) {
+ throw makeErr(`Season not found on series: ${seasonId}`, ERR_VALIDATION);
+ }
+ // A season with no synopsis + no logline gives the LLM nothing to riff
+ // against — fail loud so the user sees the misconfiguration instead of
+ // getting back 8 episodes of "a thing happens then another thing".
+ if (!season.synopsis?.trim() && !season.logline?.trim()) {
+ throw makeErr(
+ `Season "${season.title || season.number}" has no synopsis or logline — fill at least one before generating episodes`,
+ ERR_VALIDATION,
+ );
+ }
+ // Prior-seasons context for continuity. Strict number-ordering rather than
+ // id-ordering because seasons[] is already sorted by number in the
+ // sanitizer; this matches what the user is editing on screen.
+ const priorSeasons = seasons.filter((s) => (s.number || 0) < (season.number || 0));
+
+ const ctx = buildSeasonEpisodesContext(series, season, priorSeasons);
+ const { content, runId, providerId, model } = await runStagedLLM(
+ 'pipeline-season-episodes',
+ ctx,
+ {
+ providerOverride: options.providerOverride,
+ modelOverride: options.modelOverride,
+ returnsJson: true,
+ source: 'pipeline-season-episodes',
+ },
+ );
+ const episodes = shapeEpisodes(content?.episodes);
+ return {
+ season,
+ episodes,
+ raw: content,
+ runId,
+ providerId,
+ model,
+ };
+}
+
+/**
+ * Build the verify-pass context — a JSON-encoded tree of seasons + their
+ * child issues so the LLM has a single structural blob to scan. Issues are
+ * looked up via `listIssues` so the verify pass sees the *current* set, not
+ * a stale snapshot.
+ */
+async function buildVerifyContext(series) {
+ const seasons = sanitizeSeasonList(series.seasons || []);
+ const issues = await listIssues({ seriesId: series.id });
+ // Group issues by seasonId so the tree's leaf order matches the seasons'
+ // arcPosition order. Ungrouped issues land in a `null` bucket so the LLM
+ // sees them too.
+ const issuesBySeason = new Map();
+ for (const iss of issues) {
+ const key = iss.seasonId || null;
+ if (!issuesBySeason.has(key)) issuesBySeason.set(key, []);
+ issuesBySeason.get(key).push({
+ number: iss.number,
+ title: iss.title,
+ status: iss.status,
+ arcPosition: iss.arcPosition,
+ });
+ }
+ for (const list of issuesBySeason.values()) {
+ list.sort((a, b) => (a.arcPosition ?? 9999) - (b.arcPosition ?? 9999) || (a.number || 0) - (b.number || 0));
+ }
+ const tree = seasons.map((s) => ({
+ number: s.number,
+ title: s.title,
+ logline: s.logline,
+ synopsis: s.synopsis,
+ endingHook: s.endingHook,
+ episodeCountTarget: s.episodeCountTarget,
+ themes: s.themes,
+ status: s.status,
+ episodes: issuesBySeason.get(s.id) || [],
+ }));
+ const ungrouped = issuesBySeason.get(null) || [];
+ if (ungrouped.length) {
+ tree.push({
+ number: null,
+ title: '(ungrouped issues)',
+ episodes: ungrouped,
+ });
+ }
+ const arc = series.arc || {};
+ return {
+ series: {
+ name: series.name,
+ logline: series.logline,
+ premise: series.premise,
+ targetFormat: series.targetFormat,
+ },
+ arc: {
+ logline: arc.logline || '',
+ summary: arc.summary || '',
+ protagonistArc: arc.protagonistArc || '',
+ themesCsv: Array.isArray(arc.themes) ? arc.themes.join(', ') : '',
+ },
+ seasonsTreeJson: JSON.stringify(tree, null, 2),
+ existingCharactersJson: JSON.stringify(series.characters || [], null, 2),
+ existingSettingsJson: JSON.stringify(series.settings || [], null, 2),
+ existingObjectsJson: JSON.stringify(series.objects || [], null, 2),
+ };
+}
+
+/**
+ * Shape verify-pass issues. Drops malformed entries (no problem, invalid
+ * severity) so a partial LLM response doesn't trash the route response.
+ */
+function shapeVerifyIssues(rawIssues) {
+ if (!Array.isArray(rawIssues)) return [];
+ const out = [];
+ for (const raw of rawIssues) {
+ const problem = typeof raw?.problem === 'string' ? raw.problem.trim() : '';
+ if (!problem) continue;
+ const severity = VERIFY_SEVERITIES.has(raw?.severity) ? raw.severity : 'medium';
+ out.push({
+ severity,
+ location: typeof raw?.location === 'string' ? raw.location.trim().slice(0, 200) : '',
+ problem: problem.slice(0, 2000),
+ suggestion: typeof raw?.suggestion === 'string' ? raw.suggestion.trim().slice(0, 2000) : '',
+ });
+ }
+ return out;
+}
+
+export async function verifyArc(seriesId, options = {}) {
+ const series = await getSeries(seriesId);
+ if (!series.arc) {
+ throw new ServerError(
+ 'Series has no arc to verify — run /arc/generate first',
+ { status: 400, code: 'PIPELINE_NO_ARC' },
+ );
+ }
+ const ctx = await buildVerifyContext(series);
+ const { content, runId, providerId, model } = await runStagedLLM(
+ 'pipeline-arc-verify',
+ ctx,
+ {
+ providerOverride: options.providerOverride,
+ modelOverride: options.modelOverride,
+ returnsJson: true,
+ source: 'pipeline-arc-verify',
+ },
+ );
+ const issues = shapeVerifyIssues(content?.issues);
+ return { issues, raw: content, runId, providerId, model };
+}
+
+// Export internals for tests.
+export const __testing = {
+ buildArcOverviewContext,
+ buildSeasonEpisodesContext,
+ buildVerifyContext,
+ shapeSeasonOutlines,
+ shapeEpisodes,
+ shapeVerifyIssues,
+};
diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.js
new file mode 100644
index 0000000000..424eb8a875
--- /dev/null
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -0,0 +1,258 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const fileStore = new Map();
+let stageRunnerSpy;
+
+vi.mock('../../lib/fileUtils.js', () => ({
+ PATHS: { data: '/mock/data' },
+ ensureDir: vi.fn().mockResolvedValue(undefined),
+ atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
+ readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),
+}));
+
+let uuidCounter = 0;
+vi.mock('crypto', async () => {
+ const actual = await vi.importActual('crypto');
+ return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };
+});
+
+// Stub the staged-LLM runner so the test owns the LLM response shape.
+// Each test sets `stageRunnerSpy = vi.fn(...)` to control what comes back.
+vi.mock('../../lib/stageRunner.js', () => ({
+ runStagedLLM: vi.fn((...args) => stageRunnerSpy(...args)),
+ extractJson: (raw) => JSON.parse(raw),
+}));
+
+const seriesSvc = await import('./series.js');
+const issuesSvc = await import('./issues.js');
+const seasonsSvc = await import('./seasons.js');
+const planner = await import('./arcPlanner.js');
+
+async function setupSeries(overrides = {}) {
+ return seriesSvc.createSeries({
+ name: 'Salt Run',
+ logline: 'A foundry city goes silent.',
+ premise: 'Long-form premise.',
+ styleNotes: 'moebius linework',
+ issueCountTarget: 24,
+ ...overrides,
+ });
+}
+
+describe('arcPlanner — generateArcOverview', () => {
+ beforeEach(() => {
+ fileStore.clear();
+ uuidCounter = 0;
+ stageRunnerSpy = undefined;
+ });
+
+ it('runs the prompt and returns sanitized arc + seasons preview', async () => {
+ const s = await setupSeries();
+ stageRunnerSpy = vi.fn(async () => ({
+ content: {
+ logline: 'A foundry city falls and rises.',
+ summary: 'Three-season arc...',
+ themes: ['legacy', 'labor'],
+ protagonistArc: 'From surveyor to founder.',
+ seasonOutlines: [
+ { number: 1, title: 'The Choir Awakens', logline: 'The pilot.', endingHook: 'silence', episodeCountTarget: 8 },
+ { number: 2, title: 'Diaspora', logline: 'The middle.', endingHook: 'reunion', episodeCountTarget: 8 },
+ { number: 3, title: 'Salt at the Root', logline: 'The finale.', endingHook: '', episodeCountTarget: 8 },
+ ],
+ },
+ runId: 'run-abc',
+ providerId: 'claude',
+ model: 'opus-4',
+ }));
+
+ const out = await planner.generateArcOverview(s.id);
+ expect(stageRunnerSpy).toHaveBeenCalledWith(
+ 'pipeline-arc-overview',
+ expect.objectContaining({ series: expect.objectContaining({ name: 'Salt Run' }) }),
+ expect.objectContaining({ returnsJson: true, source: 'pipeline-arc-overview' }),
+ );
+ expect(out.arc).toMatchObject({
+ logline: 'A foundry city falls and rises.',
+ themes: ['legacy', 'labor'],
+ status: 'draft',
+ });
+ expect(out.seasons).toHaveLength(3);
+ expect(out.seasons[0].id).toMatch(/^sea-/);
+ expect(out.seasons[0].title).toBe('The Choir Awakens');
+ expect(out.seasons[0].episodeCountTarget).toBe(8);
+ expect(out.runId).toBe('run-abc');
+ });
+
+ it('drops malformed season outlines and returns the rest', async () => {
+ const s = await setupSeries();
+ stageRunnerSpy = vi.fn(async () => ({
+ content: {
+ logline: 'L',
+ summary: 'S',
+ themes: [],
+ protagonistArc: 'A',
+ seasonOutlines: [
+ { number: 1, title: 'Pilot' },
+ { number: 0, title: '' }, // dropped — no title + zero number
+ { number: 2, title: 'Aftermath' },
+ 'this is not an object', // dropped
+ ],
+ },
+ runId: 'r1', providerId: 'p', model: 'm',
+ }));
+ const out = await planner.generateArcOverview(s.id);
+ expect(out.seasons.map((s) => s.title)).toEqual(['Pilot', 'Aftermath']);
+ });
+
+ it('returns null arc when every identifying field is empty', async () => {
+ const s = await setupSeries();
+ stageRunnerSpy = vi.fn(async () => ({
+ content: { logline: '', summary: '', themes: [], protagonistArc: '', seasonOutlines: [] },
+ runId: 'r1', providerId: 'p', model: 'm',
+ }));
+ const out = await planner.generateArcOverview(s.id);
+ expect(out.arc).toBe(null);
+ expect(out.seasons).toEqual([]);
+ });
+});
+
+describe('arcPlanner — generateSeasonEpisodes', () => {
+ beforeEach(() => {
+ fileStore.clear();
+ uuidCounter = 0;
+ stageRunnerSpy = undefined;
+ });
+
+ async function setupSeriesWithSeasons() {
+ const s = await setupSeries();
+ const s1 = await seasonsSvc.createSeason(s.id, {
+ title: 'Pilot',
+ logline: 'season 1 logline',
+ synopsis: 'season 1 synopsis',
+ episodeCountTarget: 8,
+ });
+ const s2 = await seasonsSvc.createSeason(s.id, {
+ title: 'Diaspora',
+ logline: 'season 2 logline',
+ synopsis: 'season 2 synopsis',
+ episodeCountTarget: 8,
+ });
+ return { series: await seriesSvc.getSeries(s.id), seasons: [s1, s2] };
+ }
+
+ it('builds prior-seasons context only for seasons before the target', async () => {
+ const { series, seasons } = await setupSeriesWithSeasons();
+ stageRunnerSpy = vi.fn(async () => ({
+ content: { episodes: [{ number: 1, title: 'Ep 1', logline: '', synopsis: '', arcRole: 'pilot' }] },
+ runId: 'r1', providerId: 'p', model: 'm',
+ }));
+ await planner.generateSeasonEpisodes(series.id, seasons[1].id);
+ const call = stageRunnerSpy.mock.calls[0];
+ const ctx = call[1];
+ expect(ctx.season.title).toBe('Diaspora');
+ expect(ctx.priorSeasonsContext).toContain('Season 1 — Pilot');
+ expect(ctx.priorSeasonsContext).not.toContain('Diaspora');
+ });
+
+ it('shows "first season" copy for the season-1 case', async () => {
+ const { series, seasons } = await setupSeriesWithSeasons();
+ stageRunnerSpy = vi.fn(async () => ({
+ content: { episodes: [] }, runId: 'r1', providerId: 'p', model: 'm',
+ }));
+ await planner.generateSeasonEpisodes(series.id, seasons[0].id);
+ const ctx = stageRunnerSpy.mock.calls[0][1];
+ expect(ctx.priorSeasonsContext).toContain('first season');
+ });
+
+ it('rejects ERR_VALIDATION when the season has neither logline nor synopsis', async () => {
+ const s = await setupSeries();
+ const bare = await seasonsSvc.createSeason(s.id, { title: 'Bare', number: 1 });
+ await expect(planner.generateSeasonEpisodes(s.id, bare.id))
+ .rejects.toMatchObject({ code: planner.ERR_VALIDATION });
+ });
+
+ it('rejects ERR_VALIDATION for an unknown season id', async () => {
+ const s = await setupSeries();
+ await expect(planner.generateSeasonEpisodes(s.id, 'sea-nope'))
+ .rejects.toMatchObject({ code: planner.ERR_VALIDATION });
+ });
+
+ it('shapes episodes, drops untitled entries, and validates arcRole', async () => {
+ const { series, seasons } = await setupSeriesWithSeasons();
+ stageRunnerSpy = vi.fn(async () => ({
+ content: {
+ episodes: [
+ { number: 1, title: 'Ep 1', logline: 'L1', synopsis: 'S1', primaryCharacters: ['LINA'], arcRole: 'pilot' },
+ { number: 2, title: '', logline: 'no title' }, // dropped
+ { number: 3, title: 'Ep 3', arcRole: 'bogus-role', primaryCharacters: ['LINA', 42, ' '] },
+ ],
+ },
+ runId: 'r1', providerId: 'p', model: 'm',
+ }));
+ const out = await planner.generateSeasonEpisodes(series.id, seasons[0].id);
+ expect(out.episodes.map((e) => e.title)).toEqual(['Ep 1', 'Ep 3']);
+ expect(out.episodes[1].arcRole).toBe(null); // invalid role drops to null
+ expect(out.episodes[1].primaryCharacters).toEqual(['LINA']); // non-string + blank entries filtered
+ });
+});
+
+describe('arcPlanner — verifyArc', () => {
+ beforeEach(() => {
+ fileStore.clear();
+ uuidCounter = 0;
+ stageRunnerSpy = undefined;
+ });
+
+ it('throws 400 NO_ARC if the series has no arc to verify', async () => {
+ const s = await setupSeries();
+ await expect(planner.verifyArc(s.id))
+ .rejects.toMatchObject({ status: 400, code: 'PIPELINE_NO_ARC' });
+ });
+
+ it('builds the seasons tree with grouped + ungrouped issues, then runs the prompt', async () => {
+ const s = await setupSeries();
+ await seriesSvc.updateSeries(s.id, {
+ arc: { logline: 'Whole-arc pitch', summary: 'A long summary', themes: ['legacy'] },
+ });
+ const sea = await seasonsSvc.createSeason(s.id, { title: 'Pilot', synopsis: 'season synopsis' });
+ const grouped = await issuesSvc.createIssue({ seriesId: s.id, title: 'Ep 1', seasonId: sea.id, arcPosition: 1 });
+ const ungrouped = await issuesSvc.createIssue({ seriesId: s.id, title: 'Floating' });
+
+ stageRunnerSpy = vi.fn(async () => ({
+ content: { issues: [{ severity: 'medium', location: 'season:1', problem: 'one beat', suggestion: 'add another' }] },
+ runId: 'r1', providerId: 'p', model: 'm',
+ }));
+
+ const out = await planner.verifyArc(s.id);
+ const ctx = stageRunnerSpy.mock.calls[0][1];
+ const tree = JSON.parse(ctx.seasonsTreeJson);
+ expect(tree[0].title).toBe('Pilot');
+ expect(tree[0].episodes.map((e) => e.title)).toEqual([grouped.title]);
+ expect(tree[tree.length - 1].title).toBe('(ungrouped issues)');
+ expect(tree[tree.length - 1].episodes.map((e) => e.title)).toEqual([ungrouped.title]);
+
+ expect(out.issues).toEqual([
+ { severity: 'medium', location: 'season:1', problem: 'one beat', suggestion: 'add another' },
+ ]);
+ });
+
+ it('drops malformed verify issues + defaults severity to medium', async () => {
+ const s = await setupSeries();
+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'L' } });
+ stageRunnerSpy = vi.fn(async () => ({
+ content: {
+ issues: [
+ { severity: 'high', problem: 'real one' },
+ { problem: '' }, // dropped — no problem
+ { problem: 'no severity' }, // kept — severity defaults to medium
+ { severity: 'bogus', problem: 'invalid severity', location: 'season:2' },
+ ],
+ },
+ runId: 'r1', providerId: 'p', model: 'm',
+ }));
+ const out = await planner.verifyArc(s.id);
+ expect(out.issues.map((i) => i.problem)).toEqual(['real one', 'no severity', 'invalid severity']);
+ expect(out.issues[1].severity).toBe('medium');
+ expect(out.issues[2].severity).toBe('medium');
+ });
+});
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index e0fd6a30c6..a68ab29613 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -179,6 +179,10 @@ export async function createIssue(input = {}) {
number: input.number || nextIssueNumber(state.issues, seriesId),
title,
status: 'draft',
+ // Phase 2: optional arc pointers passed by the season-episodes generator
+ // (and any future caller wiring an issue to a season at create time).
+ seasonId: 'seasonId' in input ? input.seasonId : null,
+ arcPosition: 'arcPosition' in input ? input.arcPosition : null,
stages: input.stages || {},
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),