Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(pipeline): per-volume Validate volume continuity pass + inline verify scope hints
[._.]/ Adam Eivy782358761a55
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 3dc564ede3..02899cdb42 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,27 @@## Added+- **Series Pipeline — per-volume Validate volume continuity pass.**+ Complement to the cross-volume Verify arc pass: a new "Validate volume"+ button on each season/volume row runs a deeper, narrower continuity check+ scoped to that single volume. Goes to beat depth (`stages.idea.output`) for+ issues whose beats are expanded; falls back to synopsis depth (`stages.idea.input`)+ for un-expanded issues, so a partially-expanded volume can still be+ validated mid-workflow. Boundary checks against the immediately-prior and+ immediately-next volumes only (the cross-volume arc verify handles distant+ cross-references). Checks: volume-internal arc shape, within-volume+ continuity, beat-level escalation, promise drift, boundary continuity,+ cast economy, volume-scope world-entity drift, and obvious length-vs-weight+ mismatches. Each verify button now also exposes an inline "What this+ checks" disclosure listing its rules and depth so the human editor knows+ what each pass covers (and what it explicitly doesn't) before trusting+ the result. **Files:** new+ `data.sample/prompts/stages/pipeline-volume-verify.md` + stage-config+ entry, new `verifyVolume()` in `server/services/pipeline/arcPlanner.js`,+ new `POST /pipeline/series/:id/seasons/:seasonId/verify` route,+ `verifyPipelineVolume()` API helper, and `VerifyScopeHint` + Validate+ volume button wiring in `client/src/components/pipeline/ArcCanvas.jsx`.+- **Series Pipeline — Vonnegut story-shape picker + sparkline visualization.**Series records can now carry an explicit narrative-shape decision drawn fromKurt Vonnegut's eight story shapes (Rags to Riches, Tragedy, Man in Hole,diff --git a/client/src/components/pipeline/ArcCanvas.jsx b/client/src/components/pipeline/ArcCanvas.jsxindex d6807bbedd..c269eaf0d5 100644--- a/client/src/components/pipeline/ArcCanvas.jsx+++ b/client/src/components/pipeline/ArcCanvas.jsx@@ -27,7 +27,7 @@ import { useMemo, useState } from 'react';import { Link } from 'react-router-dom';import {Plus, Trash2, Loader2, Sparkles, ShieldCheck, ChevronRight, ChevronDown,- ChevronsUpDown, AlertCircle, Wand2,+ ChevronsUpDown, AlertCircle, Wand2, Info,} from 'lucide-react';import toast from '../ui/Toast';import { timeAgo } from '../../utils/formatters';@@ -36,6 +36,7 @@ import {createPipelineIssue, deletePipelineIssue, updatePipelineIssue,createPipelineSeason, updatePipelineSeason, deletePipelineSeason,generatePipelineArcOverview, generatePipelineSeasonEpisodes, verifyPipelineArc,+ verifyPipelineVolume,resolvePipelineArcIssues,listPipelineIssues, updatePipelineSeries,} from '../../services/api';@@ -55,6 +56,54 @@ const SEVERITY_COLORS = {low: 'text-gray-400 border-gray-500/30 bg-gray-700/20',};+// What each verify pass actually checks. Surfaced as a `<details>` next to+// the button so the editor knows what they're getting (and what they're NOT+// getting) before they trust the green check.+const VERIFY_ARC_SCOPE = {+ depth: 'Synopsis-level only across every volume. Beats and scripts are NOT read — use Validate volume for that.',+ checks: [+ 'Character contradictions across volumes (dead character speaks; protagonist state breaks at a volume boundary)',+ 'Dropped subplots (an early endingHook never paid off later)',+ 'Episode-count vs. arc-weight mismatch per volume',+ 'Unresolved finale hooks (logline / protagonist arc / themes)',+ 'Arc-role imbalance (missing or duplicate pilot / finale)',+ 'Theme drift (a theme is named in the arc but appears in no synopsis)',+ 'World entity drift (refs to nonexistent factions / characters / locations, or unused major entities)',+ ],+};++const VERIFY_VOLUME_SCOPE = {+ depth: 'One volume in depth — reads beat sheets (stages.idea.output) for issues that have them, falls back to synopsis depth for un-expanded issues. Boundary checks against the immediate-neighbor volumes only.',+ checks: [+ 'Volume-internal arc shape (does the volume read as a complete sub-arc; does the final issue pay off the endingHook)',+ 'Within-volume continuity (a character / object / beat that disappears mid-volume without resolution)',+ 'Beat-level escalation (issues with beats only) — adjacent issues that plateau or contradict each other',+ 'Promise drift (the volume logline / synopsis makes a promise no issue delivers — or vice versa)',+ 'Boundary continuity (volume opening picks up the prior endingHook; volume endingHook seeds the next volume)',+ 'Cast economy (a one-beat introduction never seen again, or a major bible character the volume never uses)',+ 'Volume-scope world-entity drift',+ 'Length-vs-weight mismatch obvious in isolation',+ ],+};++function VerifyScopeHint({ scope }) {+ return (+ <details className="text-[10px] text-gray-500">+ <summary className="cursor-pointer hover:text-gray-300 inline-flex items-center gap-1">+ <Info size={10} /> What this checks+ </summary>+ <div className="mt-1 pl-4 space-y-1">+ <p className="text-gray-400 italic">{scope.depth}</p>+ <ul className="list-disc pl-4 space-y-0.5">+ {scope.checks.map((c) => (+ <li key={c}>{c}</li>+ ))}+ </ul>+ </div>+ </details>+ );+}+export default function ArcCanvas({ series, issues, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {const seasons = series.seasons || [];// Group issues by seasonId for the tree; ungrouped issues land under null.@@ -244,6 +293,7 @@ function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {onClick={runVerify}disabled={!!running}className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded text-sm font-medium border bg-port-bg text-gray-300 border-port-border hover:border-port-accent/40 disabled:opacity-40"+ title="Cross-volume continuity pass at synopsis depth">{running === 'verify' ? <Loader2 size={14} className="animate-spin" /> : <ShieldCheck size={14} />}Verify arc@@ -252,6 +302,8 @@ function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {</div></div>+ {hasGeneratedArc ? <VerifyScopeHint scope={VERIFY_ARC_SCOPE} /> : null}+{arc ? (<ArcContent series={series} onSeriesUpdate={onSeriesUpdate} />) : (@@ -410,12 +462,12 @@ function ArcContent({ series, onSeriesUpdate }) {);}-function VerifyResults({ issues, onDismiss, onResolveAll, onResolveOne, resolvingAll, resolvingIdx }) {+function VerifyResults({ issues, onDismiss, onResolveAll, onResolveOne, resolvingAll, resolvingIdx, title = 'Verification' }) {const busy = resolvingAll || (resolvingIdx && resolvingIdx.size > 0);return (<div className="border border-port-border rounded p-3 bg-port-bg/50 space-y-2"><div className="flex items-center justify-between gap-2 flex-wrap">- <h3 className="text-xs uppercase tracking-wider text-gray-500">Verification — {issues.length} issue{issues.length === 1 ? '' : 's'}</h3>+ <h3 className="text-xs uppercase tracking-wider text-gray-500">{title} — {issues.length} issue{issues.length === 1 ? '' : 's'}</h3><div className="flex items-center gap-2">{onResolveAll ? (<button@@ -477,6 +529,30 @@ function SeasonRow({ series, season, seasons, issues, onSeriesUpdate, onIssuesUpconst [collapsed, setCollapsed] = useState(false);const [generatingEpisodes, setGeneratingEpisodes] = useState(false);const [editing, setEditing] = useState(false);+ const [verifying, setVerifying] = useState(false);+ const [verifyIssues, setVerifyIssues] = useState(null);++ const hasArc = !!series.arc;+ const hasEpisodes = issues.length > 0;+ const runVerifyVolume = async () => {+ setVerifying(true);+ const result = await verifyPipelineVolume(series.id, season.id, {+ providerOverride: series.llm?.provider || undefined,+ modelOverride: series.llm?.model || undefined,+ }).catch((err) => {+ toast.error(err.message || 'Failed to verify volume');+ return null;+ });+ setVerifying(false);+ if (!result) return;+ setVerifyIssues(result.issues || []);+ const n = (result.issues || []).length;+ if (n === 0) {+ toast.success(`Volume ${season.number} verified — no issues found`);+ } else {+ toast.error(`Volume ${season.number} verification surfaced ${n} issue${n === 1 ? '' : 's'}`);+ }+ };const runGenerateEpisodes = async () => {if (issues.length > 0) {@@ -585,12 +661,24 @@ function SeasonRow({ series, season, seasons, issues, onSeriesUpdate, onIssuesUp/>))}</ul>+ {verifyIssues && verifyIssues.length > 0 ? (+ <div className="px-3 pb-3">+ <VerifyResults+ issues={verifyIssues}+ title={`Volume ${season.number} verification`}+ onDismiss={() => setVerifyIssues(null)}+ />+ </div>+ ) : null}<SeasonActionsseries={series}season={season}- hasEpisodes={issues.length > 0}+ hasArc={hasArc}+ hasEpisodes={hasEpisodes}generatingEpisodes={generatingEpisodes}+ verifying={verifying}onGenerateEpisodes={runGenerateEpisodes}+ onValidateVolume={runVerifyVolume}onIssuesUpdate={onIssuesUpdate}/></>@@ -704,7 +792,10 @@ function SeasonEditor({ series, season, seasons, onSeriesUpdate }) {);}-function SeasonActions({ series, season, hasEpisodes, generatingEpisodes, onGenerateEpisodes, onIssuesUpdate }) {+function SeasonActions({+ series, season, hasArc, hasEpisodes, generatingEpisodes,+ verifying, onGenerateEpisodes, onValidateVolume, onIssuesUpdate,+}) {const [adding, setAdding] = useState(false);const [newTitle, setNewTitle] = useState('');const seasonHasContext = !!(season.logline?.trim() || season.synopsis?.trim());@@ -731,61 +822,87 @@ function SeasonActions({ series, season, hasEpisodes, generatingEpisodes, onGenetoast.success(`Issue / Episode "${created.title}" added`);};+ // Validate volume needs (1) an authored arc on the parent series and+ // (2) at least one issue under this volume — otherwise there is nothing+ // for the LLM to check against the volume's promises.+ const validateDisabledReason = !hasArc+ ? 'Generate the series arc first (the volume verifier checks against the arc)'+ : !hasEpisodes+ ? 'Add or generate at least one issue / episode first'+ : null;+return (- <div className="px-3 pb-3 pt-1 border-t border-port-border/50 flex items-center gap-2 flex-wrap">- {adding ? (- <form onSubmit={handleAdd} className="flex items-center gap-2 flex-1">- <input- value={newTitle}- onChange={(e) => setNewTitle(e.target.value)}- placeholder="Issue / Episode title…"- className="flex-1 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"- autoFocus- maxLength={300}- />- <button- type="submit"- disabled={!newTitle.trim()}- className="inline-flex items-center gap-1 px-3 py-1.5 rounded bg-port-accent text-white text-sm font-medium disabled:opacity-40"- >- <Plus size={12} /> Add- </button>- <button- type="button"- onClick={() => { setAdding(false); setNewTitle(''); }}- className="text-xs text-gray-400 hover:text-white px-2"- >- Cancel- </button>- </form>- ) : (- <>- <button- type="button"- onClick={() => setAdding(true)}- className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-300 hover:text-white border border-port-border bg-port-bg"- >- <Plus size={12} /> Add issue / episode- </button>- <button- type="button"- onClick={onGenerateEpisodes}- disabled={generatingEpisodes || hasEpisodes || !seasonHasContext}- title={- hasEpisodes- ? 'Volume already has issues / episodes'- : !seasonHasContext- ? 'Add a volume logline or synopsis first'- : 'Have an LLM plan the per-issue / per-episode breakdown'- }- className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-port-accent hover:text-white border border-port-border bg-port-bg hover:border-port-accent/40 disabled:opacity-40 disabled:hover:text-port-accent"- >- {generatingEpisodes ? <Loader2 size={12} className="animate-spin" /> : <Wand2 size={12} />}- Generate issues / episodes (LLM)- </button>- </>- )}- </div>+ <>+ <div className="px-3 pb-2 pt-2 border-t border-port-border/50 flex items-center gap-2 flex-wrap">+ {adding ? (+ <form onSubmit={handleAdd} className="flex items-center gap-2 flex-1">+ <input+ value={newTitle}+ onChange={(e) => setNewTitle(e.target.value)}+ placeholder="Issue / Episode title…"+ className="flex-1 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"+ autoFocus+ maxLength={300}+ />+ <button+ type="submit"+ disabled={!newTitle.trim()}+ className="inline-flex items-center gap-1 px-3 py-1.5 rounded bg-port-accent text-white text-sm font-medium disabled:opacity-40"+ >+ <Plus size={12} /> Add+ </button>+ <button+ type="button"+ onClick={() => { setAdding(false); setNewTitle(''); }}+ className="text-xs text-gray-400 hover:text-white px-2"+ >+ Cancel+ </button>+ </form>+ ) : (+ <>+ <button+ type="button"+ onClick={() => setAdding(true)}+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-300 hover:text-white border border-port-border bg-port-bg"+ >+ <Plus size={12} /> Add issue / episode+ </button>+ <button+ type="button"+ onClick={onGenerateEpisodes}+ disabled={generatingEpisodes || hasEpisodes || !seasonHasContext}+ title={+ hasEpisodes+ ? 'Volume already has issues / episodes'+ : !seasonHasContext+ ? 'Add a volume logline or synopsis first'+ : 'Have an LLM plan the per-issue / per-episode breakdown'+ }+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-port-accent hover:text-white border border-port-border bg-port-bg hover:border-port-accent/40 disabled:opacity-40 disabled:hover:text-port-accent"+ >+ {generatingEpisodes ? <Loader2 size={12} className="animate-spin" /> : <Wand2 size={12} />}+ Generate issues / episodes (LLM)+ </button>+ <button+ type="button"+ onClick={onValidateVolume}+ disabled={!!validateDisabledReason || verifying}+ title={validateDisabledReason || `Deep continuity pass on volume ${season.number}`}+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-300 hover:text-white border border-port-border bg-port-bg hover:border-port-accent/40 disabled:opacity-40 disabled:hover:text-gray-300"+ >+ {verifying ? <Loader2 size={12} className="animate-spin" /> : <ShieldCheck size={12} />}+ Validate volume+ </button>+ </>+ )}+ </div>+ {!adding ? (+ <div className="px-3 pb-3">+ <VerifyScopeHint scope={VERIFY_VOLUME_SCOPE} />+ </div>+ ) : null}+ </>);}diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex e405a68b59..78a0e406dd 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -251,6 +251,16 @@ export const verifyPipelineArc = (seriesId, { providerOverride, modelOverride }body: JSON.stringify({ providerOverride, modelOverride }),});+// Deep verify pass for a single volume / season. Complements verifyPipelineArc:+// the arc pass is cross-volume + synopsis-depth; this pass is volume-scoped+// and goes to beat depth for issues whose stages.idea.output is populated.+// Returns { issues, runId, providerId, model, seasonId }. Empty issues[] = clean.+export const verifyPipelineVolume = (seriesId, seasonId, { providerOverride, modelOverride } = {}) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/seasons/${encodeURIComponent(seasonId)}/verify`, {+ method: 'POST',+ body: JSON.stringify({ providerOverride, modelOverride }),+ });+// Auto-resolve verification findings — server runs an LLM pass that rewrites// the arc + volume/season outlines to address every finding, then persists.// Pass `findings: [...]` to resolve only that subset; omit to re-verify anddiff --git a/data.sample/prompts/stage-config.json b/data.sample/prompts/stage-config.jsonindex 21c26a976b..98b2183e3b 100644--- a/data.sample/prompts/stage-config.json+++ b/data.sample/prompts/stage-config.json@@ -242,6 +242,13 @@"returnsJson": true,"variables": []},+ "pipeline-volume-verify": {+ "name": "Pipeline — Volume / Season Verification",+ "description": "Deep continuity pass on a single volume / season: volume-internal arc shape, within-volume continuity, beat-level escalation (issues with beats), promise drift, boundary continuity with neighbor volumes, cast economy, volume-scope world-entity drift, and obvious length-vs-weight mismatches. Complement to the cross-volume arc verify, deeper because the scope is smaller. Returns actionable { severity, location, problem, suggestion } issues — empty list means clean.",+ "model": "heavy",+ "returnsJson": true,+ "variables": []+ },"pipeline-comic-panel-image-prompt": {"name": "Pipeline — Comic Panel Image Prompt","description": "Refine a single comic panel's description into a richer image-gen-ready prompt. Uses caption / dialogue / sfx context + neighboring-panel continuity to elaborate without re-imagining the scene.",diff --git a/data.sample/prompts/stages/pipeline-volume-verify.md b/data.sample/prompts/stages/pipeline-volume-verify.mdnew file mode 100644index 0000000000..3aa6380c03--- /dev/null+++ b/data.sample/prompts/stages/pipeline-volume-verify.md@@ -0,0 +1,119 @@+# Pipeline — Volume / Season Verification++You are a continuity editor doing a deep pass on **a single volume / season** of a planned series. The cross-volume `pipeline-arc-verify` pass already covers structural problems across the whole arc at synopsis depth — your job is the complementary inner pass: surface problems that live **inside this one volume**, going deeper than the cross-volume pass can afford.++Every series is published in two parallel formats: graphic novel (issues → volumes) AND TV series (episodes → seasons). One issue == one episode; one volume == one season. Findings should call out problems that would break either format.++## Series bible++- **Name:** {{series.name}}+- **Logline:** {{series.logline}}+- **Premise:**++```+{{series.premise}}+```++## Linked World — canonical entities++The arc was authored against this World Builder world: **{{worldName}}**. Continuity findings should call out when the volume references factions / characters / locations that don't exist in this entity set.++### World entity categories++```+{{worldCategoriesText}}+```++### World composite reference sheets++```+{{worldCompositesText}}+```++{{> bible-deference }}++## Full arc (context — not under review here)++- **Whole-series logline:** {{arc.logline}}+- **Themes:** {{arc.themesCsv}}+- **Protagonist arc:**++```+{{arc.protagonistArc}}+```++- **Arc summary:**++```+{{arc.summary}}+```++## This volume++- **Volume / Season number:** {{volume.number}}+- **Title:** {{volume.title}}+- **Logline:** {{volume.logline}}+- **Issue / episode count target:** {{volume.episodeCountTarget}}+- **Ending hook:** {{volume.endingHook}}+- **Themes (volume):** {{volume.themesCsv}}+- **Synopsis:**++```+{{volume.synopsis}}+```++## Sibling volumes — neighbors only (context for boundary checks)++```json+{{neighborsJson}}+```++## Issues / episodes in this volume++Each entry has either `beats` (the LLM-expanded beat sheet from `stages.idea.output`) OR just `synopsis` (the un-expanded `stages.idea.input` seed) — never both. Beat-level findings are only valid against issues that have `beats`; synopsis-only entries can only be checked at synopsis depth.++```json+{{volumeIssuesJson}}+```++## What to look for++Walk the volume in issue / episode order. Score each issue against the volume's promises (logline, synopsis, endingHook) and against the issues around it. Specifically check:++1. **Volume-internal arc shape.** Does this volume's issues form a complete sub-arc (setup → escalation → midpoint → climax → endingHook payoff)? Flag a volume whose final issue does NOT pay off the volume's `endingHook`, or where the midpoint issue has no escalation.+2. **Within-volume continuity.** Does a character's state at the end of issue N contradict their state opening issue N+1? Did an issue introduce a beat, location, or object that disappears in subsequent issues without resolution?+3. **Beat-level escalation (issues with `beats` only).** Do the beats across consecutive issues actually escalate stakes, or do two adjacent issues plateau at the same intensity? Flag beats that contradict each other across issues.+4. **Promise drift.** The volume's `logline` / `synopsis` makes a promise that none of the child issues delivers on. Or: a child issue introduces a major plot thread the volume's synopsis never mentions and that won't fit in the remaining issue count.+5. **Boundary continuity.** Does the volume's opening issue actually pick up from the prior volume's `endingHook` (when present)? Does the volume's `endingHook` set up something the next volume's `logline` references?+6. **Cast economy.** A character introduced in this volume that gets exactly one beat and is never seen again. Or a major character from the bible / world that the volume's issues never use despite a thematic fit.+7. **World entity drift (volume scope).** This volume's issues name factions / characters / locations that don't exist in the linked world (suggest renaming to a real entity).+8. **Length-vs-weight mismatch.** Issue count target says 8 but the synopsis is summarizable in 3 beats, or vice versa. (Cross-volume pass already checks the whole arc — only flag here when it's obvious from this volume in isolation.)++DO NOT flag problems that are properly cross-volume in nature (a character introduced in volume 1 paying off in volume 4 — that's the arc verify's job, not yours). Stay inside this volume's walls; the only outside-the-walls checks allowed are #5 (boundary continuity with the immediate neighbors shown above).++## Output contract++Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary. Each `issues[]` entry must be **actionable** — name the issue / 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": "episode:3",+ "problem": "string (what's wrong, with the specific evidence — quote the contradicting lines from beats / synopsis)",+ "suggestion": "string (the smallest edit that resolves it)"+ }+ ]+}+```++`severity` must be one of `high` / `medium` / `low`:++- **`high`** — would break a reader / viewer's understanding of the volume (dead character returns, contradicted protagonist state, endingHook un-paid).+- **`medium`** — would make the volume feel sloppy (plateaued beats, cast member who appears once, promise the volume didn't keep).+- **`low`** — opportunity to tighten (underused theme, an issue whose beats don't quite escalate from the prior issue).++`location` should use the form `episode:<arcPosition>` (e.g., `episode:3`) or `episode:<n>-<n+1>` for an issue boundary. Use `volume` when the finding is about the volume as a whole rather than a specific issue.++Return `{ "issues": [] }` if everything checks out. Do NOT pad with low-confidence "consider also..." entries.diff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex 9e17c19c80..1f0e80aa3a 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -381,6 +381,8 @@ const providerOverrideShape = {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);// Auto-resolve verification findings. `findings` empty/omitted = re-verify// first then resolve everything; otherwise the LLM only addresses the@@ -658,6 +660,18 @@ router.post('/series/:id/arc/verify', asyncHandler(async (req, res) => {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);+}));+// 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) => {diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.jsindex da226b86d3..bd11c559f4 100644--- a/server/routes/pipeline.test.js+++ b/server/routes/pipeline.test.js@@ -38,6 +38,7 @@ vi.mock('../services/pipeline/textStages.js', async () => {let arcGenerateSpy;let seasonEpisodesSpy;let arcVerifySpy;+let volumeVerifySpy;vi.mock('../services/pipeline/arcPlanner.js', async () => {const actual = await vi.importActual('../services/pipeline/arcPlanner.js');return {@@ -45,6 +46,7 @@ vi.mock('../services/pipeline/arcPlanner.js', async () => {generateArcOverview: vi.fn((...args) => arcGenerateSpy(...args)),generateSeasonEpisodes: vi.fn((...args) => seasonEpisodesSpy(...args)),verifyArc: vi.fn((...args) => arcVerifySpy(...args)),+ verifyVolume: vi.fn((...args) => volumeVerifySpy(...args)),};});@@ -1100,4 +1102,22 @@ describe('pipeline routes', () => {expect(r.body.issues).toHaveLength(1);expect(r.body.issues[0].severity).toBe('high');});++ it('POST /series/:id/seasons/:seasonId/verify forwards to the volume verifier', async () => {+ const app = makeApp();+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });+ volumeVerifySpy = vi.fn(async (_seriesId, seasonId) => ({+ issues: [+ { severity: 'medium', location: 'episode:3', problem: 'beats plateau', suggestion: 'escalate ep 3' },+ ],+ runId: 'rv', providerId: 'p', model: 'm', seasonId,+ }));+ const r = await request(app)+ .post(`/api/pipeline/series/${ser.body.id}/seasons/sea-fake/verify`)+ .send({ providerOverride: 'anthropic' });+ expect(r.status).toBe(200);+ expect(r.body.issues).toHaveLength(1);+ expect(r.body.issues[0].location).toBe('episode:3');+ expect(volumeVerifySpy).toHaveBeenCalledWith(ser.body.id, 'sea-fake', expect.objectContaining({ providerOverride: 'anthropic' }));+ });});diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.jsindex b48bdc6fa5..c424ac5034 100644--- a/server/services/pipeline/arcPlanner.js+++ b/server/services/pipeline/arcPlanner.js@@ -23,6 +23,7 @@ import { runStagedLLM } from '../../lib/stageRunner.js';import { ServerError } from '../../lib/errorHandler.js';import { getSeries, updateSeries } from './series.js';import { listIssues } from './issues.js';+import { getSeason } from './seasons.js';import { sanitizeArc, sanitizeSeasonList, sanitizeSeason, buildSeason } from '../../lib/storyArc.js';import { recommendStructure, describeStructure } from '../../lib/seasonStructure.js';import { LENGTH_PROFILE_NAMES, DEFAULT_LENGTH_PROFILE } from '../../lib/issueLength.js';@@ -53,7 +54,7 @@ function renderPriorSeason(s, priorIssues) {const header = `### Season ${s.number} — ${s.title}\n\n${s.logline}\n\n${s.synopsis || '(no synopsis)'}`;const seasonEpisodes = priorIssues.filter((iss) => iss.seasonId === s.id)- .sort((a, b) => (a.arcPosition ?? 9999) - (b.arcPosition ?? 9999));+ .sort(compareIssuesByPosition);if (seasonEpisodes.length === 0) return header;const lines = seasonEpisodes.map((iss) => {const idea = (iss.stages?.idea?.input || '').trim();@@ -108,6 +109,34 @@ async function resolveWorldContext(series, preloaded) {return (await loadWorldContext(series.universeId)) || EMPTY_WORLD_CONTEXT;}+// Canonical issue sort: arcPosition first (issues seeded by the season-+// episode generator carry sequential positions), then series number as a+// tiebreaker for issues that were created ad-hoc and never got a position.+const compareIssuesByPosition = (a, b) =>+ (a.arcPosition ?? 9999) - (b.arcPosition ?? 9999) || (a.number || 0) - (b.number || 0);++// Series + world + arc fields shared by every arc-level prompt context.+// Pulled out so verify-arc and verify-volume don't drift on what counts as+// "the bible block" — both passes must see the same series identity.+async function buildArcBaseContext(series, preloadedWorld) {+ const arc = series.arc || {};+ const world = await resolveWorldContext(series, preloadedWorld);+ return {+ series: {+ name: series.name,+ logline: series.logline,+ premise: series.premise,+ },+ ...world,+ arc: {+ logline: arc.logline || '',+ summary: arc.summary || '',+ protagonistArc: arc.protagonistArc || '',+ themesCsv: Array.isArray(arc.themes) ? arc.themes.join(', ') : '',+ },+ };+}+// The `recommendedStructure` field encodes comic-as-TV norms (6–10 per// season, single season ≤ 12, 3-season arc around 18–30) so the LLM stops// defaulting to 3 seasons regardless of total count.@@ -338,7 +367,11 @@ export async function generateSeasonEpisodes(seriesId, seasonId, options = {}) {*/async function buildVerifyContext(series, preloadedWorld) {const seasons = sanitizeSeasonList(series.seasons || []);- const issues = await listIssues({ seriesId: series.id });+ const [issues, base, canon] = await Promise.all([+ listIssues({ seriesId: series.id }),+ buildArcBaseContext(series, preloadedWorld),+ getSeriesCanon(series),+ ]);// 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.@@ -358,7 +391,7 @@ async function buildVerifyContext(series, preloadedWorld) {});}for (const list of issuesBySeason.values()) {- list.sort((a, b) => (a.arcPosition ?? 9999) - (b.arcPosition ?? 9999) || (a.number || 0) - (b.number || 0));+ list.sort(compareIssuesByPosition);}const tree = seasons.map((s) => ({number: s.number,@@ -379,22 +412,8 @@ async function buildVerifyContext(series, preloadedWorld) {episodes: ungrouped,});}- const arc = series.arc || {};- const world = await resolveWorldContext(series, preloadedWorld);- const canon = await getSeriesCanon(series);return {- series: {- name: series.name,- logline: series.logline,- premise: series.premise,- },- ...world,- arc: {- logline: arc.logline || '',- summary: arc.summary || '',- protagonistArc: arc.protagonistArc || '',- themesCsv: Array.isArray(arc.themes) ? arc.themes.join(', ') : '',- },+ ...base,seasonsTreeJson: JSON.stringify(tree, null, 2),existingCharactersJson: JSON.stringify(canon.characters, null, 2),existingSettingsJson: JSON.stringify(canon.settings, null, 2),@@ -446,6 +465,104 @@ export async function verifyArc(seriesId, options = {}) {return { issues, raw: content, runId, providerId, model };}+// Set exactly one of `beats` / `synopsis` so the prompt's beat-level checks+// don't run against synopsis-only issues (and vice-versa). Beats land in+// idea.output once the LLM-expand pass runs; before that, idea.input still+// carries the seed synopsis.+function renderVolumeIssue(iss) {+ const beats = (iss.stages?.idea?.output || '').trim();+ const synopsis = (iss.stages?.idea?.input || '').trim();+ const base = {+ number: iss.number,+ title: iss.title,+ status: iss.status,+ arcPosition: iss.arcPosition,+ };+ if (beats) return { ...base, beats };+ return { ...base, synopsis: synopsis || null };+}++// Neighbor volumes — only the immediately-prior and immediately-next season+// (by `number`) — so the LLM can check boundary continuity (#5 in the+// prompt) without ballooning the context. Excludes the volume under review.+function buildNeighborVolumes(allSeasons, currentSeasonId) {+ const sorted = (allSeasons || [])+ .filter((s) => s && s.id)+ .slice()+ .sort((a, b) => (a.number || 0) - (b.number || 0));+ const idx = sorted.findIndex((s) => s.id === currentSeasonId);+ if (idx < 0) return [];+ const out = [];+ if (idx > 0) out.push({ position: 'prior', ...sliceSeasonForNeighbor(sorted[idx - 1]) });+ if (idx < sorted.length - 1) out.push({ position: 'next', ...sliceSeasonForNeighbor(sorted[idx + 1]) });+ return out;+}++function sliceSeasonForNeighbor(s) {+ return {+ number: s.number,+ title: s.title,+ logline: s.logline || '',+ synopsis: s.synopsis || '',+ endingHook: s.endingHook || '',+ };+}++async function buildVolumeVerifyContext(series, season, preloadedWorld) {+ const [allIssues, base] = await Promise.all([+ listIssues({ seriesId: series.id }),+ buildArcBaseContext(series, preloadedWorld),+ ]);+ const volumeIssues = allIssues+ .filter((iss) => iss.seasonId === season.id)+ .sort(compareIssuesByPosition)+ .map(renderVolumeIssue);+ return {+ ...base,+ volume: {+ number: season.number ?? '',+ title: season.title || '',+ logline: season.logline || '',+ synopsis: season.synopsis || '',+ endingHook: season.endingHook || '',+ episodeCountTarget: season.episodeCountTarget ?? '',+ themesCsv: Array.isArray(season.themes) ? season.themes.join(', ') : '',+ },+ neighborsJson: JSON.stringify(buildNeighborVolumes(series.seasons, season.id), null, 2),+ volumeIssuesJson: JSON.stringify(volumeIssues, null, 2),+ };+}++// Verify a single volume / season — the deeper, narrower counterpart to+// verifyArc. The cross-volume pass operates at synopsis depth across the+// whole arc; this pass operates at beat depth (when beats exist) across one+// volume. Issues without beats are checked at synopsis depth — the prompt+// is explicitly aware of which depth each issue is at, so a partially-+// expanded volume can still be validated mid-workflow.+export async function verifyVolume(seriesId, seasonId, options = {}) {+ const series = await getSeries(seriesId);+ if (!series.arc) {+ throw new ServerError(+ 'Series has no arc — run /arc/generate first before verifying a volume',+ { status: 400, code: 'PIPELINE_NO_ARC' },+ );+ }+ const season = await getSeason(seriesId, seasonId);+ const ctx = await buildVolumeVerifyContext(series, season, options.preloadedWorld);+ const { content, runId, providerId, model } = await runStagedLLM(+ 'pipeline-volume-verify',+ ctx,+ {+ providerOverride: options.providerOverride,+ modelOverride: options.modelOverride,+ returnsJson: true,+ source: 'pipeline-volume-verify',+ },+ );+ const issues = shapeVerifyIssues(content?.issues);+ return { issues, raw: content, runId, providerId, model, seasonId };+}+async function buildResolveContext(series, findings, preloadedWorld) {const ctx = await buildVerifyContext(series, preloadedWorld);const structure = recommendStructure(series.issueCountTarget);@@ -581,9 +698,12 @@ export const __testing = {buildArcOverviewContext,buildSeasonEpisodesContext,buildVerifyContext,+ buildVolumeVerifyContext,buildResolveContext,shapeSeasonOutlines,shapeEpisodes,shapeVerifyIssues,shapeFindings,+ renderVolumeIssue,+ buildNeighborVolumes,};diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.jsindex f6436ce0f5..8f92fe508a 100644--- a/server/services/pipeline/arcPlanner.test.js+++ b/server/services/pipeline/arcPlanner.test.js@@ -336,6 +336,141 @@ describe('arcPlanner — verifyArc', () => {});});+describe('arcPlanner — verifyVolume', () => {+ beforeEach(() => {+ fileStore.clear();+ uuidCounter = 0;+ stageRunnerSpy = undefined;+ });++ it('throws 400 NO_ARC if the series has no arc to anchor the volume against', async () => {+ const s = await setupSeries();+ const sea = await seasonsSvc.createSeason(s.id, { title: 'V1', logline: 'l' });+ await expect(planner.verifyVolume(s.id, sea.id))+ .rejects.toMatchObject({ status: 400, code: 'PIPELINE_NO_ARC' });+ });++ it('throws NOT_FOUND when the season id does not exist on the series', async () => {+ const s = await setupSeries();+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'L' } });+ await expect(planner.verifyVolume(s.id, 'sea-does-not-exist'))+ .rejects.toMatchObject({ code: 'PIPELINE_SEASON_NOT_FOUND' });+ });++ it('emits beats for expanded issues and synopsis for un-expanded ones, never both', async () => {+ const s = await setupSeries();+ await seriesSvc.updateSeries(s.id, {+ arc: { logline: 'Whole arc', summary: 'sum', themes: ['legacy'] },+ });+ const sea = await seasonsSvc.createSeason(s.id, {+ title: 'V1', logline: 'volume l', synopsis: 'volume s', endingHook: 'hook',+ episodeCountTarget: 3,+ });+ // Issue 1: has beats (LLM output filled). Expect `beats` field, no `synopsis`.+ const beatsIssue = await issuesSvc.createIssue({+ seriesId: s.id, title: 'Ep 1', seasonId: sea.id, arcPosition: 1,+ stages: { idea: { input: 'seed', output: 'beat 1\nbeat 2\nbeat 3', status: 'ready' } },+ });+ // Issue 2: synopsis-only (idea.input set, output empty). Expect `synopsis`,+ // no `beats`.+ const synopsisIssue = await issuesSvc.createIssue({+ seriesId: s.id, title: 'Ep 2', seasonId: sea.id, arcPosition: 2,+ stages: { idea: { input: 'just a seed', status: 'edited' } },+ });+ // Issue from another season — must not leak into this volume's payload.+ const otherSeason = await seasonsSvc.createSeason(s.id, { title: 'V2', logline: 'other' });+ await issuesSvc.createIssue({+ seriesId: s.id, title: 'Other vol issue', seasonId: otherSeason.id, arcPosition: 1,+ stages: { idea: { input: 'other', output: 'other beats', status: 'ready' } },+ });++ stageRunnerSpy = vi.fn(async () => ({+ content: { issues: [{ severity: 'high', problem: 'X', location: 'episode:1', suggestion: 'Y' }] },+ runId: 'rv', providerId: 'p', model: 'm',+ }));++ const out = await planner.verifyVolume(s.id, sea.id);+ expect(stageRunnerSpy).toHaveBeenCalledWith(+ 'pipeline-volume-verify',+ expect.any(Object),+ expect.objectContaining({ returnsJson: true, source: 'pipeline-volume-verify' }),+ );++ const ctx = stageRunnerSpy.mock.calls[0][1];+ expect(ctx.volume.title).toBe('V1');+ expect(ctx.volume.endingHook).toBe('hook');++ const volumeIssues = JSON.parse(ctx.volumeIssuesJson);+ expect(volumeIssues).toHaveLength(2);+ expect(volumeIssues[0].title).toBe(beatsIssue.title);+ expect(volumeIssues[0].beats).toContain('beat 1');+ expect(volumeIssues[0]).not.toHaveProperty('synopsis');+ expect(volumeIssues[1].title).toBe(synopsisIssue.title);+ expect(volumeIssues[1].synopsis).toBe('just a seed');+ expect(volumeIssues[1]).not.toHaveProperty('beats');++ expect(out.issues).toEqual([+ { severity: 'high', location: 'episode:1', problem: 'X', suggestion: 'Y' },+ ]);+ expect(out.seasonId).toBe(sea.id);+ });++ it('includes only the immediate-neighbor volumes (prior + next), excluding self', async () => {+ const s = await setupSeries();+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'L' } });+ const v1 = await seasonsSvc.createSeason(s.id, { title: 'V1', logline: 'one' });+ const v2 = await seasonsSvc.createSeason(s.id, { title: 'V2', logline: 'two', endingHook: 'hook2' });+ const v3 = await seasonsSvc.createSeason(s.id, { title: 'V3', logline: 'three' });+ const v4 = await seasonsSvc.createSeason(s.id, { title: 'V4', logline: 'four' });++ stageRunnerSpy = vi.fn(async () => ({+ content: { issues: [] }, runId: 'r', providerId: 'p', model: 'm',+ }));+ // Verifying the middle volume should expose V2 (prior) + V4 (next), never V1 or V3 itself.+ await planner.verifyVolume(s.id, v3.id);+ const ctx = stageRunnerSpy.mock.calls[0][1];+ const neighbors = JSON.parse(ctx.neighborsJson);+ expect(neighbors.map((n) => n.position)).toEqual(['prior', 'next']);+ expect(neighbors[0].title).toBe('V2');+ expect(neighbors[0].endingHook).toBe('hook2');+ expect(neighbors[1].title).toBe('V4');+ expect(neighbors.find((n) => n.title === 'V3')).toBeUndefined();+ expect(neighbors.find((n) => n.title === 'V1')).toBeUndefined();++ // First volume has no prior, only next.+ stageRunnerSpy.mockClear();+ stageRunnerSpy.mockImplementation(async () => ({ content: { issues: [] }, runId: 'r', providerId: 'p', model: 'm' }));+ await planner.verifyVolume(s.id, v1.id);+ const firstNeighbors = JSON.parse(stageRunnerSpy.mock.calls[0][1].neighborsJson);+ expect(firstNeighbors.map((n) => n.position)).toEqual(['next']);++ // Last volume has no next, only prior.+ stageRunnerSpy.mockClear();+ stageRunnerSpy.mockImplementation(async () => ({ content: { issues: [] }, runId: 'r', providerId: 'p', model: 'm' }));+ await planner.verifyVolume(s.id, v4.id);+ const lastNeighbors = JSON.parse(stageRunnerSpy.mock.calls[0][1].neighborsJson);+ expect(lastNeighbors.map((n) => n.position)).toEqual(['prior']);+ });++ it('returns empty issues for a clean volume + drops malformed entries', async () => {+ const s = await setupSeries();+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'L' } });+ const sea = await seasonsSvc.createSeason(s.id, { title: 'V', logline: 'l' });+ stageRunnerSpy = vi.fn(async () => ({+ content: {+ issues: [+ { problem: '' }, // dropped+ { severity: 'low', problem: 'real but tiny' }, // kept+ 'not an object', // dropped+ ],+ },+ runId: 'r', providerId: 'p', model: 'm',+ }));+ const out = await planner.verifyVolume(s.id, sea.id);+ expect(out.issues.map((i) => i.problem)).toEqual(['real but tiny']);+ });+});+describe('arcPlanner — resolveVerifyIssues', () => {beforeEach(() => {fileStore.clear();