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): arc + season schema and CRUD

Adam Eivy83328424e4f8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index b17d683a67..5d36880ccb 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,9 @@
# Unreleased Changes
+## Added
+
+- **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
- **Pipeline Series page — two-pane layout.** PipelineSeries (`/pipeline/series/:id`) drops its `max-w-5xl` cap and splits into a sticky left bible sidebar + right card-grid canvas at `lg+`. The bible inputs (name / format / logline / target issue count / premise / style notes / world / characters) live in the sidebar; issues/episodes render as a responsive card grid (1/2/3/4 cols across breakpoints) showing number, status badge, title (line-clamped), and `updated <timeAgo>`. Sidebar collapses to a 48px rail via a panel toggle (state persists in `localStorage` under `portos-pipeline-series-sidebar-collapsed`) so the canvas can use the full viewport when you're deep in episode work. Mobile (< lg) stays single-column with the sidebar reflowing above the canvas. Phase 1 of the Pipeline Story-Arc Planning initiative — pure UI refactor, no schema or API change; subsequent phases evolve the card grid into an Arc → Season → Episode tree.
diff --git a/server/lib/storyArc.js b/server/lib/storyArc.js
new file mode 100644
index 0000000000..2f07662ef4
--- /dev/null
+++ b/server/lib/storyArc.js
@@ -0,0 +1,161 @@
+/**
+ * Canonical Arc + Season shapes for the Pipeline Story Arc Planning feature.
+ *
+ * Sibling to `storyBible.js` — same role, different scope. Story bibles describe
+ * the *characters, settings, and objects* that recur across an arc; this module
+ * describes the *temporal spine*: the multi-season story arc and its season
+ * breakdown. Both live on the series record.
+ *
+ * Shapes:
+ * series.arc (optional) overall multi-season story spine
+ * series.seasons[] ordered list of seasons/volumes
+ * issue.seasonId (optional pointer back to a season)
+ * issue.arcPosition (optional ordinal within the season — drives auto-sort)
+ *
+ * Used by `services/pipeline/series.js` (sanitize on load/save) and
+ * `services/pipeline/seasons.js` (CRUD + child-issue reassignment on delete).
+ */
+
+import { randomUUID } from 'crypto';
+import { isStr, trimTo } from './storyBible.js';
+
+export const ARC_LIMITS = Object.freeze({
+ LOGLINE_MAX: 500,
+ SUMMARY_MAX: 8000,
+ PROTAGONIST_ARC_MAX: 4000,
+ THEME_MAX: 100,
+ THEMES_PER_ARC_MAX: 20,
+ // Season
+ SEASON_TITLE_MAX: 200,
+ SEASON_LOGLINE_MAX: 500,
+ SEASON_SYNOPSIS_MAX: 4000,
+ SEASON_ENDING_HOOK_MAX: 1000,
+ SEASON_NUMBER_MAX: 99,
+ SEASON_EPISODE_COUNT_MAX: 999,
+ SEASONS_PER_SERIES_MAX: 50,
+});
+
+export const ARC_STATUSES = Object.freeze(['draft', 'verified']);
+export const SEASON_STATUSES = Object.freeze(['draft', 'verified', 'in-production', 'complete']);
+
+const SEASON_ID_PREFIX = 'sea-';
+// `id` of an existing season as written by us. Used by `sanitizeSeason` so
+// callers (route patch handlers, season service) accept either an id we
+// generated or an opaque id from an imported series file.
+const SEASON_ID_RE = /^sea-[a-zA-Z0-9-]+$/;
+
+const nowIso = () => new Date().toISOString();
+
+function ensureSeasonId(raw) {
+ if (isStr(raw) && SEASON_ID_RE.test(raw)) return raw;
+ return `${SEASON_ID_PREFIX}${randomUUID()}`;
+}
+
+function cleanThemes(raw) {
+ if (!Array.isArray(raw)) return [];
+ const out = [];
+ for (const v of raw) {
+ const s = trimTo(v, ARC_LIMITS.THEME_MAX);
+ if (s) out.push(s);
+ if (out.length >= ARC_LIMITS.THEMES_PER_ARC_MAX) break;
+ }
+ return out;
+}
+
+/**
+ * Sanitize the optional `series.arc` field. Returns `null` if the input is
+ * empty (no identifying fields) — callers store `null` to mean "no arc yet."
+ * Anything else round-trips through the canonical shape with explicit
+ * type-safe defaults so a partial-shape payload from the LLM (or an old
+ * series.json) never crashes downstream readers.
+ */
+export function sanitizeArc(raw) {
+ if (raw == null) return null;
+ if (typeof raw !== 'object') return null;
+ const logline = trimTo(raw.logline, ARC_LIMITS.LOGLINE_MAX);
+ const summary = trimTo(raw.summary, ARC_LIMITS.SUMMARY_MAX);
+ const protagonistArc = trimTo(raw.protagonistArc, ARC_LIMITS.PROTAGONIST_ARC_MAX);
+ const themes = cleanThemes(raw.themes);
+ // An arc with zero identifying content is indistinguishable from "no arc"
+ // — store null so the UI can render the empty state instead of a blank
+ // expanded panel. This also keeps the JSON tighter on disk.
+ if (!logline && !summary && !protagonistArc && themes.length === 0) return null;
+ const status = ARC_STATUSES.includes(raw.status) ? raw.status : 'draft';
+ return { logline, summary, protagonistArc, themes, status };
+}
+
+/**
+ * Sanitize one season. Returns `null` if the season has no identifying content
+ * (no title and no number > 0) — `sanitizeSeasonList` then drops it on the
+ * floor. `preserveTimestamps: false` forces a fresh `updatedAt` (used when a
+ * patch lands on an existing season).
+ */
+export function sanitizeSeason(raw, { preserveTimestamps = true } = {}) {
+ if (!raw || typeof raw !== 'object') return null;
+ const title = trimTo(raw.title, ARC_LIMITS.SEASON_TITLE_MAX);
+ const number = Number.isFinite(raw.number)
+ ? Math.max(0, Math.min(ARC_LIMITS.SEASON_NUMBER_MAX, Math.floor(raw.number)))
+ : 0;
+ // A season with neither a title nor a positive number is unaddressable —
+ // there's nothing for the UI to render and nothing for an issue's
+ // `seasonId` pointer to match against meaningfully.
+ if (!title && number <= 0) return null;
+ const episodeCountTarget = Number.isFinite(raw.episodeCountTarget)
+ ? Math.max(0, Math.min(ARC_LIMITS.SEASON_EPISODE_COUNT_MAX, Math.floor(raw.episodeCountTarget)))
+ : 0;
+ const status = SEASON_STATUSES.includes(raw.status) ? raw.status : 'draft';
+ const created = preserveTimestamps && isStr(raw.createdAt) ? raw.createdAt : nowIso();
+ const updated = preserveTimestamps && isStr(raw.updatedAt) ? raw.updatedAt : nowIso();
+ return {
+ id: ensureSeasonId(raw.id),
+ number,
+ title,
+ logline: trimTo(raw.logline, ARC_LIMITS.SEASON_LOGLINE_MAX),
+ synopsis: trimTo(raw.synopsis, ARC_LIMITS.SEASON_SYNOPSIS_MAX),
+ episodeCountTarget,
+ themes: cleanThemes(raw.themes),
+ endingHook: trimTo(raw.endingHook, ARC_LIMITS.SEASON_ENDING_HOOK_MAX),
+ status,
+ createdAt: created,
+ updatedAt: updated,
+ };
+}
+
+/**
+ * Sanitize the `series.seasons[]` field. Drops rejected entries, caps at
+ * SEASONS_PER_SERIES_MAX, deduplicates ids (last-write-wins on collision),
+ * and sorts by `number` ascending so consumers can render straight from the
+ * array.
+ */
+export function sanitizeSeasonList(rawList, opts = {}) {
+ if (!Array.isArray(rawList)) return [];
+ const byId = new Map();
+ for (const raw of rawList) {
+ const s = sanitizeSeason(raw, opts);
+ if (!s) continue;
+ byId.set(s.id, s);
+ if (byId.size >= ARC_LIMITS.SEASONS_PER_SERIES_MAX) break;
+ }
+ return [...byId.values()].sort((a, b) => (a.number || 0) - (b.number || 0));
+}
+
+/**
+ * Build a fresh season from a create payload. The route layer enforces a
+ * minimum shape (title + number) via zod; this function fills in id,
+ * timestamps, and the canonical defaults.
+ */
+export function buildSeason(input = {}) {
+ return sanitizeSeason({
+ id: `${SEASON_ID_PREFIX}${randomUUID()}`,
+ number: input.number,
+ title: input.title,
+ logline: input.logline,
+ synopsis: input.synopsis,
+ episodeCountTarget: input.episodeCountTarget,
+ themes: input.themes,
+ endingHook: input.endingHook,
+ status: input.status,
+ createdAt: nowIso(),
+ updatedAt: nowIso(),
+ });
+}
diff --git a/server/lib/storyArc.test.js b/server/lib/storyArc.test.js
new file mode 100644
index 0000000000..18c1557fda
--- /dev/null
+++ b/server/lib/storyArc.test.js
@@ -0,0 +1,153 @@
+import { describe, it, expect, vi } from 'vitest';
+
+let uuidCounter = 0;
+vi.mock('crypto', async () => {
+ const actual = await vi.importActual('crypto');
+ return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };
+});
+
+const { sanitizeArc, sanitizeSeason, sanitizeSeasonList, buildSeason, ARC_LIMITS } = await import('./storyArc.js');
+
+describe('storyArc — sanitizeArc', () => {
+ it('returns null for null/undefined/non-objects', () => {
+ expect(sanitizeArc(null)).toBe(null);
+ expect(sanitizeArc(undefined)).toBe(null);
+ expect(sanitizeArc('arc')).toBe(null);
+ expect(sanitizeArc(42)).toBe(null);
+ });
+
+ it('returns null when every identifying field is empty', () => {
+ expect(sanitizeArc({})).toBe(null);
+ expect(sanitizeArc({ logline: '', summary: '', protagonistArc: '', themes: [] })).toBe(null);
+ expect(sanitizeArc({ logline: ' ', themes: ['', ' '] })).toBe(null);
+ });
+
+ it('round-trips the canonical shape with defaults filled in', () => {
+ const arc = sanitizeArc({ logline: 'A cult, a city, a child.' });
+ expect(arc).toEqual({
+ logline: 'A cult, a city, a child.',
+ summary: '',
+ protagonistArc: '',
+ themes: [],
+ status: 'draft',
+ });
+ });
+
+ it('drops invalid status', () => {
+ expect(sanitizeArc({ logline: 'x', status: 'bogus' }).status).toBe('draft');
+ expect(sanitizeArc({ logline: 'x', status: 'verified' }).status).toBe('verified');
+ });
+
+ it('trims fields to their cap and cleans themes', () => {
+ const arc = sanitizeArc({
+ logline: 'a'.repeat(ARC_LIMITS.LOGLINE_MAX + 50),
+ themes: [' betrayal ', '', 'legacy', 'x'.repeat(ARC_LIMITS.THEME_MAX + 5)],
+ });
+ expect(arc.logline.length).toBe(ARC_LIMITS.LOGLINE_MAX);
+ expect(arc.themes).toEqual(['betrayal', 'legacy', 'x'.repeat(ARC_LIMITS.THEME_MAX)]);
+ });
+
+ it('caps themes at THEMES_PER_ARC_MAX', () => {
+ const many = Array.from({ length: ARC_LIMITS.THEMES_PER_ARC_MAX + 5 }, (_, i) => `t${i}`);
+ expect(sanitizeArc({ logline: 'x', themes: many }).themes).toHaveLength(ARC_LIMITS.THEMES_PER_ARC_MAX);
+ });
+});
+
+describe('storyArc — sanitizeSeason', () => {
+ it('rejects entries with neither title nor positive number', () => {
+ expect(sanitizeSeason({})).toBe(null);
+ expect(sanitizeSeason({ number: 0 })).toBe(null);
+ expect(sanitizeSeason({ title: '' })).toBe(null);
+ expect(sanitizeSeason({ title: ' ' })).toBe(null);
+ });
+
+ it('builds a canonical season from a partial input', () => {
+ const s = sanitizeSeason({ title: 'Diaspora', number: 2 });
+ expect(s.id).toMatch(/^sea-/);
+ expect(s.title).toBe('Diaspora');
+ expect(s.number).toBe(2);
+ expect(s.status).toBe('draft');
+ expect(s.episodeCountTarget).toBe(0);
+ expect(s.themes).toEqual([]);
+ expect(s.createdAt).toMatch(/T/);
+ // createdAt + updatedAt are two separate nowIso() calls so they may differ
+ // by ms within the same tick. Just confirm both are present + ordered.
+ expect(s.updatedAt >= s.createdAt).toBe(true);
+ });
+
+ it('preserves an existing sea- id', () => {
+ const s = sanitizeSeason({ id: 'sea-existing', title: 'x' });
+ expect(s.id).toBe('sea-existing');
+ });
+
+ it('regenerates a non-conforming id', () => {
+ uuidCounter = 0;
+ const s = sanitizeSeason({ id: 'not-a-season-id', title: 'x' });
+ expect(s.id).toMatch(/^sea-uuid-/);
+ });
+
+ it('clamps numeric fields to caps', () => {
+ const s = sanitizeSeason({
+ title: 'x',
+ number: ARC_LIMITS.SEASON_NUMBER_MAX + 99,
+ episodeCountTarget: ARC_LIMITS.SEASON_EPISODE_COUNT_MAX + 999,
+ });
+ expect(s.number).toBe(ARC_LIMITS.SEASON_NUMBER_MAX);
+ expect(s.episodeCountTarget).toBe(ARC_LIMITS.SEASON_EPISODE_COUNT_MAX);
+ });
+
+ it('refreshes timestamps when preserveTimestamps=false', async () => {
+ const original = sanitizeSeason({ title: 'x', createdAt: '2020-01-01T00:00:00.000Z', updatedAt: '2020-01-01T00:00:00.000Z' });
+ // Tick the clock forward so the new updatedAt is strictly greater
+ await new Promise((r) => setTimeout(r, 5));
+ const next = sanitizeSeason({ ...original, title: 'y' }, { preserveTimestamps: false });
+ expect(next.createdAt).not.toBe(original.createdAt); // both flipped
+ expect(next.updatedAt > original.updatedAt).toBe(true);
+ });
+});
+
+describe('storyArc — sanitizeSeasonList', () => {
+ it('returns [] for non-array input', () => {
+ expect(sanitizeSeasonList(null)).toEqual([]);
+ expect(sanitizeSeasonList({})).toEqual([]);
+ expect(sanitizeSeasonList('s1,s2')).toEqual([]);
+ });
+
+ it('drops rejected entries and sorts by number ascending', () => {
+ const out = sanitizeSeasonList([
+ { title: 'A', number: 3 },
+ { title: '' }, // dropped
+ { title: 'B', number: 1 },
+ { title: 'C', number: 2 },
+ ]);
+ expect(out.map((s) => s.title)).toEqual(['B', 'C', 'A']);
+ });
+
+ it('deduplicates by id (last write wins)', () => {
+ const out = sanitizeSeasonList([
+ { id: 'sea-dup', title: 'first', number: 1 },
+ { id: 'sea-dup', title: 'second', number: 1 },
+ ]);
+ expect(out).toHaveLength(1);
+ expect(out[0].title).toBe('second');
+ });
+
+ it('caps at SEASONS_PER_SERIES_MAX', () => {
+ const many = Array.from({ length: ARC_LIMITS.SEASONS_PER_SERIES_MAX + 5 }, (_, i) => ({ title: `s${i}`, number: i + 1 }));
+ expect(sanitizeSeasonList(many)).toHaveLength(ARC_LIMITS.SEASONS_PER_SERIES_MAX);
+ });
+});
+
+describe('storyArc — buildSeason', () => {
+ it('always produces a sea- prefixed id and fresh timestamps', () => {
+ uuidCounter = 100;
+ const s = buildSeason({ title: 'Pilot', number: 1 });
+ expect(s.id).toMatch(/^sea-uuid-/);
+ expect(s.createdAt).toBe(s.updatedAt);
+ });
+
+ it('returns null when the input has no identifying content', () => {
+ expect(buildSeason({})).toBe(null);
+ expect(buildSeason({ logline: 'just a logline' })).toBe(null);
+ });
+});
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index dca8864089..f2bbfcc6d9 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -33,6 +33,7 @@ import {
} from '../lib/validation.js';
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 { generateStage } from '../services/pipeline/textStages.js';
import * as autoRunner from '../services/pipeline/autoRunner.js';
import { enqueueVisualImage } from '../services/pipeline/visualStages.js';
@@ -40,6 +41,7 @@ import { startEpisodeVideoForIssue, ERR_NO_STORYBOARDS } from '../services/pipel
import { ASPECT_RATIOS, QUALITIES } from '../lib/creativeDirectorPresets.js';
import { extractScenes, SOURCE_KIND } from '../lib/sceneExtractor.js';
import { BIBLE_KIND } from '../lib/storyBible.js';
+import { ARC_LIMITS, ARC_STATUSES, SEASON_STATUSES } from '../lib/storyArc.js';
const router = Router();
@@ -48,6 +50,9 @@ const SERVICE_ERROR_STATUS = {
[seriesSvc.ERR_VALIDATION]: 400,
[issuesSvc.ERR_NOT_FOUND]: 404,
[issuesSvc.ERR_VALIDATION]: 400,
+ [seasonsSvc.ERR_NOT_FOUND]: 404,
+ [seasonsSvc.ERR_VALIDATION]: 400,
+ [seasonsSvc.ERR_REASSIGN_TARGET]: 400,
[ERR_NO_STORYBOARDS]: 400,
};
@@ -87,6 +92,31 @@ const objectSchema = objectBibleCreateSchema.extend({
id: z.string().trim().max(80).optional(),
}).passthrough();
+// Arc + Season — phase 2 of Story Arc Planning. The arc lives on the series
+// record itself; seasons get their own resource so the route layer can take
+// per-record CRUD without forcing the caller to PATCH the whole series.
+const arcSchema = z.object({
+ logline: z.string().trim().max(ARC_LIMITS.LOGLINE_MAX).optional().default(''),
+ summary: z.string().trim().max(ARC_LIMITS.SUMMARY_MAX).optional().default(''),
+ protagonistArc: z.string().trim().max(ARC_LIMITS.PROTAGONIST_ARC_MAX).optional().default(''),
+ themes: z.array(z.string().trim().min(1).max(ARC_LIMITS.THEME_MAX))
+ .max(ARC_LIMITS.THEMES_PER_ARC_MAX).optional(),
+ status: z.enum(ARC_STATUSES).optional(),
+});
+
+const seasonSchema = z.object({
+ id: z.string().trim().min(1).max(64).optional(),
+ number: z.number().int().min(0).max(ARC_LIMITS.SEASON_NUMBER_MAX).optional(),
+ title: z.string().trim().max(ARC_LIMITS.SEASON_TITLE_MAX).optional(),
+ logline: z.string().trim().max(ARC_LIMITS.SEASON_LOGLINE_MAX).optional(),
+ synopsis: z.string().trim().max(ARC_LIMITS.SEASON_SYNOPSIS_MAX).optional(),
+ episodeCountTarget: z.number().int().min(0).max(ARC_LIMITS.SEASON_EPISODE_COUNT_MAX).optional(),
+ themes: z.array(z.string().trim().min(1).max(ARC_LIMITS.THEME_MAX))
+ .max(ARC_LIMITS.THEMES_PER_ARC_MAX).optional(),
+ endingHook: z.string().trim().max(ARC_LIMITS.SEASON_ENDING_HOOK_MAX).optional(),
+ status: z.enum(SEASON_STATUSES).optional(),
+}).passthrough();
+
const seriesCreateSchema = z.object({
name: z.string().trim().min(1).max(seriesSvc.NAME_MAX),
logline: z.string().trim().max(seriesSvc.LOGLINE_MAX).optional().default(''),
@@ -96,6 +126,8 @@ const seriesCreateSchema = z.object({
characters: z.array(characterSchema).max(seriesSvc.BIBLE_ENTRIES_PER_SERIES_MAX).optional(),
settings: z.array(settingSchema).max(seriesSvc.BIBLE_ENTRIES_PER_SERIES_MAX).optional(),
objects: z.array(objectSchema).max(seriesSvc.BIBLE_ENTRIES_PER_SERIES_MAX).optional(),
+ arc: arcSchema.nullable().optional(),
+ seasons: z.array(seasonSchema).max(ARC_LIMITS.SEASONS_PER_SERIES_MAX).optional(),
styleNotes: z.string().trim().max(seriesSvc.STYLE_NOTES_MAX).optional().default(''),
targetFormat: z.enum(seriesSvc.TARGET_FORMATS).optional(),
issueCountTarget: z.number().int().min(0).max(seriesSvc.ISSUE_COUNT_TARGET_MAX).optional(),
@@ -110,11 +142,27 @@ const seriesPatchSchema = z.object({
characters: z.array(characterSchema).max(seriesSvc.BIBLE_ENTRIES_PER_SERIES_MAX).optional(),
settings: z.array(settingSchema).max(seriesSvc.BIBLE_ENTRIES_PER_SERIES_MAX).optional(),
objects: z.array(objectSchema).max(seriesSvc.BIBLE_ENTRIES_PER_SERIES_MAX).optional(),
+ arc: arcSchema.nullable().optional(),
+ seasons: z.array(seasonSchema).max(ARC_LIMITS.SEASONS_PER_SERIES_MAX).optional(),
styleNotes: z.string().trim().max(seriesSvc.STYLE_NOTES_MAX).optional(),
targetFormat: z.enum(seriesSvc.TARGET_FORMATS).optional(),
issueCountTarget: z.number().int().min(0).max(seriesSvc.ISSUE_COUNT_TARGET_MAX).optional(),
}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });
+// Season-resource schemas: dedicated CRUD on a sibling resource so the
+// client can edit one season without resending the whole series patch.
+const seasonCreateSchema = seasonSchema.refine(
+ (p) => (p.title && p.title.trim().length > 0) || (Number.isFinite(p.number) && p.number > 0),
+ { message: 'season requires a non-empty title or a number > 0' },
+);
+const seasonPatchSchema = seasonSchema.refine(
+ (p) => Object.keys(p).length > 0,
+ { message: 'patch must include at least one field' },
+);
+const seasonDeleteSchema = z.object({
+ reassignTo: z.string().trim().min(1).max(64).nullable().optional(),
+});
+
// ---- Issue schemas ----
const issueCreateSchema = z.object({
@@ -146,6 +194,10 @@ const issuePatchSchema = z.object({
title: z.string().trim().min(1).max(issuesSvc.TITLE_MAX).optional(),
number: z.number().int().min(1).max(9999).optional(),
status: z.enum(issuesSvc.ISSUE_STATUSES).optional(),
+ // Phase 2 of Story Arc Planning: optional pointer back to a season +
+ // ordinal within that season. `null` clears the assignment.
+ seasonId: z.string().trim().min(1).max(issuesSvc.SEASON_ID_MAX).nullable().optional(),
+ arcPosition: z.number().int().min(0).max(issuesSvc.ARC_POSITION_MAX).nullable().optional(),
// Use visualStageInputSchema as the union arm so visual-stage payloads keep
// their `scenes` / `pages` / `cdProjectId` / `videoPath` fields. The schema
// is a superset of stageInputSchema (those four are optional additions), so
@@ -296,6 +348,44 @@ router.post('/series/:id/issues', asyncHandler(async (req, res) => {
res.status(201).json(created);
}));
+// =====================
+// Season routes — Phase 2 of Story Arc Planning. Seasons live inside
+// `series.seasons[]` but get their own resource so a single-season edit
+// doesn't have to re-PATCH the entire series record.
+// =====================
+
+router.get('/series/:id/seasons', asyncHandler(async (req, res) => {
+ const seasons = await seasonsSvc.listSeasons(req.params.id)
+ .catch((err) => { throw mapServiceError(err); });
+ res.json(seasons);
+}));
+
+router.post('/series/:id/seasons', asyncHandler(async (req, res) => {
+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const body = validateRequest(seasonCreateSchema, req.body ?? {});
+ const created = await seasonsSvc.createSeason(req.params.id, body)
+ .catch((err) => { throw mapServiceError(err); });
+ res.status(201).json(created);
+}));
+
+router.patch('/series/:id/seasons/:seasonId', asyncHandler(async (req, res) => {
+ const body = validateRequest(seasonPatchSchema, req.body ?? {});
+ const updated = await seasonsSvc.updateSeason(req.params.id, req.params.seasonId, body)
+ .catch((err) => { throw mapServiceError(err); });
+ res.json(updated);
+}));
+
+router.delete('/series/:id/seasons/:seasonId', asyncHandler(async (req, res) => {
+ // Reassign target arrives via the request body so HTTP DELETE stays valid;
+ // a query-param fallback would invite the same content twice in different
+ // shapes. Body is optional — omitting it un-groups every child issue.
+ const body = validateRequest(seasonDeleteSchema, req.body ?? {});
+ const result = await seasonsSvc.deleteSeason(req.params.id, req.params.seasonId, {
+ reassignTo: body.reassignTo ?? null,
+ }).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 50feeb4875..8e26b8b9a9 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -460,4 +460,129 @@ describe('pipeline routes', () => {
expect(r.body.stage.scenes[0].description).toBe('fresh scene');
spy.mockRestore();
});
+
+ // -----------------------
+ // Season routes (Phase 2 of Story Arc Planning)
+ // -----------------------
+
+ it('GET /series/:id/seasons returns [] for a fresh series', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const r = await request(app).get(`/api/pipeline/series/${ser.body.id}/seasons`);
+ expect(r.status).toBe(200);
+ expect(r.body).toEqual([]);
+ });
+
+ it('GET /series/:id/seasons 404s for unknown series', async () => {
+ const app = makeApp();
+ const r = await request(app).get('/api/pipeline/series/ser-nope/seasons');
+ expect(r.status).toBe(404);
+ });
+
+ it('POST /series/:id/seasons creates a season and auto-numbers it', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const r1 = await request(app).post(`/api/pipeline/series/${ser.body.id}/seasons`).send({ title: 'Pilot' });
+ expect(r1.status).toBe(201);
+ expect(r1.body.id).toMatch(/^sea-/);
+ expect(r1.body.number).toBe(1);
+ const r2 = await request(app).post(`/api/pipeline/series/${ser.body.id}/seasons`).send({ title: 'Aftermath' });
+ expect(r2.body.number).toBe(2);
+ });
+
+ it('POST /series/:id/seasons rejects entry with neither title nor number', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const r = await request(app).post(`/api/pipeline/series/${ser.body.id}/seasons`).send({});
+ expect(r.status).toBe(400);
+ });
+
+ it('PATCH /series/:id/seasons/:seasonId updates fields', 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' });
+ const r = await request(app)
+ .patch(`/api/pipeline/series/${ser.body.id}/seasons/${sea.body.id}`)
+ .send({ logline: 'L1', status: 'verified' });
+ expect(r.status).toBe(200);
+ expect(r.body.logline).toBe('L1');
+ expect(r.body.status).toBe('verified');
+ expect(r.body.title).toBe('Pilot');
+ });
+
+ it('PATCH /series/:id/seasons/:seasonId 404s for unknown season', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const r = await request(app)
+ .patch(`/api/pipeline/series/${ser.body.id}/seasons/sea-nope`)
+ .send({ title: 'x' });
+ expect(r.status).toBe(404);
+ });
+
+ it('DELETE /series/:id/seasons/:seasonId un-groups child issues by default', 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' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'Ep 1' });
+ await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({ seasonId: sea.body.id, arcPosition: 1 });
+
+ const r = await request(app).delete(`/api/pipeline/series/${ser.body.id}/seasons/${sea.body.id}`).send({});
+ expect(r.status).toBe(200);
+ expect(r.body).toMatchObject({ id: sea.body.id, reassignedIssueCount: 1, reassignedTo: null });
+
+ const reloaded = await request(app).get(`/api/pipeline/issues/${iss.body.id}`);
+ expect(reloaded.body.seasonId).toBe(null);
+ });
+
+ it('DELETE /series/:id/seasons/:seasonId reassigns child issues to reassignTo sibling', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const a = await request(app).post(`/api/pipeline/series/${ser.body.id}/seasons`).send({ title: 'Pilot' });
+ const b = await request(app).post(`/api/pipeline/series/${ser.body.id}/seasons`).send({ title: 'Hiatus' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'Ep 1' });
+ await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({ seasonId: a.body.id });
+
+ const r = await request(app).delete(`/api/pipeline/series/${ser.body.id}/seasons/${a.body.id}`)
+ .send({ reassignTo: b.body.id });
+ expect(r.status).toBe(200);
+ expect(r.body.reassignedTo).toBe(b.body.id);
+
+ const reloaded = await request(app).get(`/api/pipeline/issues/${iss.body.id}`);
+ expect(reloaded.body.seasonId).toBe(b.body.id);
+ });
+
+ it('DELETE /series/:id/seasons/:seasonId 400s when reassignTo points at non-existent sibling', 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' });
+ const r = await request(app).delete(`/api/pipeline/series/${ser.body.id}/seasons/${sea.body.id}`)
+ .send({ reassignTo: 'sea-ghost' });
+ expect(r.status).toBe(400);
+ });
+
+ it('PATCH /issues/:id accepts seasonId + arcPosition', 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' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'Ep 1' });
+ const r = await request(app).patch(`/api/pipeline/issues/${iss.body.id}`)
+ .send({ seasonId: sea.body.id, arcPosition: 3 });
+ expect(r.status).toBe(200);
+ expect(r.body.seasonId).toBe(sea.body.id);
+ expect(r.body.arcPosition).toBe(3);
+ });
+
+ it('PATCH /series/:id accepts arc payload', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const r = await request(app).patch(`/api/pipeline/series/${ser.body.id}`).send({
+ arc: { logline: 'Big-picture pitch', themes: ['legacy', 'betrayal'], status: 'draft' },
+ });
+ expect(r.status).toBe(200);
+ expect(r.body.arc).toMatchObject({
+ logline: 'Big-picture pitch',
+ themes: ['legacy', 'betrayal'],
+ status: 'draft',
+ });
+ });
});
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index 1da9f276b3..e0fd6a30c6 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -31,6 +31,10 @@ const makeErr = (message, code) => Object.assign(new Error(message), { code });
export const TITLE_MAX = 300;
export const SERIES_ID_MAX = 64;
+export const SEASON_ID_MAX = 64;
+// Issues fall back to position 0 when un-numbered; the cap keeps a runaway
+// LLM payload from inflating the field unbounded.
+export const ARC_POSITION_MAX = 9999;
export const STAGE_INPUT_MAX = 200_000; // ~200kB — fits a long prose draft
export const STAGE_OUTPUT_MAX = 400_000; // ~400kB — fits a long comic script
export const STAGE_NOTES_MAX = 4000;
@@ -111,12 +115,23 @@ const sanitizeIssue = (raw) => {
const status = ISSUE_STATUSES.includes(raw.status) ? raw.status : 'draft';
const createdAt = isStr(raw.createdAt) ? raw.createdAt : new Date().toISOString();
const updatedAt = isStr(raw.updatedAt) ? raw.updatedAt : createdAt;
+ // Phase 2 of Story Arc Planning: optional pointer back into the parent
+ // series' arc tree. `null` is the back-compat default — every pre-existing
+ // issue stays un-grouped until the user (or LLM-arc-generation) assigns it.
+ const seasonId = isStr(raw.seasonId) && raw.seasonId
+ ? trimTo(raw.seasonId, SEASON_ID_MAX)
+ : null;
+ const arcPosition = Number.isFinite(raw.arcPosition)
+ ? Math.max(0, Math.min(ARC_POSITION_MAX, Math.floor(raw.arcPosition)))
+ : null;
return {
id: raw.id,
seriesId: trimTo(raw.seriesId, SERIES_ID_MAX),
number,
title,
status,
+ seasonId,
+ arcPosition,
stages: sanitizeStages(raw.stages || {}),
createdAt,
updatedAt,
@@ -195,6 +210,8 @@ export async function updateIssue(id, patch = {}) {
...('title' in patch ? { title: patch.title } : {}),
...('number' in patch ? { number: patch.number } : {}),
...('status' in patch ? { status: patch.status } : {}),
+ ...('seasonId' in patch ? { seasonId: patch.seasonId } : {}),
+ ...('arcPosition' in patch ? { arcPosition: patch.arcPosition } : {}),
stages: mergedStages,
updatedAt: new Date().toISOString(),
});
diff --git a/server/services/pipeline/seasons.js b/server/services/pipeline/seasons.js
new file mode 100644
index 0000000000..6730d0f106
--- /dev/null
+++ b/server/services/pipeline/seasons.js
@@ -0,0 +1,122 @@
+/**
+ * Pipeline — Seasons Service
+ *
+ * Seasons live inside the series record (`series.seasons[]`) — they are not a
+ * separate file. This module is a thin facade over `series.js` that provides
+ * the CRUD vocabulary the route layer expects (list / create / update /
+ * delete) and handles the cross-record concern that delete entails:
+ * re-pointing every child issue's `seasonId` so a deleted season doesn't
+ * leave orphan references.
+ *
+ * Phase 2 of the Story Arc Planning initiative. See PLAN.md for the full spec.
+ */
+
+import { ARC_LIMITS, buildSeason, sanitizeSeason } from '../../lib/storyArc.js';
+import * as seriesSvc from './series.js';
+import * as issuesSvc from './issues.js';
+
+export const ERR_NOT_FOUND = 'PIPELINE_SEASON_NOT_FOUND';
+export const ERR_VALIDATION = 'PIPELINE_SEASON_VALIDATION';
+export const ERR_REASSIGN_TARGET = 'PIPELINE_SEASON_REASSIGN_TARGET_INVALID';
+const makeErr = (message, code) => Object.assign(new Error(message), { code });
+
+const isStr = (v) => typeof v === 'string';
+
+export async function listSeasons(seriesId) {
+ const series = await seriesSvc.getSeries(seriesId);
+ return series.seasons || [];
+}
+
+export async function getSeason(seriesId, seasonId) {
+ const seasons = await listSeasons(seriesId);
+ const found = seasons.find((s) => s.id === seasonId);
+ if (!found) throw makeErr(`Season not found: ${seasonId}`, ERR_NOT_FOUND);
+ return found;
+}
+
+export async function createSeason(seriesId, input = {}) {
+ const next = buildSeason(input);
+ if (!next) {
+ throw makeErr('Season requires a title or a number > 0', ERR_VALIDATION);
+ }
+ const series = await seriesSvc.getSeries(seriesId);
+ const existing = series.seasons || [];
+ if (existing.length >= ARC_LIMITS.SEASONS_PER_SERIES_MAX) {
+ throw makeErr(`Series already has ${ARC_LIMITS.SEASONS_PER_SERIES_MAX} seasons (max)`, ERR_VALIDATION);
+ }
+ // If the user didn't pick a number, default to last + 1 so the canonical
+ // ordering reads naturally. Falls back to 1 for the first season.
+ if (!next.number) {
+ const peakNumber = existing.reduce((m, s) => Math.max(m, s.number || 0), 0);
+ next.number = peakNumber + 1;
+ }
+ const merged = [...existing, next];
+ const updated = await seriesSvc.updateSeries(seriesId, { seasons: merged });
+ // Return the season we built so the caller doesn't have to re-find it; the
+ // sort/dedup in `sanitizeSeasonList` may have re-ordered the list, but the
+ // id stays stable.
+ return updated.seasons.find((s) => s.id === next.id);
+}
+
+export async function updateSeason(seriesId, seasonId, patch = {}) {
+ const series = await seriesSvc.getSeries(seriesId);
+ const seasons = series.seasons || [];
+ const cur = seasons.find((s) => s.id === seasonId);
+ if (!cur) throw makeErr(`Season not found: ${seasonId}`, ERR_NOT_FOUND);
+ // Preserve `createdAt` and force a fresh `updatedAt` by overwriting them
+ // directly in the sanitizer input — the default `preserveTimestamps: true`
+ // path then just reads them through cleanly.
+ const next = sanitizeSeason({
+ ...cur,
+ ...patch,
+ id: cur.id,
+ createdAt: cur.createdAt,
+ updatedAt: new Date().toISOString(),
+ });
+ if (!next) throw makeErr('Season requires a title or a number > 0', ERR_VALIDATION);
+ // Re-write the whole seasons array — the series sanitizer re-sorts by
+ // `number` ascending so a number change moves the season automatically.
+ const merged = seasons.map((s) => (s.id === seasonId ? next : s));
+ const updated = await seriesSvc.updateSeries(seriesId, { seasons: merged });
+ return updated.seasons.find((s) => s.id === seasonId);
+}
+
+/**
+ * Delete a season. Every issue whose `seasonId` matched the deleted season
+ * gets reassigned to `reassignTo` (a sibling season id or `null` for
+ * un-grouped). Passing `reassignTo` for a season that doesn't exist on the
+ * series rejects with `ERR_REASSIGN_TARGET` before mutating anything.
+ */
+export async function deleteSeason(seriesId, seasonId, { reassignTo = null } = {}) {
+ const series = await seriesSvc.getSeries(seriesId);
+ const seasons = series.seasons || [];
+ const cur = seasons.find((s) => s.id === seasonId);
+ if (!cur) throw makeErr(`Season not found: ${seasonId}`, ERR_NOT_FOUND);
+ // Validate the reassign target up front. Passing a non-existent sibling id
+ // here is a user-side bug (stale state, copy-paste error) — surfacing it
+ // before any disk writes means the caller can retry cleanly.
+ if (reassignTo != null) {
+ if (!isStr(reassignTo)) {
+ throw makeErr('reassignTo must be a season id or null', ERR_REASSIGN_TARGET);
+ }
+ if (reassignTo === seasonId) {
+ throw makeErr('reassignTo cannot be the season being deleted', ERR_REASSIGN_TARGET);
+ }
+ const target = seasons.find((s) => s.id === reassignTo);
+ if (!target) {
+ throw makeErr(`reassignTo season not found: ${reassignTo}`, ERR_REASSIGN_TARGET);
+ }
+ }
+ // Re-point child issues first so a mid-write crash doesn't leave them
+ // dangling against a deleted season id. `updateIssue` is per-issue (and
+ // each call writes the file), so we batch-iterate; the data set is small
+ // (issues per series ~< 100) so the cost is bounded.
+ const childIssues = await issuesSvc.listIssues({ seriesId });
+ const reassignList = childIssues.filter((iss) => iss.seasonId === seasonId);
+ for (const iss of reassignList) {
+ await issuesSvc.updateIssue(iss.id, { seasonId: reassignTo });
+ }
+ const merged = seasons.filter((s) => s.id !== seasonId);
+ await seriesSvc.updateSeries(seriesId, { seasons: merged });
+ return { id: seasonId, reassignedIssueCount: reassignList.length, reassignedTo: reassignTo };
+}
diff --git a/server/services/pipeline/seasons.test.js b/server/services/pipeline/seasons.test.js
new file mode 100644
index 0000000000..a15e02d738
--- /dev/null
+++ b/server/services/pipeline/seasons.test.js
@@ -0,0 +1,148 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const fileStore = new Map();
+
+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}` };
+});
+
+const seriesSvc = await import('./series.js');
+const issuesSvc = await import('./issues.js');
+const svc = await import('./seasons.js');
+
+async function setupSeries() {
+ return seriesSvc.createSeries({ name: 'Salt Run', logline: 'L' });
+}
+
+describe('pipeline seasons service', () => {
+ beforeEach(() => {
+ fileStore.clear();
+ uuidCounter = 0;
+ });
+
+ it('listSeasons returns [] for a fresh series', async () => {
+ const s = await setupSeries();
+ expect(await svc.listSeasons(s.id)).toEqual([]);
+ });
+
+ it('createSeason inserts and assigns a default number if absent', async () => {
+ const s = await setupSeries();
+ const a = await svc.createSeason(s.id, { title: 'Pilot' });
+ expect(a.id).toMatch(/^sea-/);
+ expect(a.number).toBe(1);
+ const b = await svc.createSeason(s.id, { title: 'Aftermath' });
+ expect(b.number).toBe(2);
+ });
+
+ it('createSeason preserves explicit number', async () => {
+ const s = await setupSeries();
+ const a = await svc.createSeason(s.id, { title: 'Mid-season', number: 5 });
+ expect(a.number).toBe(5);
+ const b = await svc.createSeason(s.id, { title: 'Finale' });
+ // Auto-numbers off the peak — 6, not 2.
+ expect(b.number).toBe(6);
+ });
+
+ it('createSeason rejects when title and number are both missing', async () => {
+ const s = await setupSeries();
+ await expect(svc.createSeason(s.id, {})).rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+
+ it('createSeason rejects past SEASONS_PER_SERIES_MAX', async () => {
+ const s = await setupSeries();
+ const { ARC_LIMITS } = await import('../../lib/storyArc.js');
+ for (let i = 1; i <= ARC_LIMITS.SEASONS_PER_SERIES_MAX; i++) {
+ await svc.createSeason(s.id, { title: `s${i}` });
+ }
+ await expect(svc.createSeason(s.id, { title: 'overflow' }))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+
+ it('updateSeason patches fields and refreshes updatedAt', async () => {
+ const s = await setupSeries();
+ const a = await svc.createSeason(s.id, { title: 'Pilot' });
+ await new Promise((r) => setTimeout(r, 5));
+ const patched = await svc.updateSeason(s.id, a.id, { logline: 'New logline', status: 'verified' });
+ expect(patched.logline).toBe('New logline');
+ expect(patched.status).toBe('verified');
+ expect(patched.title).toBe('Pilot'); // unchanged
+ expect(patched.updatedAt > a.updatedAt).toBe(true);
+ expect(patched.createdAt).toBe(a.createdAt);
+ });
+
+ it('updateSeason re-sorts when number changes', async () => {
+ const s = await setupSeries();
+ const a = await svc.createSeason(s.id, { title: 'A', number: 1 });
+ const b = await svc.createSeason(s.id, { title: 'B', number: 2 });
+ await svc.updateSeason(s.id, a.id, { number: 3 });
+ const seasons = await svc.listSeasons(s.id);
+ expect(seasons.map((x) => x.title)).toEqual(['B', 'A']);
+ });
+
+ it('updateSeason throws ERR_NOT_FOUND for unknown season id', async () => {
+ const s = await setupSeries();
+ await expect(svc.updateSeason(s.id, 'sea-nope', { title: 'x' }))
+ .rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });
+ });
+
+ it('deleteSeason removes the season + un-groups child issues by default', async () => {
+ const s = await setupSeries();
+ const sea = await svc.createSeason(s.id, { title: 'Pilot' });
+ const iss = await issuesSvc.createIssue({ seriesId: s.id, title: 'Ep 1' });
+ await issuesSvc.updateIssue(iss.id, { seasonId: sea.id, arcPosition: 1 });
+
+ const result = await svc.deleteSeason(s.id, sea.id);
+ expect(result).toEqual({ id: sea.id, reassignedIssueCount: 1, reassignedTo: null });
+
+ const remainingSeasons = await svc.listSeasons(s.id);
+ expect(remainingSeasons).toEqual([]);
+
+ const reloaded = await issuesSvc.getIssue(iss.id);
+ expect(reloaded.seasonId).toBe(null);
+ expect(reloaded.arcPosition).toBe(1); // arcPosition unchanged — only seasonId clears
+ });
+
+ it('deleteSeason reassigns child issues to reassignTo', async () => {
+ const s = await setupSeries();
+ const a = await svc.createSeason(s.id, { title: 'Pilot' });
+ const b = await svc.createSeason(s.id, { title: 'Hiatus' });
+ const iss = await issuesSvc.createIssue({ seriesId: s.id, title: 'Ep 1' });
+ await issuesSvc.updateIssue(iss.id, { seasonId: a.id });
+
+ await svc.deleteSeason(s.id, a.id, { reassignTo: b.id });
+ const reloaded = await issuesSvc.getIssue(iss.id);
+ expect(reloaded.seasonId).toBe(b.id);
+ });
+
+ it('deleteSeason rejects reassignTo pointing at non-existent sibling', async () => {
+ const s = await setupSeries();
+ const a = await svc.createSeason(s.id, { title: 'Pilot' });
+ await expect(svc.deleteSeason(s.id, a.id, { reassignTo: 'sea-ghost' }))
+ .rejects.toMatchObject({ code: svc.ERR_REASSIGN_TARGET });
+ // No mutation should have happened — season still there.
+ const seasons = await svc.listSeasons(s.id);
+ expect(seasons.map((x) => x.id)).toEqual([a.id]);
+ });
+
+ it('deleteSeason rejects reassignTo pointing at itself', async () => {
+ const s = await setupSeries();
+ const a = await svc.createSeason(s.id, { title: 'Pilot' });
+ await expect(svc.deleteSeason(s.id, a.id, { reassignTo: a.id }))
+ .rejects.toMatchObject({ code: svc.ERR_REASSIGN_TARGET });
+ });
+
+ it('deleteSeason throws ERR_NOT_FOUND for unknown season id', async () => {
+ const s = await setupSeries();
+ await expect(svc.deleteSeason(s.id, 'sea-nope'))
+ .rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });
+ });
+});
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index a9a8d451a6..b028ec2790 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -18,6 +18,7 @@ import {
BIBLE_LIMITS, BIBLE_KIND, BIBLE_FIELD,
isStr, trimTo,
} from '../../lib/storyBible.js';
+import { sanitizeArc, sanitizeSeasonList } from '../../lib/storyArc.js';
import { extractBible } from '../../lib/bibleExtractor.js';
// Lazy resolution — PATHS.data may not be available at module-load time
@@ -68,6 +69,11 @@ const sanitizeSeries = (raw) => {
characters: sanitizeBibleList(raw.characters, BIBLE_KIND.CHARACTER),
settings: sanitizeBibleList(raw.settings, BIBLE_KIND.SETTING),
objects: sanitizeBibleList(raw.objects, BIBLE_KIND.OBJECT),
+ // Phase 2 of Story Arc Planning: optional multi-season story spine + the
+ // ordered season list. Both default to empty so existing series.json
+ // files migrate forward without a writer pass — first save backfills.
+ arc: sanitizeArc(raw.arc),
+ seasons: sanitizeSeasonList(raw.seasons),
styleNotes: trimTo(raw.styleNotes, STYLE_NOTES_MAX),
targetFormat,
issueCountTarget,
@@ -114,6 +120,8 @@ export async function createSeries(input = {}) {
characters: input.characters || [],
settings: input.settings || [],
objects: input.objects || [],
+ arc: input.arc || null,
+ seasons: input.seasons || [],
styleNotes: input.styleNotes || '',
targetFormat: input.targetFormat || 'comic+tv',
issueCountTarget: input.issueCountTarget || 0,
@@ -140,6 +148,8 @@ export async function updateSeries(id, patch = {}) {
...('characters' in patch ? { characters: patch.characters } : {}),
...('settings' in patch ? { settings: patch.settings } : {}),
...('objects' in patch ? { objects: patch.objects } : {}),
+ ...('arc' in patch ? { arc: patch.arc } : {}),
+ ...('seasons' in patch ? { seasons: patch.seasons } : {}),
...('styleNotes' in patch ? { styleNotes: patch.styleNotes } : {}),
...('targetFormat' in patch ? { targetFormat: patch.targetFormat } : {}),
...('issueCountTarget' in patch ? { issueCountTarget: patch.issueCountTarget } : {}),