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

pipeline: derive arc/bible from manuscript + manuscript-completeness editor pass

[._.]/ Adam Eivy6f95ed518cda
diff --git a/client/src/components/pipeline/ArcCanvas.jsx b/client/src/components/pipeline/ArcCanvas.jsx
index 5925c46e89..75899f0159 100644
--- a/client/src/components/pipeline/ArcCanvas.jsx
+++ b/client/src/components/pipeline/ArcCanvas.jsx
@@ -28,7 +28,7 @@ import { Link } from 'react-router-dom';
import {
Plus, Trash2, Loader2, Sparkles, ShieldCheck, ChevronRight, ChevronDown,
ChevronsUpDown, AlertCircle, Wand2, Info, ListChecks, X, Lock, Unlock,
- ImageIcon, Layers, FileDown, BookOpen, ChartSpline,
+ ImageIcon, Layers, FileDown, BookOpen, ChartSpline, FileSearch, BookText,
} from 'lucide-react';
import toast from '../ui/Toast';
import { timeAgo } from '../../utils/formatters';
@@ -41,6 +41,8 @@ import {
generatePipelineArcOverview, generatePipelineSeasonEpisodes, verifyPipelineArc,
verifyPipelineVolume,
resolvePipelineArcIssues,
+ derivePipelineArcFromManuscript, commitPipelineArcFromManuscript,
+ analyzePipelineManuscriptCompleteness,
listPipelineIssues, updatePipelineSeries, setPipelineArcFieldLock,
startPipelineVolumeBeats, cancelPipelineVolumeBeats,
generatePipelineVolumeCover, generatePipelineVolumeBackCover,
@@ -518,8 +520,12 @@ export function ArcRoadmapChart({ points }) {
function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {
const arc = series.arc;
const arcLocked = !!series.locked?.arc;
- const [running, setRunning] = useState(null); // 'generate' | 'verify' | 'resolve' | null
+ const [running, setRunning] = useState(null); // 'generate' | 'verify' | 'resolve' | 'derive' | 'derive-commit' | 'completeness' | null
const [verifyIssues, setVerifyIssues] = useState(null);
+ // Derive-from-manuscript preview (null until the LLM proposal lands) and the
+ // categorized "finish the draft" findings.
+ const [derivePreview, setDerivePreview] = useState(null);
+ const [completeness, setCompleteness] = useState(null);
// Which finding indexes have an in-flight per-finding resolve. Lets the row
// show its own spinner without blocking the rest of the page.
const [resolvingIdx, setResolvingIdx] = useState(new Set());
@@ -631,6 +637,62 @@ function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {
}
};
+ // Back-derive arc + bible + a single-volume restructure from the issue
+ // manuscripts. Read-only — opens the preview the user reviews/edits before
+ // committing.
+ const runDerive = async () => {
+ setRunning('derive');
+ const result = await withFlush(() =>
+ derivePipelineArcFromManuscript(series.id, llmOverride).catch((err) => {
+ toast.error(err.message || 'Failed to derive from manuscript');
+ return null;
+ }),
+ );
+ setRunning(null);
+ if (!result) return;
+ setDerivePreview(result);
+ };
+
+ // Apply the (edited) derive preview. No LLM re-run — the confirmed proposal
+ // is sent verbatim. Refreshes series + issues so the volume collapse + issue
+ // reassignment + bible fill show immediately.
+ const runDeriveCommit = async (proposal) => {
+ setRunning('derive-commit');
+ const result = await commitPipelineArcFromManuscript(series.id, proposal).catch((err) => {
+ toast.error(err.message || 'Failed to apply');
+ return null;
+ });
+ setRunning(null);
+ if (!result) return;
+ if (result.series) onSeriesUpdate(result.series);
+ if (onIssuesUpdate) {
+ const refreshed = await listPipelineIssues(series.id).catch(() => null);
+ if (refreshed) onIssuesUpdate(refreshed);
+ }
+ setDerivePreview(null);
+ toast.success(`Arc, bible, and a single volume of ${result.issueCount} issue${result.issueCount === 1 ? '' : 's'} derived from the manuscript`);
+ };
+
+ // "Finish the draft" — manuscript-completeness editor pass. Advisory; no
+ // auto-resolve (the suggestions guide manual authoring).
+ const runCompleteness = async () => {
+ setRunning('completeness');
+ const result = await withFlush(() =>
+ analyzePipelineManuscriptCompleteness(series.id, llmOverride).catch((err) => {
+ toast.error(err.message || 'Failed to analyze manuscript');
+ return null;
+ }),
+ );
+ setRunning(null);
+ if (!result) return;
+ setCompleteness(result.issues || []);
+ if ((result.issues || []).length === 0) {
+ toast.success('Manuscript looks complete — no gaps found');
+ } else {
+ toast(`Found ${result.issues.length} suggestion${result.issues.length === 1 ? '' : 's'} to finish the draft`);
+ }
+ };
+
// A picked `shape` alone counts as an "arc" record (it's an explicit
// narrative-design decision the sanitizer preserves), but it isn't a
// generated arc — the LLM hasn't written anything yet. Use the
@@ -702,6 +764,28 @@ function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {
<VerifyScopeTooltip scope={VERIFY_ARC_SCOPE} id="verify-arc-scope-tooltip" />
</div>
) : null}
+ <button
+ type="button"
+ onClick={runDerive}
+ disabled={!!running || arcLocked}
+ title={arcLocked
+ ? 'Arc is locked — unlock to derive from the manuscript'
+ : 'Reconstruct the arc, bible, and a single-volume structure from the issue scripts you already wrote'}
+ 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"
+ >
+ {running === 'derive' ? <Loader2 size={14} className="animate-spin" /> : <BookText size={14} />}
+ Derive from manuscript
+ </button>
+ <button
+ type="button"
+ onClick={runCompleteness}
+ disabled={!!running}
+ title="Read the actual drafted script and suggest what's missing to finish the draft — gaps in content, arc, and character development"
+ 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"
+ >
+ {running === 'completeness' ? <Loader2 size={14} className="animate-spin" /> : <FileSearch size={14} />}
+ Finish the draft
+ </button>
</div>
</div>
@@ -753,10 +837,219 @@ function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {
lockedNote={arcLocked ? 'Arc is locked — unlock above to enable auto-resolve.' : null}
/>
) : null}
+
+ {derivePreview ? (
+ <DeriveFromManuscriptPreview
+ preview={derivePreview}
+ committing={running === 'derive-commit'}
+ onCancel={() => setDerivePreview(null)}
+ onConfirm={runDeriveCommit}
+ />
+ ) : null}
+
+ {completeness ? (
+ <CompletenessResults
+ issues={completeness}
+ onDismiss={() => setCompleteness(null)}
+ />
+ ) : null}
</section>
);
}
+// Field-count guard for derived synopsis textareas — mirrors the server caps so
+// the user isn't surprised by a 400 on commit.
+const DERIVE_SYNOPSIS_MAX = 8000;
+const DERIVE_TITLE_MAX = 300;
+
+// Review/edit panel for the derive-from-manuscript proposal. The arc + bible
+// fields and the single-volume title/synopsis are editable; each existing issue
+// gets an editable title + synopsis (pre-filled from the derived seasons). On
+// confirm the edited proposal is sent — the LLM is NOT re-run.
+function DeriveFromManuscriptPreview({ preview, committing, onCancel, onConfirm }) {
+ const [arc, setArc] = useState(() => ({
+ logline: preview.arc?.logline || '',
+ summary: preview.arc?.summary || '',
+ protagonistArc: preview.arc?.protagonistArc || '',
+ themes: Array.isArray(preview.arc?.themes) ? preview.arc.themes : [],
+ shape: preview.arc?.shape ?? null,
+ }));
+ const [bible, setBible] = useState(() => ({
+ logline: preview.bible?.logline || '',
+ premise: preview.bible?.premise || '',
+ issueCountTarget: preview.bible?.issueCountTarget ?? (preview.issues?.length || 0),
+ }));
+ const [volume, setVolume] = useState(() => ({
+ title: preview.volume?.title || '',
+ logline: preview.volume?.logline || '',
+ synopsis: preview.volume?.synopsis || '',
+ }));
+ // Per-issue editable rows. Default synopsis = the derived suggestion, falling
+ // back to whatever synopsis the issue already carried.
+ const [issues, setIssues] = useState(() =>
+ (preview.issues || []).map((iss) => ({
+ id: iss.id,
+ number: iss.number,
+ title: iss.title || '',
+ synopsis: iss.synopsisSuggestion || iss.currentSynopsis || '',
+ ideaLocked: !!iss.ideaLocked,
+ })),
+ );
+
+ const setIssueField = (id, field, value) =>
+ setIssues((prev) => prev.map((it) => (it.id === id ? { ...it, [field]: value } : it)));
+
+ const confirm = () => {
+ onConfirm({
+ arc,
+ bible,
+ volume,
+ issues: issues.map((it) => ({
+ id: it.id,
+ title: it.title.slice(0, DERIVE_TITLE_MAX),
+ synopsis: it.ideaLocked ? '' : it.synopsis.slice(0, DERIVE_SYNOPSIS_MAX),
+ })),
+ });
+ };
+
+ const inputCls = 'w-full bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white focus:border-port-accent/50 outline-none';
+
+ return (
+ <div className="bg-port-bg border border-port-accent/30 rounded-lg p-3 space-y-3">
+ <div className="flex items-center justify-between">
+ <h3 className="text-sm font-medium text-white flex items-center gap-1.5">
+ <BookText size={14} className="text-port-accent" />
+ Derived from manuscript — review before applying
+ </h3>
+ <button type="button" onClick={onCancel} disabled={committing} className="text-gray-500 hover:text-white disabled:opacity-40">
+ <X size={16} />
+ </button>
+ </div>
+ <p className="text-xs text-gray-400">
+ Applying collapses the series into <strong>one volume</strong> holding all {issues.length} issue{issues.length === 1 ? '' : 's'} as chapters/acts,
+ fills the bible, and seeds each issue&apos;s synopsis. Your verbatim issue scripts are <strong>not</strong> changed.
+ </p>
+
+ <div className="grid gap-3 @md:grid-cols-2">
+ <label className="block space-y-1">
+ <span className="text-[11px] uppercase tracking-wider text-gray-500">Series logline</span>
+ <input className={inputCls} value={bible.logline} maxLength={500}
+ onChange={(e) => { setBible((b) => ({ ...b, logline: e.target.value })); setArc((a) => ({ ...a, logline: e.target.value })); }} />
+ </label>
+ <label className="block space-y-1">
+ <span className="text-[11px] uppercase tracking-wider text-gray-500">Issue count target</span>
+ <input type="number" min={0} className={inputCls} value={bible.issueCountTarget}
+ onChange={(e) => setBible((b) => ({ ...b, issueCountTarget: parseInt(e.target.value, 10) || 0 }))} />
+ </label>
+ </div>
+ <label className="block space-y-1">
+ <span className="text-[11px] uppercase tracking-wider text-gray-500">Premise</span>
+ <textarea className={`${inputCls} resize-y`} rows={3} value={bible.premise} maxLength={8000}
+ onChange={(e) => { setBible((b) => ({ ...b, premise: e.target.value })); setArc((a) => ({ ...a, summary: e.target.value })); }} />
+ </label>
+ <label className="block space-y-1">
+ <span className="text-[11px] uppercase tracking-wider text-gray-500">Protagonist arc</span>
+ <textarea className={`${inputCls} resize-y`} rows={2} value={arc.protagonistArc} maxLength={8000}
+ onChange={(e) => setArc((a) => ({ ...a, protagonistArc: e.target.value }))} />
+ </label>
+
+ <div className="border-t border-port-border pt-2 space-y-2">
+ <span className="text-[11px] uppercase tracking-wider text-gray-500">Volume</span>
+ <input className={inputCls} value={volume.title} maxLength={DERIVE_TITLE_MAX} placeholder="Volume title"
+ onChange={(e) => setVolume((v) => ({ ...v, title: e.target.value }))} />
+ </div>
+
+ <div className="border-t border-port-border pt-2 space-y-2">
+ <span className="text-[11px] uppercase tracking-wider text-gray-500">Issues (acts / chapters)</span>
+ {issues.map((it) => (
+ <div key={it.id} className="bg-port-card border border-port-border rounded p-2 space-y-1">
+ <div className="flex items-center gap-2">
+ <span className="text-[11px] text-gray-500 shrink-0">#{it.number}</span>
+ <input className={inputCls} value={it.title} maxLength={DERIVE_TITLE_MAX} placeholder="Issue title"
+ onChange={(e) => setIssueField(it.id, 'title', e.target.value)} />
+ </div>
+ <textarea
+ className={`${inputCls} resize-y`}
+ rows={2}
+ value={it.synopsis}
+ maxLength={DERIVE_SYNOPSIS_MAX}
+ placeholder={it.ideaLocked ? 'Synopsis locked on this issue — left unchanged' : 'Issue synopsis (seeds idea.input so Verify Arc can read it)'}
+ disabled={it.ideaLocked}
+ onChange={(e) => setIssueField(it.id, 'synopsis', e.target.value)}
+ />
+ </div>
+ ))}
+ </div>
+
+ <div className="flex items-center gap-2 pt-1">
+ <button type="button" onClick={confirm} disabled={committing}
+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded text-sm font-medium bg-port-accent/20 text-port-accent border border-port-accent/40 hover:bg-port-accent/30 disabled:opacity-40">
+ {committing ? <Loader2 size={14} className="animate-spin" /> : <BookText size={14} />}
+ Apply — collapse to one volume
+ </button>
+ <button type="button" onClick={onCancel} disabled={committing} className="px-3 py-1.5 rounded text-sm text-gray-400 hover:text-white">
+ Cancel
+ </button>
+ </div>
+ </div>
+ );
+}
+
+// Human-readable labels for the manuscript-completeness categories.
+const COMPLETENESS_CATEGORY_LABELS = {
+ 'missing-content': 'Missing content',
+ 'arc-gap': 'Arc gaps',
+ 'character-gap': 'Character development',
+ pacing: 'Pacing',
+ continuity: 'Continuity',
+ other: 'Other',
+};
+const COMPLETENESS_CATEGORY_ORDER = ['missing-content', 'arc-gap', 'character-gap', 'pacing', 'continuity', 'other'];
+
+// Advisory findings panel for "finish the draft" — grouped by category, no
+// resolve buttons (the suggestions guide manual authoring, not an LLM rewrite).
+function CompletenessResults({ issues, onDismiss }) {
+ const grouped = useMemo(() => {
+ const byCat = new Map();
+ for (const iss of issues) {
+ const cat = COMPLETENESS_CATEGORY_LABELS[iss.category] ? iss.category : 'other';
+ if (!byCat.has(cat)) byCat.set(cat, []);
+ byCat.get(cat).push(iss);
+ }
+ return COMPLETENESS_CATEGORY_ORDER.filter((c) => byCat.has(c)).map((c) => [c, byCat.get(c)]);
+ }, [issues]);
+
+ return (
+ <div className="bg-port-bg border border-port-border rounded-lg p-3 space-y-2">
+ <div className="flex items-center justify-between">
+ <h3 className="text-sm font-medium text-white flex items-center gap-1.5">
+ <FileSearch size={14} className="text-port-accent" />
+ Finish the draft — {issues.length} suggestion{issues.length === 1 ? '' : 's'}
+ </h3>
+ <button type="button" onClick={onDismiss} className="text-gray-500 hover:text-white"><X size={16} /></button>
+ </div>
+ {issues.length === 0 ? (
+ <p className="text-xs text-gray-400">The manuscript reads as complete — no gaps found.</p>
+ ) : (
+ grouped.map(([cat, list]) => (
+ <div key={cat} className="space-y-1">
+ <span className="text-[11px] uppercase tracking-wider text-gray-500">{COMPLETENESS_CATEGORY_LABELS[cat]} ({list.length})</span>
+ <ul className="space-y-1">
+ {list.map((iss, i) => (
+ <li key={i} className={`text-xs p-2 rounded border ${SEVERITY_COLORS[iss.severity] || SEVERITY_COLORS.medium}`}>
+ {iss.location ? <span className="font-medium">{iss.location}: </span> : null}
+ <span>{iss.problem}</span>
+ {iss.suggestion ? <p className="mt-1 text-gray-300"><span className="opacity-70">Suggestion: </span>{iss.suggestion}</p> : null}
+ </li>
+ ))}
+ </ul>
+ </div>
+ ))
+ )}
+ </div>
+ );
+}
+
// Theme pill limits — mirror server/lib/storyArc.js ARC_LIMITS.
const THEME_MAX = 100;
const THEMES_PER_ARC_MAX = 20;
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index a9bf853dc6..af39ec68dc 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -391,6 +391,33 @@ export const resolvePipelineArcIssues = (seriesId, { findings, providerOverride,
body: JSON.stringify({ findings, providerOverride, modelOverride }),
});
+// Back-derive arc + bible + a single-volume restructure from the series' EXISTING
+// issue manuscripts. Read-only preview the UI shows for review/edit. Returns
+// { arc, volume, bible, issues, derivedSeasons, runId, providerId, model }.
+export const derivePipelineArcFromManuscript = (seriesId, { providerOverride, modelOverride } = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/arc/derive-from-manuscript`, {
+ method: 'POST',
+ body: JSON.stringify({ providerOverride, modelOverride }),
+ });
+
+// Apply the (edited) derive preview — writes bible, collapses to one volume,
+// reassigns issues, seeds per-issue synopses. No LLM re-run. Pass the confirmed
+// { arc, bible, volume, issues } proposal. Returns { series, volumeId, issueCount }.
+export const commitPipelineArcFromManuscript = (seriesId, proposal = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/arc/derive-from-manuscript/commit`, {
+ method: 'POST',
+ body: JSON.stringify(proposal),
+ });
+
+// Manuscript-completeness ("finish the draft") editor pass — reads the actual
+// drafted script and returns categorized { severity, category, location,
+// problem, suggestion } findings. Advisory; no auto-resolve. Empty = complete.
+export const analyzePipelineManuscriptCompleteness = (seriesId, { providerOverride, modelOverride } = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/manuscript/completeness`, {
+ method: 'POST',
+ body: JSON.stringify({ providerOverride, modelOverride }),
+ });
+
// ---- Volume beat-sheet bulk generator ----
// Sequential idea-stage run across every issue in a volume. `mode` is
// 'skip-existing' (default) or 'regenerate-all'. Returns
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index 6d4af29598..b7f05cb1ea 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -284,6 +284,13 @@
"returnsJson": true,
"variables": []
},
+ "pipeline-manuscript-completeness": {
+ "name": "Pipeline — Manuscript Completeness",
+ "description": "Developmental editor pass over the ACTUAL drafted manuscript (comic script / prose / teleplay across all issues), not synopses. Surfaces what's missing to FINISH a near-complete draft: missing-content (beats/pages/scenes), arc-gap (themes/protagonist turns the draft doesn't yet deliver), character-gap (under-developed cast), pacing, and continuity. Returns categorized { severity, category, location, problem, suggestion } findings — empty list means complete.",
+ "model": "heavy",
+ "returnsJson": true,
+ "variables": []
+ },
"pipeline-volume-cover-concepts": {
"name": "Pipeline — Volume Cover Concepts",
"description": "Generate FRONT and BACK cover-art concepts for one volume (season) of a comic series. Returns a {coverConcept, backCoverConcept} JSON pair — pure scene descriptions for the image-gen renderer (no masthead, logo, or typography). Lightweight per-season call; may seed the cover and/or backCover script slots when they're blank, and never clobbers a user edit.",
diff --git a/data.reference/prompts/stages/pipeline-manuscript-completeness.md b/data.reference/prompts/stages/pipeline-manuscript-completeness.md
new file mode 100644
index 0000000000..4ca655947d
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-manuscript-completeness.md
@@ -0,0 +1,97 @@
+# Pipeline — Manuscript Completeness
+
+You are a developmental editor reading a **near-complete but unfinished** comic / graphic-novel manuscript. Unlike a continuity pass over a synopsis, you are reading the **actual drafted script** below. The author's goal is to *round out and finish* the draft: your job is to identify what is **missing or under-developed** so the whole story, arc, and cast feel complete before the production pipeline begins.
+
+This IS a developmental critique — but a focused one. Do not rewrite the author's voice or propose a different story. Find the gaps in the story they are already telling, and propose the smallest concrete additions that close them.
+
+## Series bible
+
+- **Name:** {{series.name}}
+- **Logline:** {{series.logline}}
+- **Premise:**
+
+```
+{{series.premise}}
+```
+
+## Intended arc
+
+- **Whole-story logline:** {{arc.logline}}
+- **Themes:** {{arc.themesCsv}}
+- **Protagonist arc:**
+
+```
+{{arc.protagonistArc}}
+```
+
+- **Arc summary:**
+
+```
+{{arc.summary}}
+```
+
+## Story shape (Vonnegut)
+
+{{{shapeGuidance}}}
+
+{{#hasLinkedWorld}}
+## Linked World — canonical entities
+
+The series is grounded in the world **{{worldName}}**. Reference characters/places/objects by their canonical names when flagging gaps.
+
+```
+{{worldCanonText}}
+```
+{{/hasLinkedWorld}}
+
+## Known cast (canon characters)
+
+```json
+{{existingCharactersJson}}
+```
+
+## The drafted manuscript
+
+Each issue is delimited by a `# Issue N` header. The script may use page/panel markers, prose, or screenplay form — read whichever it is.
+
+```
+{{manuscript}}
+```
+
+## What to look for
+
+Read the manuscript end to end against the intended arc, then surface gaps in these categories:
+
+1. **`missing-content`** — Beats, pages, or scenes the story needs but doesn't have: an abrupt cut where a transition belongs, a payoff whose setup never appears (or a setup whose payoff never appears), a climax that arrives without the connective tissue to earn it, an ending that stops rather than resolves.
+2. **`arc-gap`** — Places where the drafted material doesn't yet deliver the **intended arc** above: a theme named in the bible that the manuscript never dramatizes, a protagonist-arc turn (e.g. the moment the hero changes) that is asserted but never shown, the story shape's expected fortune swing that the draft skips.
+3. **`character-gap`** — Characters who are under-developed for their role: a major character with no interiority or motivation on the page, a relationship the plot depends on that is never built, a cast member introduced and then dropped, an antagonist with no comprehensible want.
+4. **`pacing`** — Sections that are rushed or that drag relative to their weight in the arc (a pivotal turn given one panel; a minor errand given ten pages).
+5. **`continuity`** — Concrete contradictions in the drafted text (a prop/wound/location/time-of-day that doesn't track between panels or issues).
+
+Prioritize what actually keeps the draft from being *finished*. A 90%-done manuscript usually has a handful of real holes — find those, not a hundred nitpicks.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary. Each `issues[]` entry must be **actionable**: name where in the manuscript the gap is (issue + page/scene when you can), name what's missing, and propose the smallest concrete addition that closes it.
+
+```json
+{
+ "issues": [
+ {
+ "severity": "high",
+ "category": "missing-content",
+ "location": "Issue 2, around the castle-escape page",
+ "problem": "string (what is missing or under-developed, with specific evidence from the script)",
+ "suggestion": "string (the smallest concrete addition — a beat, a page, a scene, a line of motivation — that closes the gap)"
+ }
+ ]
+}
+```
+
+- `category` must be one of `missing-content` / `arc-gap` / `character-gap` / `pacing` / `continuity`.
+- `severity` must be one of `high` / `medium` / `low`:
+ - **`high`** — the draft cannot be considered finished without this (a missing climax, an unresolved central arc).
+ - **`medium`** — the story works but feels incomplete or thin here (an under-built relationship, a skipped transition).
+ - **`low`** — an opportunity to enrich (a theme that could land harder, a minor character that could carry more).
+
+Return `{ "issues": [] }` only if the manuscript is genuinely complete. Do NOT pad with low-confidence entries.
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index fb908a15f1..bbb88acb81 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -554,6 +554,38 @@ const arcResolveSchema = z.object({
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(),
+});
+
+// Manuscript-completeness ("finish the draft") editor pass — override shape only.
+const manuscriptCompletenessSchema = z.object(providerOverrideShape);
+
const autoRunSchema = z.object({
providerId: z.string().trim().max(80).optional(),
model: z.string().trim().max(200).optional(),
@@ -1235,6 +1267,37 @@ router.post('/series/:id/arc/resolve-issues', asyncHandler(async (req, res) => {
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);
+}));
+
+// Manuscript-completeness editor pass — categorized "finish the draft"
+// suggestions read from the actual drafted script (not synopses). Advisory.
+router.post('/series/:id/manuscript/completeness', asyncHandler(async (req, res) => {
+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const body = validateRequest(manuscriptCompletenessSchema, req.body ?? {});
+ const result = await arcPlanner.analyzeManuscriptCompleteness(req.params.id, body)
+ .catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
// =====================
// Volume (season) covers — front + back illustration on the season record.
// Stored on series.seasons[].cover / .backCover, sanitized by sanitizeSeason,
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
index b70f04db96..0a05f3f403 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -45,6 +45,9 @@ let arcGenerateSpy;
let seasonEpisodesSpy;
let arcVerifySpy;
let volumeVerifySpy;
+let deriveSpy;
+let deriveCommitSpy;
+let completenessSpy;
vi.mock('../services/pipeline/arcPlanner.js', async () => {
const actual = await vi.importActual('../services/pipeline/arcPlanner.js');
return {
@@ -53,6 +56,9 @@ vi.mock('../services/pipeline/arcPlanner.js', async () => {
generateSeasonEpisodes: vi.fn((...args) => seasonEpisodesSpy(...args)),
verifyArc: vi.fn((...args) => arcVerifySpy(...args)),
verifyVolume: vi.fn((...args) => volumeVerifySpy(...args)),
+ deriveFromManuscript: vi.fn((...args) => deriveSpy(...args)),
+ commitDerivedManuscript: vi.fn((...args) => deriveCommitSpy(...args)),
+ analyzeManuscriptCompleteness: vi.fn((...args) => completenessSpy(...args)),
};
});
@@ -1973,6 +1979,50 @@ describe('pipeline routes', () => {
expect(volumeVerifySpy).toHaveBeenCalledWith(ser.body.id, 'sea-fake', expect.objectContaining({ providerOverride: 'anthropic' }));
});
+ it('POST /series/:id/arc/derive-from-manuscript returns the preview', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
+ deriveSpy = vi.fn(async () => ({
+ arc: { logline: 'L' }, volume: { title: 'V' }, bible: { logline: 'L', premise: 'P', issueCountTarget: 3 },
+ issues: [{ id: 'i1', number: 1, title: 'One', synopsisSuggestion: 'syn' }],
+ runId: 'rd', providerId: 'p', model: 'm',
+ }));
+ const r = await request(app).post(`/api/pipeline/series/${ser.body.id}/arc/derive-from-manuscript`).send({});
+ expect(r.status).toBe(200);
+ expect(r.body.volume.title).toBe('V');
+ expect(r.body.issues).toHaveLength(1);
+ expect(deriveSpy).toHaveBeenCalledWith(ser.body.id, expect.any(Object));
+ });
+
+ it('POST /series/:id/arc/derive-from-manuscript/commit forwards the edited proposal', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
+ deriveCommitSpy = vi.fn(async () => ({ series: { id: ser.body.id, seasons: [{ id: 'sea-1' }] }, volumeId: 'sea-1', issueCount: 3 }));
+ const proposal = {
+ arc: { logline: 'L', summary: 'S' },
+ bible: { logline: 'L', premise: 'S', issueCountTarget: 3 },
+ volume: { title: 'The Giant' },
+ issues: [{ id: 'i1', title: 'Act One', synopsis: 'syn one' }],
+ };
+ const r = await request(app).post(`/api/pipeline/series/${ser.body.id}/arc/derive-from-manuscript/commit`).send(proposal);
+ expect(r.status).toBe(200);
+ expect(r.body.issueCount).toBe(3);
+ expect(deriveCommitSpy).toHaveBeenCalledWith(ser.body.id, expect.objectContaining({ volume: { title: 'The Giant' } }));
+ });
+
+ it('POST /series/:id/manuscript/completeness returns categorized findings', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
+ completenessSpy = vi.fn(async () => ({
+ issues: [{ severity: 'high', category: 'missing-content', location: 'Issue 2', problem: 'no climax', suggestion: 'add one' }],
+ runId: 'rc', providerId: 'p', model: 'm',
+ }));
+ const r = await request(app).post(`/api/pipeline/series/${ser.body.id}/manuscript/completeness`).send({});
+ expect(r.status).toBe(200);
+ expect(r.body.issues[0].category).toBe('missing-content');
+ expect(completenessSpy).toHaveBeenCalledWith(ser.body.id, expect.any(Object));
+ });
+
describe('audio stage routes', () => {
async function seedIssueWithStoryboards(app) {
const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.js
index 4cc73c0a86..1189ed8b0e 100644
--- a/server/services/pipeline/arcPlanner.js
+++ b/server/services/pipeline/arcPlanner.js
@@ -23,7 +23,7 @@ import { runStagedLLM } from '../../lib/stageRunner.js';
import { ServerError } from '../../lib/errorHandler.js';
import { stripAnsi } from '../../lib/ansiStrip.js';
import { getSeries, updateSeries, updateSeasonOnSeries, ARC_LOCKABLE_FIELDS } from './series.js';
-import { listIssues, updateIssue, recomputeIssueNumbersForSeries, getIssue, updateStageWithLatest, assertStageUnlocked } from './issues.js';
+import { listIssues, updateIssue, recomputeIssueNumbersForSeries, getIssue, updateStage, updateStageWithLatest, assertStageUnlocked } from './issues.js';
import { emitRecordUpdated, withReexportSuppressed } from '../sharing/recordEvents.js';
import { getSeason } from './seasons.js';
import {
@@ -154,6 +154,41 @@ async function resolveWorldContext(series, preloaded) {
export const compareIssuesByPosition = (a, b) =>
(a.arcPosition ?? 9999) - (b.arcPosition ?? 9999) || (a.number || 0) - (b.number || 0);
+// Cap on the concatenated manuscript fed to back-derivation passes. Mirrors the
+// importer's source ceiling intent — large enough for a full graphic novel,
+// bounded so a runaway corpus can't blow the prompt budget.
+const BACKFILL_SOURCE_MAX = 200_000;
+
+// Local copy of textStages' stageContentOf. Inlined (not imported) because
+// textStages.js imports from THIS module (compareIssuesByPosition,
+// NO_LINKED_UNIVERSE_PLACEHOLDER) — importing back would create a cycle whose
+// binding is undefined at module-eval time. The one-liner is stable.
+const stageTextOf = (stage) => (stage?.input?.trim() || stage?.output?.trim() || '');
+
+/**
+ * Concatenate the richest authored artifact per issue (comicScript → teleplay →
+ * prose → idea) into one corpus an upstream pass can back-derive FROM — the
+ * "started from a finished manuscript" case. Issues are ordered by arcPosition
+ * so the corpus reads in story order. Returns '' when no issue has any text.
+ *
+ * Shared by `deriveFromManuscript` here and the Story Builder's plotArc/idea
+ * backfill (storyBuilder.js) so both see the identical corpus shape.
+ */
+export async function collectIssueSourceText(seriesId) {
+ if (!seriesId) return '';
+ const issues = (await listIssues({ seriesId }).catch(() => [])).sort(compareIssuesByPosition);
+ const parts = [];
+ for (const iss of issues) {
+ const st = iss.stages || {};
+ const pick = ['comicScript', 'teleplay', 'prose', 'idea']
+ .map((sid) => ({ sid, content: stageTextOf(st[sid]) }))
+ .find((x) => x.content);
+ if (!pick) continue;
+ parts.push(`# Issue ${iss.number}${iss.title ? ` — ${iss.title}` : ''} (${pick.sid})\n\n${pick.content}`);
+ }
+ return parts.join('\n\n---\n\n').slice(0, BACKFILL_SOURCE_MAX);
+}
+
// 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.
@@ -352,6 +387,241 @@ export async function generateArcFromSource(seriesId, {
return { arc, seasons, raw: content, runId, providerId, model };
}
+// Render one derived season's logline + synopsis into a per-issue synopsis seed
+// the preview pre-fills `idea.input` with. Empty string when the season carries
+// no usable text (the caller leaves the issue's existing synopsis untouched).
+function issueSynopsisFromSeason(season) {
+ if (!season) return '';
+ return [season.logline, season.synopsis].map((s) => (typeof s === 'string' ? s.trim() : '')).filter(Boolean).join('\n\n');
+}
+
+/**
+ * Back-derive an arc + bible + a single-volume restructure proposal from the
+ * series' EXISTING issue manuscripts — the "I imported a finished graphic novel,
+ * now reconstruct its spine" path. Read-only: writes nothing. Returns a preview
+ * the UI shows for review/edit before `commitDerivedManuscript` applies it.
+ *
+ * The proposal is deliberately single-volume (a graphic novel is one book): the
+ * derived multi-season `seasons` from `generateArcFromSource` are flattened into
+ * per-issue synopsis suggestions (zipped by story order), so the user's "the
+ * volume descriptions read better as issue descriptions" intuition is the
+ * default. `volume` is the single book; `issues[]` maps each existing issue to a
+ * proposed title + synopsis the user can edit.
+ */
+export async function deriveFromManuscript(seriesId, { providerOverride, modelOverride } = {}) {
+ const series = await getSeries(seriesId);
+ if (series.locked?.arc === true) {
+ throw makeErr('Arc is locked — unlock it on the Arc Canvas before deriving from the manuscript', ERR_VALIDATION);
+ }
+ const sourceText = await collectIssueSourceText(seriesId);
+ if (!sourceText) {
+ throw makeErr(
+ 'No issue manuscript to derive from — write a comic script, prose, or teleplay on at least one issue first',
+ ERR_VALIDATION,
+ );
+ }
+ const { arc, seasons, raw, runId, providerId, model } = await generateArcFromSource(seriesId, {
+ sourceText, providerOverride, modelOverride,
+ });
+ const issues = (await listIssues({ seriesId })).sort(compareIssuesByPosition);
+ const issueMapping = issues.map((iss, i) => ({
+ id: iss.id,
+ number: iss.number,
+ title: iss.title || `Issue ${i + 1}`,
+ currentSynopsis: (iss.stages?.idea?.input || '').trim(),
+ // Zip the derived seasons onto issues in story order; extra seasons (more
+ // seasons than issues) fall off the end — the user can fold them into the
+ // last issue's synopsis in the preview if they matter.
+ synopsisSuggestion: issueSynopsisFromSeason(seasons[i]),
+ ideaLocked: iss.stages?.idea?.locked === true,
+ }));
+ return {
+ arc,
+ // The single book the issues comprise. Title defaults to the series name;
+ // logline/synopsis seed from the derived arc.
+ volume: {
+ title: series.name || seasons[0]?.title || 'Volume 1',
+ logline: arc?.logline || '',
+ synopsis: arc?.summary || '',
+ },
+ bible: {
+ logline: arc?.logline || series.logline || '',
+ premise: arc?.summary || series.premise || '',
+ issueCountTarget: issues.length,
+ },
+ issues: issueMapping,
+ // Surface the raw derived seasons too so a future "keep as multi-volume"
+ // affordance can opt out of the flatten without re-running the LLM.
+ derivedSeasons: seasons,
+ runId,
+ providerId,
+ model,
+ };
+}
+
+// Seed one issue's `idea.input` synopsis (respecting the per-stage lock). Used
+// by the derive-commit to make Verify Arc — which reads `idea.input` — useful on
+// issues that only carried a verbatim comicScript before. Never touches
+// `idea.output` (beats) or the comicScript manuscript.
+async function seedIssueSynopsis(issueId, synopsis) {
+ const text = typeof synopsis === 'string' ? synopsis.trim() : '';
+ if (!text) return;
+ const iss = await getIssue(issueId).catch(() => null);
+ if (!iss || iss.stages?.idea?.locked === true) return;
+ const hasBeats = !!(iss.stages?.idea?.output || '').trim();
+ await updateStage(issueId, 'idea', {
+ input: text,
+ // Don't downgrade an issue that already has generated beats.
+ status: hasBeats ? (iss.stages?.idea?.status || 'edited') : 'empty',
+ });
+}
+
+/**
+ * Apply a (possibly user-edited) `deriveFromManuscript` preview: write the
+ * bible, collapse the series to ONE volume, reassign every issue onto it, and
+ * seed per-issue synopses. The verbatim issue scripts (comicScript/prose) are
+ * never touched — same contract as `resolveVerifyIssues`.
+ *
+ * The single volume reuses the lowest-numbered existing season's id when one
+ * exists (so issues already under it don't churn), and `commitSeasonsWithRemap`
+ * drops the rest while honoring arc/season locks. A follow-up sweep then pins
+ * EVERY issue onto the kept volume — covering both issues the remap routed to
+ * the ungrouped bucket and any that were already attached elsewhere.
+ */
+export async function commitDerivedManuscript(seriesId, { arc, bible, volume, issues = [] } = {}) {
+ const series = await getSeries(seriesId);
+ if (series.locked?.arc === true) {
+ throw makeErr('Arc is locked — unlock it on the Arc Canvas before applying', ERR_VALIDATION);
+ }
+
+ // 1) Bible — top-level series fields the Arc Canvas sidebar reads. These are
+ // not lock-gated individually (only `locked.arc` exists, checked above).
+ const biblePatch = {};
+ if (typeof bible?.logline === 'string') biblePatch.logline = bible.logline;
+ if (typeof bible?.premise === 'string') biblePatch.premise = bible.premise;
+ if (Number.isFinite(bible?.issueCountTarget)) biblePatch.issueCountTarget = bible.issueCountTarget;
+ if (Object.keys(biblePatch).length) await updateSeries(seriesId, biblePatch);
+
+ // 2) Build the single target volume, reusing the lowest-numbered existing
+ // season's id so its child issues don't need re-homing. sanitizeSeason
+ // mints a fresh sea-uuid when `id` is undefined (no seasons yet).
+ const existingSeasons = (Array.isArray(series.seasons) ? series.seasons : [])
+ .slice()
+ .sort((a, b) => (a.number || 0) - (b.number || 0));
+ const keep = existingSeasons[0] || null;
+ const existingIssues = await listIssues({ seriesId });
+ const targetSeason = sanitizeSeason({
+ id: keep?.id,
+ number: 1,
+ title: volume?.title || series.name || 'Volume 1',
+ logline: volume?.logline || '',
+ synopsis: volume?.synopsis || '',
+ episodeCountTarget: existingIssues.length,
+ status: keep?.status || 'draft',
+ locked: keep?.locked === true,
+ });
+
+ // 3) Persist arc + the single season (drops the others; honors locks +
+ // migrates orphans). Re-read first so we merge against the bible write.
+ const sanitizedArc = sanitizeArc({ ...(arc || {}), status: 'draft' });
+ const latest = await getSeries(seriesId);
+ await commitSeasonsWithRemap(latest, { arc: sanitizedArc, seasons: [targetSeason] });
+
+ // 4) Pin every issue onto the single volume and apply per-issue edits.
+ const editsById = new Map((Array.isArray(issues) ? issues : []).map((e) => [e.id, e]));
+ await withReexportSuppressed('series', seriesId, async () => {
+ for (const iss of existingIssues) {
+ if (iss.seasonId !== targetSeason.id) {
+ await updateIssue(iss.id, { seasonId: targetSeason.id }, { skipRenumber: true });
+ }
+ const edit = editsById.get(iss.id);
+ if (edit?.title && typeof edit.title === 'string' && edit.title.trim() && edit.title.trim() !== iss.title) {
+ await updateIssue(iss.id, { title: edit.title.trim() }, { skipRenumber: true });
+ }
+ if (edit?.synopsis) await seedIssueSynopsis(iss.id, edit.synopsis);
+ }
+ await recomputeIssueNumbersForSeries(seriesId);
+ });
+ emitRecordUpdated('series', seriesId);
+
+ const updated = await getSeries(seriesId);
+ return { series: updated, volumeId: targetSeason.id, issueCount: existingIssues.length };
+}
+
+// ── Manuscript completeness ("finish the draft") ──────────────────────────
+// Unlike verifyArc/verifyVolume (which read synopsis/beats from idea.input /
+// idea.output), this pass reads the ACTUAL drafted manuscript (comicScript /
+// prose / teleplay) so it can flag what's missing to FINISH a near-complete
+// draft: gaps in content, holes in the arc, and under-developed characters.
+
+// Findings carry a `category` on top of the verify shape so the UI can group
+// them. Unknown categories collapse to 'other' rather than being dropped.
+const COMPLETENESS_CATEGORIES = new Set([
+ 'missing-content', 'arc-gap', 'character-gap', 'pacing', 'continuity', 'other',
+]);
+
+function shapeCompletenessFindings(rawIssues) {
+ if (!Array.isArray(rawIssues)) return [];
+ const out = [];
+ for (const raw of rawIssues) {
+ const problem = typeof raw?.problem === 'string' ? raw.problem.trim() : '';
+ if (!problem) continue;
+ out.push({
+ severity: VERIFY_SEVERITIES.has(raw?.severity) ? raw.severity : 'medium',
+ category: COMPLETENESS_CATEGORIES.has(raw?.category) ? raw.category : 'other',
+ location: typeof raw?.location === 'string' ? raw.location.trim().slice(0, 200) : '',
+ problem: problem.slice(0, 2000),
+ suggestion: typeof raw?.suggestion === 'string' ? raw.suggestion.trim().slice(0, 2000) : '',
+ });
+ }
+ return out;
+}
+
+async function buildCompletenessContext(series, manuscript, preloadedWorld) {
+ const [base, canon] = await Promise.all([
+ buildArcBaseContext(series, preloadedWorld),
+ getSeriesCanon(series),
+ ]);
+ return {
+ ...base,
+ manuscript,
+ existingCharactersJson: JSON.stringify(canon.characters, null, 2),
+ existingPlacesJson: JSON.stringify(canon.places, null, 2),
+ existingObjectsJson: JSON.stringify(canon.objects, null, 2),
+ };
+}
+
+/**
+ * Editor pass over the drafted manuscript itself: returns categorized
+ * suggestions for rounding out and finishing a near-complete draft — missing
+ * pages/beats, arc holes, and character-development gaps. Read-only; advisory
+ * (no auto-resolve). Complements verifyArc/verifyVolume, which stay at synopsis
+ * depth and never see the script.
+ */
+export async function analyzeManuscriptCompleteness(seriesId, options = {}) {
+ const series = await getSeries(seriesId);
+ const manuscript = await collectIssueSourceText(seriesId);
+ if (!manuscript) {
+ throw makeErr(
+ 'No manuscript to analyze — write a comic script, prose, or teleplay on at least one issue first',
+ ERR_VALIDATION,
+ );
+ }
+ const ctx = await buildCompletenessContext(series, manuscript, options.preloadedWorld);
+ const { content, runId, providerId, model } = await runStagedLLM(
+ 'pipeline-manuscript-completeness',
+ ctx,
+ {
+ providerOverride: options.providerOverride,
+ modelOverride: options.modelOverride,
+ returnsJson: true,
+ source: 'pipeline-manuscript-completeness',
+ },
+ );
+ const issues = shapeCompletenessFindings(content?.issues);
+ return { issues, raw: content, runId, providerId, model };
+}
+
// Reader-map context: the protagonist arc + the Vonnegut shape backbone + the
// planned volume boundaries (so the LLM can place cliffhangers at issue gaps).
// Mirrors buildArcOverviewContext's world+arc projection.
@@ -1391,6 +1661,9 @@ export const __testing = {
shapeEpisodes,
shapeVerifyIssues,
shapeFindings,
+ shapeCompletenessFindings,
+ buildCompletenessContext,
+ issueSynopsisFromSeason,
renderVolumeIssue,
buildNeighborVolumes,
mergeArcWithLocks,
diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.js
index 7c1e6c30b3..1de45db590 100644
--- a/server/services/pipeline/arcPlanner.test.js
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -1477,3 +1477,146 @@ describe('arcPlanner — refineReaderMap', () => {
await expect(planner.generateReaderMap(s.id)).rejects.toMatchObject({ code: 'PIPELINE_ARC_VALIDATION' });
});
});
+
+describe('arcPlanner — manuscript completeness + derive-from-manuscript', () => {
+ beforeEach(() => {
+ fileStore.clear();
+ uuidCounter = 0;
+ stageRunnerSpy = undefined;
+ });
+
+ it('issueSynopsisFromSeason joins logline + synopsis (and is empty for nothing)', () => {
+ const { issueSynopsisFromSeason } = planner.__testing;
+ expect(issueSynopsisFromSeason({ logline: 'A', synopsis: 'B' })).toBe('A\n\nB');
+ expect(issueSynopsisFromSeason({ logline: 'A', synopsis: '' })).toBe('A');
+ expect(issueSynopsisFromSeason(null)).toBe('');
+ expect(issueSynopsisFromSeason({})).toBe('');
+ });
+
+ it('shapeCompletenessFindings coerces category/severity and drops empty problems', () => {
+ const { shapeCompletenessFindings } = planner.__testing;
+ const out = shapeCompletenessFindings([
+ { severity: 'high', category: 'missing-content', problem: 'no climax', suggestion: 'add one' },
+ { severity: 'bogus', category: 'invented-category', problem: 'thin cast' },
+ { problem: ' ' }, // dropped — empty after trim
+ { category: 'pacing', problem: 'rushed' }, // default severity medium
+ ]);
+ expect(out).toHaveLength(3);
+ expect(out[0]).toMatchObject({ severity: 'high', category: 'missing-content' });
+ expect(out[1]).toMatchObject({ severity: 'medium', category: 'other' }); // both coerced
+ expect(out[2]).toMatchObject({ severity: 'medium', category: 'pacing' });
+ });
+
+ it('analyzeManuscriptCompleteness reads the manuscript and returns shaped findings', async () => {
+ const s = await setupSeries();
+ await issuesSvc.createIssue({
+ seriesId: s.id, title: 'Act 1', arcPosition: 1,
+ stages: { comicScript: { output: 'PAGE 1\nGiant counts his gold.', status: 'ready' } },
+ });
+ stageRunnerSpy = vi.fn(async (template, ctx) => {
+ // The pass must see the actual drafted script, not a synopsis.
+ expect(template).toBe('pipeline-manuscript-completeness');
+ expect(ctx.manuscript).toContain('Giant counts his gold');
+ return {
+ content: { issues: [{ severity: 'high', category: 'arc-gap', problem: 'no ending', suggestion: 'write one' }] },
+ runId: 'rc', providerId: 'p', model: 'm',
+ };
+ });
+ const out = await planner.analyzeManuscriptCompleteness(s.id);
+ expect(out.issues).toHaveLength(1);
+ expect(out.issues[0]).toMatchObject({ category: 'arc-gap', severity: 'high' });
+ });
+
+ it('analyzeManuscriptCompleteness refuses when no manuscript exists', async () => {
+ const s = await setupSeries();
+ await issuesSvc.createIssue({ seriesId: s.id, title: 'Empty', arcPosition: 1 });
+ await expect(planner.analyzeManuscriptCompleteness(s.id)).rejects.toMatchObject({ code: 'PIPELINE_ARC_VALIDATION' });
+ });
+
+ it('deriveFromManuscript proposes a single volume + bible + zipped issue synopses', async () => {
+ const s = await setupSeries();
+ const sea = await seasonsSvc.createSeason(s.id, { title: 'V1', episodeCountTarget: 3 });
+ await issuesSvc.createIssue({ seriesId: s.id, seasonId: sea.id, title: 'Issue 1', arcPosition: 1, stages: { comicScript: { output: 'PAGE 1\nopening', status: 'ready' } } });
+ await issuesSvc.createIssue({ seriesId: s.id, seasonId: sea.id, title: 'Issue 2', arcPosition: 2, stages: { comicScript: { output: 'PAGE 1\nmiddle', status: 'ready' } } });
+
+ stageRunnerSpy = vi.fn(async (template) => {
+ expect(template).toBe('importer-arc-extract');
+ return {
+ content: {
+ logline: 'A giant hoards gold.', summary: 'A fairy-tale retold.', themes: ['greed'], protagonistArc: 'arc', shape: null,
+ seasons: [
+ { number: 1, title: 'The Miracle Man', logline: 'Beanstalk begins', synopsis: 'syn1' },
+ { number: 2, title: 'Magic Beans', logline: 'The climb', synopsis: 'syn2' },
+ ],
+ },
+ runId: 'rd', providerId: 'p', model: 'm',
+ };
+ });
+
+ const out = await planner.deriveFromManuscript(s.id);
+ expect(out.bible).toMatchObject({ logline: 'A giant hoards gold.', premise: 'A fairy-tale retold.', issueCountTarget: 2 });
+ expect(out.volume.title).toBe('Salt Run'); // defaults to series name
+ expect(out.issues).toHaveLength(2);
+ expect(out.issues[0].synopsisSuggestion).toContain('Beanstalk begins');
+ expect(out.issues[1].synopsisSuggestion).toContain('The climb');
+ });
+
+ it('commitDerivedManuscript collapses to one volume, pins all issues, fills bible, seeds synopses, leaves scripts intact', async () => {
+ const s = await setupSeries({ logline: '', premise: '', issueCountTarget: 0 });
+ const v1 = await seasonsSvc.createSeason(s.id, { title: 'V1', episodeCountTarget: 1 });
+ const v2 = await seasonsSvc.createSeason(s.id, { title: 'V2', episodeCountTarget: 1 });
+ const v3 = await seasonsSvc.createSeason(s.id, { title: 'V3', episodeCountTarget: 1 });
+ const v4 = await seasonsSvc.createSeason(s.id, { title: 'V4', episodeCountTarget: 1 });
+ const i1 = await issuesSvc.createIssue({ seriesId: s.id, seasonId: v1.id, title: 'Issue 1', arcPosition: 1, stages: { comicScript: { output: 'PAGE 1\nverbatim one', status: 'ready' } } });
+ const i2 = await issuesSvc.createIssue({ seriesId: s.id, seasonId: v2.id, title: 'Issue 2', arcPosition: 2, stages: { comicScript: { output: 'PAGE 1\nverbatim two', status: 'ready' } } });
+ const i3 = await issuesSvc.createIssue({ seriesId: s.id, seasonId: v3.id, title: 'Issue 3', arcPosition: 3, stages: { comicScript: { output: 'PAGE 1\nverbatim three', status: 'ready' } } });
+
+ const out = await planner.commitDerivedManuscript(s.id, {
+ arc: { logline: 'LG', summary: 'SM', themes: ['t'], protagonistArc: 'PA', shape: null },
+ bible: { logline: 'LG', premise: 'SM', issueCountTarget: 3 },
+ volume: { title: 'The Giant', logline: 'vlog', synopsis: 'vsyn' },
+ issues: [
+ { id: i1.id, title: 'Act One', synopsis: 'act one synopsis' },
+ { id: i2.id, title: 'Act Two', synopsis: 'act two synopsis' },
+ { id: i3.id, synopsis: 'act three synopsis' },
+ ],
+ });
+
+ // Exactly one volume survives.
+ expect(out.series.seasons).toHaveLength(1);
+ const vol = out.series.seasons[0];
+ expect(vol.title).toBe('The Giant');
+ // Bible filled.
+ expect(out.series).toMatchObject({ logline: 'LG', premise: 'SM', issueCountTarget: 3 });
+
+ // Every issue is under the single volume.
+ const all = await issuesSvc.listIssues({ seriesId: s.id });
+ expect(all.every((iss) => iss.seasonId === vol.id)).toBe(true);
+
+ // Per-issue title + synopsis applied; verbatim comicScript untouched.
+ const f1 = await issuesSvc.getIssue(i1.id);
+ expect(f1.title).toBe('Act One');
+ expect(f1.stages.idea.input).toBe('act one synopsis');
+ expect(f1.stages.comicScript.output).toBe('PAGE 1\nverbatim one');
+ const f3 = await issuesSvc.getIssue(i3.id);
+ expect(f3.stages.idea.input).toBe('act three synopsis');
+ void v4;
+ });
+
+ it('commitDerivedManuscript respects a locked idea stage (does not overwrite synopsis)', async () => {
+ const s = await setupSeries();
+ const v1 = await seasonsSvc.createSeason(s.id, { title: 'V1' });
+ const i1 = await issuesSvc.createIssue({
+ seriesId: s.id, seasonId: v1.id, title: 'Issue 1', arcPosition: 1,
+ stages: { comicScript: { output: 'PAGE 1\nx', status: 'ready' }, idea: { input: 'frozen synopsis', status: 'edited', locked: true } },
+ });
+ await planner.commitDerivedManuscript(s.id, {
+ arc: { logline: 'L', summary: 'S' },
+ bible: { logline: 'L', premise: 'S', issueCountTarget: 1 },
+ volume: { title: 'Vol' },
+ issues: [{ id: i1.id, synopsis: 'should not apply' }],
+ });
+ const f1 = await issuesSvc.getIssue(i1.id);
+ expect(f1.stages.idea.input).toBe('frozen synopsis');
+ });
+});
diff --git a/server/services/storyBuilder.js b/server/services/storyBuilder.js
index e58bc9914c..b5f0b95c80 100644
--- a/server/services/storyBuilder.js
+++ b/server/services/storyBuilder.js
@@ -38,9 +38,8 @@ import {
} from './pipeline/series.js';
import {
generateArcOverview, generateArcFromSource, generateReaderMap, refineReaderMap, commitSeasonsWithRemap,
+ collectIssueSourceText,
} from './pipeline/arcPlanner.js';
-import { listIssues } from './pipeline/issues.js';
-import { stageContentOf } from './pipeline/textStages.js';
const TYPE_SCHEMA_VERSION = 1;
@@ -423,31 +422,6 @@ export async function setIssueLock(id, issueId, locked) {
// ── Backfill (generate upstream from downstream) ───────────────────────────
-// Cap the concatenated issue corpus fed into a backfill extraction so a long
-// series can't blow past the provider's context budget. The importer enforces
-// its own (much larger) source ceiling; this is the Story-Builder-side bound.
-const BACKFILL_SOURCE_MAX = 200_000;
-
-// Collect existing issue content for the session's series, newest-authored
-// artifact per issue, so an upstream step (idea / plotArc) can be synthesized
-// FROM the downstream work that already exists — the user's "started from a
-// comic script" case. Prefers the richest stage (comicScript → teleplay →
-// prose → idea). Returns '' when no issue has any text content.
-async function collectIssueSourceText(seriesId) {
- if (!seriesId) return '';
- const issues = await listIssues({ seriesId }).catch(() => []);
- const parts = [];
- for (const iss of issues) {
- const st = iss.stages || {};
- const pick = ['comicScript', 'teleplay', 'prose', 'idea']
- .map((sid) => ({ sid, content: stageContentOf(st[sid]) }))
- .find((x) => x.content);
- if (!pick) continue;
- parts.push(`# Issue ${iss.number}${iss.title ? ` — ${iss.title}` : ''} (${pick.sid})\n\n${pick.content}`);
- }
- return parts.join('\n\n---\n\n').slice(0, BACKFILL_SOURCE_MAX);
-}
-
// ── Generate / refine delegation ──────────────────────────────────────────
// Each step's generate delegates to the existing service that owns its content,