Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Merge remote-tracking branch 'origin/main' into better/architecture
Adam Eivya91b3036de81
diff --cc server/routes/pipeline/arcs.jsindex 0000000000,a5b5a70fae..9393afe02amode 000000,100644..100644--- a/server/routes/pipeline/arcs.js+++ b/server/routes/pipeline/arcs.js@@@ -1,0 -1,274 +1,239 @@@+ /**+ * Pipeline arc-planning routes — Phase 3 of Story Arc Planning. LLM-driven+ * passes that propose (and optionally commit) arc-level metadata, season+ * outlines, per-episode breakdowns, volume beat sheets, verification, and+ * the back-derive-from-manuscript flow.+ */++ import { Router } from 'express';+ import { z } from 'zod';+ import { asyncHandler, ServerError } from '../../lib/errorHandler.js';+ import { validateRequest } from '../../lib/validation.js';+ import * as seriesSvc from '../../services/pipeline/series.js';+ import * as arcPlanner from '../../services/pipeline/arcPlanner.js';+ import * as volumeBeatsRunner from '../../services/pipeline/volumeBeatsRunner.js';-import { extractCanonFromProse } from '../../services/universeCanon.js';-import { resolveSeriesLlmOverride } from '../../lib/seriesLlmOverride.js';-import { mapServiceError, providerOverrideShape, countExtractedCanon } from './shared.js';++import { mapServiceError, providerOverrideShape } from './shared.js';++ const router = Router();++ // The first two arc passes also accept `commit: true` to persist the LLM+ // output (skipping the preview/confirm step).+ const arcGenerateSchema = z.object({ ...providerOverrideShape, commit: z.boolean().optional() });+ const seasonEpisodesGenerateSchema = z.object({ ...providerOverrideShape, commit: z.boolean().optional() });+ const arcVerifySchema = z.object(providerOverrideShape);+ // Volume / season verify shares the same provider/model override shape.+ const volumeVerifySchema = z.object(providerOverrideShape);++ // Volume beat-sheets bulk generator. `mode` defaults to skip-existing so a+ // rerun on a partially-expanded volume only fills empty slots; the explicit+ // 'regenerate-all' is the "blow away every beat sheet" path.+ const volumeBeatsGenerateSchema = z.object({+ ...providerOverrideShape,+ mode: z.enum(volumeBeatsRunner.VOLUME_BEATS_MODES).optional().default('skip-existing'),+ });++ // Auto-resolve verification findings. `findings` empty/omitted = re-verify+ // first then resolve everything; otherwise the LLM only addresses the+ // caller-supplied subset (per-finding "Resolve" buttons).+ const verifyFindingSchema = z.object({+ severity: z.enum(['high', 'medium', 'low']).optional(),+ location: z.string().trim().max(200).optional(),+ problem: z.string().trim().min(1).max(2000),+ suggestion: z.string().trim().max(2000).optional(),+ });+ const arcResolveSchema = z.object({+ ...providerOverrideShape,+ findings: z.array(verifyFindingSchema).max(50).optional(),+ });++ // Back-derive arc/bible/structure from the existing issue manuscripts. The+ // preview pass just needs the override shape; the commit pass carries the+ // (possibly user-edited) proposal so the LLM is NOT re-run on confirm.+ const arcDeriveSchema = z.object(providerOverrideShape);+ const arcDeriveCommitSchema = z.object({+ arc: z.object({+ logline: z.string().max(500).optional(),+ summary: z.string().max(8000).optional(),+ protagonistArc: z.string().max(8000).optional(),+ themes: z.array(z.string().max(200)).max(50).optional(),+ shape: z.string().max(80).nullable().optional(),+ }).optional(),+ bible: z.object({+ logline: z.string().max(500).optional(),+ premise: z.string().max(8000).optional(),+ issueCountTarget: z.number().int().min(0).max(9999).optional(),+ }).optional(),+ volume: z.object({+ title: z.string().max(300).optional(),+ logline: z.string().max(1000).optional(),+ synopsis: z.string().max(8000).optional(),+ }).optional(),+ issues: z.array(z.object({+ id: z.string().min(1).max(120),+ title: z.string().max(300).optional(),+ synopsis: z.string().max(8000).optional(),+ })).max(200).optional(),+ });++ // 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) {+ const cur = await seriesSvc.getSeries(req.params.id)+ .catch((err) => { throw mapServiceError(err); });+ const committed = await arcPlanner.commitSeasonsWithRemap(cur, {+ arc: result.arc,+ seasons: result.seasons,+ }).catch((err) => { throw mapServiceError(err); });+ series = committed.series;+ }+ 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); });++ let createdIssues = [];+ let bibleExtracted = null;+ if (body.commit) {+ // Create one issue per episode under this season. The issue sanitizer+ // already accepts `seasonId` + `arcPosition`; the shared helper owns the+ // per-episode → createIssue mapping so the Story Builder's batch path+ // mints identical issue shapes.+ // Fetch the series once and thread it through both the issue-creation+ // batch (so each createIssue's renumber pass skips a redundant read) and+ // the continuity extraction below.+ const series = await seriesSvc.getSeries(req.params.id).catch(() => null);+ createdIssues = await arcPlanner.commitEpisodesToIssues(+ req.params.id, req.params.seasonId, result.episodes, { preloadedSeries: series },+ );++ // Non-fatal: episode creation already succeeded, so a noisy extraction+ // failure must not invalidate the user's accepted breakdown. Phase B.4:+ // canon lives on the linked universe — orphan series (no universeId)+ // skip extraction.- const corpus = result.episodes- .map((ep) => `## E${ep.number} — ${ep.title}\n\n${ep.logline || ''}\n\n${ep.synopsis || ''}`.trim())- .filter(Boolean)- .join('\n\n');- if (corpus.trim() && series?.universeId) {- // Fall back to the series' configured LLM when the client doesn't pass an- // explicit override — matches the extract-canon and extract-scenes routes- // so continuity extraction honors the provider/model picked in the series- // header instead of the global active provider. A model id is- // provider-specific, so only inherit the series model when the effective- // provider is still the series provider; an override that switches- // providers without naming a model leaves it blank so the new provider's- // default resolves.- const { provider, model } = resolveSeriesLlmOverride(series, {- overrideProvider: body.providerOverride,- overrideModel: body.modelOverride,- });- // Stamp new inserts as series-extracted (autoLock + sourceSeriesId) so- // continuity-derived canon survives later AI refines and stays- // attributable to this series. Matches the pre-B.4 series-side- // extract semantics.- const extractRes = await extractCanonFromProse(series.universeId, {- corpus,- providerOverride: provider,- modelOverride: model,- parallel: true,- autoLock: true,- sourceSeriesId: series.id,- }).catch((err) => {- console.warn(`⚠️ Continuity extraction failed for season ${req.params.seasonId}: ${err.message}`);- return null;- });- if (extractRes) {- bibleExtracted = {- ...countExtractedCanon(extractRes.results),- universe: extractRes.universe,- };- }- }++ bibleExtracted = await arcPlanner.extractEpisodeCanon({++ series,++ episodes: result.episodes,++ providerOverride: body.providerOverride,++ modelOverride: body.modelOverride,++ });+ }++ res.json({+ season: result.season,+ episodes: result.episodes,+ runId: result.runId,+ providerId: result.providerId,+ model: result.model,+ committed: !!body.commit,+ createdIssues,+ bibleExtracted,+ });+ }));++ 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);+ }));++ // Per-volume verify — the deeper, narrower counterpart to /arc/verify.+ // Runs the pipeline-volume-verify prompt over a single season's issues,+ // going to beat depth when issues have beats and falling back to synopsis+ // depth otherwise so a partially-expanded volume can still be validated.+ router.post('/series/:id/seasons/:seasonId/verify', asyncHandler(async (req, res) => {+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });+ const body = validateRequest(volumeVerifySchema, req.body ?? {});+ const result = await arcPlanner.verifyVolume(req.params.id, req.params.seasonId, body)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+ }));++ // Sequential beat-sheet (idea stage) generator for every issue in a volume.+ // Runs serially so each issue's prompt sees the prior issue's freshly-written+ // beats via buildIdeaContextAugment; SSE streams per-issue progress. Pairs+ // naturally with the volume verify pass — generate-then-validate is the+ // expected workflow.+ router.post('/series/:id/seasons/:seasonId/generate-beats', asyncHandler(async (req, res) => {+ const body = validateRequest(volumeBeatsGenerateSchema, req.body ?? {});+ const result = await volumeBeatsRunner.startVolumeBeatsRun(+ req.params.id,+ req.params.seasonId,+ {+ mode: body.mode,+ providerId: body.providerOverride,+ model: body.modelOverride,+ },+ ).catch((err) => { throw mapServiceError(err); });+ res.json({+ ...result,+ sseUrl: `/api/pipeline/series/${req.params.id}/seasons/${req.params.seasonId}/generate-beats/progress`,+ });+ }));++ router.get('/series/:id/seasons/:seasonId/generate-beats/progress', (req, res) => {+ const attached = volumeBeatsRunner.attachClient(req.params.seasonId, res);+ if (!attached) {+ throw new ServerError('No active beat-sheet run for this volume', { status: 404 });+ }+ });++ router.post('/series/:id/seasons/:seasonId/generate-beats/cancel', asyncHandler(async (req, res) => {+ const canceled = volumeBeatsRunner.cancelVolumeBeatsRun(req.params.seasonId);+ res.json({ canceled });+ }));++ // Auto-resolve verification findings. Persists the LLM's patched arc + season+ // outlines in one call. Per-episode issue records are not touched.+ router.post('/series/:id/arc/resolve-issues', asyncHandler(async (req, res) => {+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });+ const body = validateRequest(arcResolveSchema, req.body ?? {});+ const result = await arcPlanner.resolveVerifyIssues(req.params.id, body)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+ }));++ // Back-derive arc + bible + single-volume restructure from the EXISTING issue+ // manuscripts ("I imported a finished graphic novel, reconstruct its spine").+ // Read-only preview the UI shows for review/edit before the commit route.+ router.post('/series/:id/arc/derive-from-manuscript', asyncHandler(async (req, res) => {+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });+ const body = validateRequest(arcDeriveSchema, req.body ?? {});+ const result = await arcPlanner.deriveFromManuscript(req.params.id, body)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+ }));++ // Apply the (possibly edited) derive preview: bible + single volume + per-issue+ // synopses. The LLM is NOT re-run — the confirmed proposal is in the body.+ router.post('/series/:id/arc/derive-from-manuscript/commit', asyncHandler(async (req, res) => {+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });+ const body = validateRequest(arcDeriveCommitSchema, req.body ?? {});+ const result = await arcPlanner.commitDerivedManuscript(req.params.id, body)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+ }));++ export default router;diff --cc server/routes/pipeline/series.jsindex 0000000000,793eee2e33..18297f6e28mode 000000,100644..100644--- a/server/routes/pipeline/series.js+++ b/server/routes/pipeline/series.js@@@ -1,0 -1,367 +1,366 @@@+ /**+ * Pipeline series routes — Series CRUD (the long-lived narrative bible),+ * duplicate detection/merge, title-logo generation, the per-series issue+ * list/create pair, and season CRUD.+ */++ import { Router } from 'express';+ import { z } from 'zod';+ import { asyncHandler, ServerError } from '../../lib/errorHandler.js';-import { validateRequest, optionalBooleanMap } from '../../lib/validation.js';++import { validateRequest, optionalBooleanMap, llmSchema } 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 { findDuplicateSeriesGroups, findSameNameSeries } from '../../services/duplicateDetection.js';+ import { mergeSeries } from '../../services/recordMerge.js';+ import { mergeFieldsWithAI } from '../../services/recordMergeAI.js';+ import { generateSeriesTitleLogo } from '../../services/pipeline/seriesTitleLogo.js';+ import {+ LENGTH_PROFILE_NAMES,+ CUSTOM_PAGE_MIN, CUSTOM_PAGE_MAX, CUSTOM_MINUTE_MIN, CUSTOM_MINUTE_MAX,+ } from '../../lib/issueLength.js';-import { llmSchema } from '../universeBuilder.js';+ import { ARC_LIMITS, ARC_STATUSES, ARC_SHAPE_IDS, SEASON_STATUSES } from '../../lib/storyArc.js';+ import { mapServiceError } from './shared.js';++ // Inline until better/code-quality lands and exports this from validation.js+ const issuesListQuerySchema = z.object({+ offset: z.preprocess((v) => (v === undefined ? 0 : Number(v)), z.number().int().min(0)).default(0),+ limit: z.preprocess((v) => (v === undefined ? 1000 : Number(v)), z.number().int().min(1).max(1000)).default(1000),+ });++ const router = Router();++ // ---- Series schemas ----+ //+ // Canon (characters / places / objects) is no longer carried on a series+ // payload — it lives on the linked universe (Phase B.4). The bible-entry+ // Zod shapes (`characterSchema` et al.) and the `BIBLE_KIND` plumbing moved+ // out of this file when the series-side canon routes were retired.++ // 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(),+ shape: z.enum(ARC_SHAPE_IDS).nullable().optional(),+ // Reader map (audience-experience roadmap). Accepted as an opaque object and+ // validated/sanitized server-side by sanitizeReaderMap (storyArc.js) — mirrors+ // how visualStageInputSchema defers artifact validation to the service. Must+ // be listed here or Zod's default key-stripping would silently drop it on any+ // arc PATCH, and updateSeries's wholesale arc replace would then wipe it.+ readerMap: z.object({}).passthrough().nullable().optional(),+ status: z.enum(ARC_STATUSES).optional(),+ });++ // Volume-cover / back-cover sub-schema — accepts the script text plus the+ // pre-split legacy fields. Render-slot details (`proofImage`, `finalImage`)+ // arrive only from the render route's PATCH path, which builds them+ // server-side; PATCHes of the season metadata only carry the user-editable+ // `script`. `.passthrough()` keeps the door open for a "save full series"+ // round-trip echoing back server-built render fields (proofImage /+ // finalImage) without 400'ing — the parent seasonSchema is already+ // passthrough for the same reason.+ const seasonCoverSchema = z.object({+ script: z.string().max(8000).optional(),+ imageJobId: z.string().trim().max(200).nullable().optional(),+ prompt: z.string().max(16_000).nullable().optional(),+ }).passthrough();++ 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(),+ cover: seasonCoverSchema.nullable().optional(),+ backCover: seasonCoverSchema.nullable().optional(),+ status: z.enum(SEASON_STATUSES).optional(),+ // Per-season editorial lock. Enforced by `seasonsSvc.updateSeason` (refuses+ // content patches while locked) and `arcPlanner.generateSeasonEpisodes` /+ // `issuesSvc.bulkReassignSeason` / `seasonsSvc.deleteSeason` (refuse on+ // locked seasons). The sibling arc-level lock lives on `series.locked.arc`.+ locked: z.boolean().optional(),+ }).passthrough();++ // `.passthrough` keeps the door open for future per-season locks without a+ // schema bump — the series sanitizer is the source of truth. `arcFields`+ // holds the per-field arc locks (logline / summary / themes / etc.) that+ // `commitSeasonsWithRemap` honors when rewriting `series.arc`.+ const seriesLockedSchema = z.object({+ ...optionalBooleanMap(seriesSvc.LOCKABLE_STAGES),+ arcFields: z.object(optionalBooleanMap(seriesSvc.ARC_LOCKABLE_FIELDS)).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(''),+ premise: z.string().trim().max(seriesSvc.PREMISE_MAX).optional().default(''),+ // Series in PortOS are expected to be linked to a universe — canon+ // (characters, places, objects, style) lives on the universe and an+ // orphan series has nothing to render against. The UI's create form+ // enforces this; the route stays permissive so the importer and+ // share-bucket sync paths (which preserve remote data fidelity) can+ // still land legacy orphans.+ universeId: z.string().trim().max(seriesSvc.UNIVERSE_ID_MAX).nullable().optional(),+ writersRoomWorkId: z.string().trim().max(seriesSvc.WRITERS_ROOM_WORK_ID_MAX).nullable().optional(),+ arc: arcSchema.nullable().optional(),+ seasons: z.array(seasonSchema).max(ARC_LIMITS.SEASONS_PER_SERIES_MAX).optional(),+ locked: seriesLockedSchema.optional(),+ styleNotes: z.string().trim().max(seriesSvc.STYLE_NOTES_MAX).optional().default(''),+ titleLogo: z.string().trim().max(seriesSvc.TITLE_LOGO_MAX).optional().default(''),+ author: z.string().trim().max(seriesSvc.AUTHOR_MAX).optional().default(''),+ stylePromptOverride: z.string().trim().max(seriesSvc.STYLE_PROMPT_OVERRIDE_MAX).optional().default(''),+ stylePromptOverrideMode: z.enum(seriesSvc.STYLE_PROMPT_OVERRIDE_MODES).optional(),+ targetFormat: z.enum(seriesSvc.TARGET_FORMATS).optional(),+ primaryManuscriptType: z.enum(seriesSvc.MANUSCRIPT_TYPES).nullable().optional(),+ issueCountTarget: z.number().int().min(0).max(seriesSvc.ISSUE_COUNT_TARGET_MAX).optional(),+ llm: llmSchema,+ // Local-only "don't sync to peers" marker.+ ephemeral: z.boolean().optional(),+ });++ const seriesPatchSchema = z.object({+ name: z.string().trim().min(1).max(seriesSvc.NAME_MAX).optional(),+ logline: z.string().trim().max(seriesSvc.LOGLINE_MAX).optional(),+ premise: z.string().trim().max(seriesSvc.PREMISE_MAX).optional(),+ universeId: z.string().trim().max(seriesSvc.UNIVERSE_ID_MAX).nullable().optional(),+ writersRoomWorkId: z.string().trim().max(seriesSvc.WRITERS_ROOM_WORK_ID_MAX).nullable().optional(),+ arc: arcSchema.nullable().optional(),+ seasons: z.array(seasonSchema).max(ARC_LIMITS.SEASONS_PER_SERIES_MAX).optional(),+ locked: seriesLockedSchema.optional(),+ styleNotes: z.string().trim().max(seriesSvc.STYLE_NOTES_MAX).optional(),+ titleLogo: z.string().trim().max(seriesSvc.TITLE_LOGO_MAX).optional(),+ author: z.string().trim().max(seriesSvc.AUTHOR_MAX).optional(),+ stylePromptOverride: z.string().trim().max(seriesSvc.STYLE_PROMPT_OVERRIDE_MAX).optional(),+ stylePromptOverrideMode: z.enum(seriesSvc.STYLE_PROMPT_OVERRIDE_MODES).optional(),+ targetFormat: z.enum(seriesSvc.TARGET_FORMATS).optional(),+ primaryManuscriptType: z.enum(seriesSvc.MANUSCRIPT_TYPES).nullable().optional(),+ issueCountTarget: z.number().int().min(0).max(seriesSvc.ISSUE_COUNT_TARGET_MAX).optional(),+ llm: llmSchema,+ ephemeral: z.boolean().optional(),+ }).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });+ const arcFieldLockSchema = z.object({ locked: z.boolean() });++ // 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({+ title: z.string().trim().min(1).max(issuesSvc.TITLE_MAX),+ number: z.number().int().min(1).max(9999).optional(),+ // Per-issue length profile — can be set at create time so a user creating+ // a standalone oversized issue (e.g. an annual) doesn't have to open the+ // picker after the fact. Defaults server-side to 'standard'.+ lengthProfile: z.enum(LENGTH_PROFILE_NAMES).optional(),+ pageTarget: z.number().int().min(CUSTOM_PAGE_MIN).max(CUSTOM_PAGE_MAX).nullable().optional(),+ minutesTarget: z.number().int().min(CUSTOM_MINUTE_MIN).max(CUSTOM_MINUTE_MAX).nullable().optional(),+ ephemeral: z.boolean().optional(),+ });++ // =====================+ // Series routes+ // =====================++ router.get('/series', asyncHandler(async (_req, res) => {+ res.json(await seriesSvc.listSeries());+ }));++ router.post('/series', asyncHandler(async (req, res) => {+ const body = validateRequest(seriesCreateSchema, req.body ?? {});+ // Hierarchy invariant: every series belongs to exactly one universe. Enforce+ // it for all HTTP callers here (the UI already enforces it client-side).+ // The schema stays permissive (nullable) so the importer + mergeSeriesFromSync,+ // which call createSeries directly, can still land legacy orphans from peers.+ if (!body.universeId || !String(body.universeId).trim()) {+ throw new ServerError('A universe is required — a series must belong to a universe.', {+ status: 400, code: seriesSvc.ERR_VALIDATION,+ });+ }+ const created = await seriesSvc.createSeries(body);+ // Non-blocking same-name warning, scoped within the universe (route layer+ // only, so the importer's direct createSeries never pays for the scan).+ const duplicateName = await findSameNameSeries(created.name, created.universeId, { excludeId: created.id });+ res.status(201).json(duplicateName.length ? { ...created, _warnings: { duplicateName } } : created);+ }));++ // ---- Series duplicate resolution (static paths — keep BEFORE `/series/:id`) ----++ const seriesMergeSchema = z.object({+ survivorId: z.string().trim().regex(/^ser-/, 'must be a ser-<uuid> id').max(128),+ loserId: z.string().trim().regex(/^ser-/, 'must be a ser-<uuid> id').max(128),+ fieldChoices: z.record(z.enum(['survivor', 'loser'])).optional().default({}),+ // Free-form per-field values that win over the survivor/loser binary —+ // populated by the AI-merge flow (a third unified option) and optionally+ // tweaked by the user before submit.+ fieldOverrides: z.record(z.string()).optional().default({}),+ }).refine((b) => b.survivorId !== b.loserId, { message: 'survivor and loser must differ' });++ const seriesMergeAIResolveSchema = z.object({+ survivorId: z.string().trim().regex(/^ser-/, 'must be a ser-<uuid> id').max(128),+ loserId: z.string().trim().regex(/^ser-/, 'must be a ser-<uuid> id').max(128),+ fields: z.array(z.string().trim().min(1).max(64)).min(1).max(20),+ providerId: z.string().trim().max(80).optional(),+ model: z.string().trim().max(200).optional(),+ }).refine((b) => b.survivorId !== b.loserId, { message: 'survivor and loser must differ' });++ router.get('/series/duplicates', asyncHandler(async (_req, res) => {+ res.json(await findDuplicateSeriesGroups());+ }));++ router.post('/series/merge/preview', asyncHandler(async (req, res) => {+ const body = validateRequest(seriesMergeSchema, req.body ?? {});+ const preview = await mergeSeries(body.survivorId, body.loserId, body.fieldChoices, { dryRun: true, fieldOverrides: body.fieldOverrides })+ .catch((err) => { throw mapServiceError(err); });+ res.json(preview);+ }));++ router.post('/series/merge', asyncHandler(async (req, res) => {+ const body = validateRequest(seriesMergeSchema, req.body ?? {});+ const result = await mergeSeries(body.survivorId, body.loserId, body.fieldChoices, { fieldOverrides: body.fieldOverrides })+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+ }));++ // Ask the configured AI provider to merge specific conflicting text fields+ // into a single unified value per field. Same shape as the universe-side+ // /universe-builder/merge/ai-resolve route.+ router.post('/series/merge/ai-resolve', asyncHandler(async (req, res) => {+ const body = validateRequest(seriesMergeAIResolveSchema, req.body ?? {});+ const [survivor, loser] = await Promise.all([+ seriesSvc.getSeries(body.survivorId).catch((err) => { throw mapServiceError(err); }),+ seriesSvc.getSeries(body.loserId).catch((err) => { throw mapServiceError(err); }),+ ]);+ const result = await mergeFieldsWithAI({+ kind: 'series',+ survivor,+ loser,+ fields: body.fields,+ providerId: body.providerId,+ model: body.model,+ });+ res.json(result);+ }));++ router.get('/series/:id', asyncHandler(async (req, res) => {+ const s = await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });+ res.json(s);+ }));++ router.patch('/series/:id', asyncHandler(async (req, res) => {+ const body = validateRequest(seriesPatchSchema, req.body ?? {});+ const s = await seriesSvc.updateSeries(req.params.id, body).catch((err) => { throw mapServiceError(err); });+ if ('name' in body || 'universeId' in body) {+ const duplicateName = await findSameNameSeries(s.name, s.universeId, { excludeId: req.params.id });+ if (duplicateName.length) { res.json({ ...s, _warnings: { duplicateName } }); return; }+ }+ res.json(s);+ }));++ router.patch('/series/:id/arc-fields/:field/lock', asyncHandler(async (req, res) => {+ const body = validateRequest(arcFieldLockSchema, req.body ?? {});+ const s = await seriesSvc.setArcFieldLock(req.params.id, req.params.field, body.locked)+ .catch((err) => { throw mapServiceError(err); });+ res.json(s);+ }));++ router.delete('/series/:id', asyncHandler(async (req, res) => {+ const r = await seriesSvc.deleteSeries(req.params.id).catch((err) => { throw mapServiceError(err); });+ res.json(r);+ }));++ // Generate (or regenerate) the series.titleLogo description via the+ // `pipeline-series-title-logo` stage. Returns the updated series so the+ // client can swap state without a follow-up GET.+ const titleLogoGenerateSchema = z.object({+ providerId: z.string().trim().max(80).optional(),+ model: z.string().trim().max(200).optional(),+ });+ router.post('/series/:id/generate-title-logo', asyncHandler(async (req, res) => {+ const body = validateRequest(titleLogoGenerateSchema, req.body ?? {});+ const result = await generateSeriesTitleLogo(req.params.id, body)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+ }));++ router.get('/series/:id/issues', asyncHandler(async (req, res) => {+ // Validate the series exists so a typo returns 404 instead of [] (less+ // confusing for the UI).+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });+ const hasPagination = req.query.offset !== undefined || req.query.limit !== undefined;+ // List endpoints strip per-stage runHistory; the UI never renders it on+ // these views and a maxed-out issue can otherwise ship ~12MB of payload.+ // Detail reads (`GET /issues/:id`) stay on the full shape.+ if (hasPagination) {+ const { offset, limit } = validateRequest(issuesListQuerySchema, req.query);+ res.json(await issuesSvc.listIssues({ seriesId: req.params.id, offset, limit, paginated: true, withHistory: false }));+ } else {+ res.json(await issuesSvc.listIssues({ seriesId: req.params.id, withHistory: false }));+ }+ }));++ router.post('/series/:id/issues', asyncHandler(async (req, res) => {+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });+ const body = validateRequest(issueCreateSchema, req.body ?? {});+ const created = await issuesSvc.createIssue({ ...body, seriesId: req.params.id });+ 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);+ }));++ export default router;