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

Review the pilot before expanding series production (#7096)

[._.]/eae413a69ff9
diff --git a/client/src/components/pipeline/ArcCanvas.jsx b/client/src/components/pipeline/ArcCanvas.jsx
index 2bbf07cb6d..a03c9a2c45 100644
--- a/client/src/components/pipeline/ArcCanvas.jsx
+++ b/client/src/components/pipeline/ArcCanvas.jsx
@@ -74,7 +74,9 @@ export default function ArcCanvas({ series, issues, onSeriesUpdate, onIssuesUpda
return (
<div className="space-y-4">
- <div className="grid grid-cols-1 @5xl:grid-cols-[minmax(0,1.45fr)_minmax(360px,0.55fr)] gap-4 items-start">
+ <details className="group rounded-lg border border-port-border">
+ <summary className="cursor-pointer p-3 text-sm text-gray-300">Arc overview & editorial roadmap</summary>
+ <div className="p-3 grid grid-cols-1 @5xl:grid-cols-[minmax(0,1.45fr)_minmax(360px,0.55fr)] gap-4 items-start">
<ArcHeader
series={series}
onSeriesUpdate={onSeriesUpdate}
@@ -84,6 +86,7 @@ export default function ArcCanvas({ series, issues, onSeriesUpdate, onIssuesUpda
/>
<EditorialRoadmapPanel series={series} seasons={seasons} issues={issues} />
</div>
+ </details>
{seasons.length > 0 ? (
<section className="space-y-3">
diff --git a/client/src/components/pipeline/AutopilotPanel.jsx b/client/src/components/pipeline/AutopilotPanel.jsx
index cffb46d3bb..6612c685ab 100644
--- a/client/src/components/pipeline/AutopilotPanel.jsx
+++ b/client/src/components/pipeline/AutopilotPanel.jsx
@@ -83,6 +83,8 @@ const AUTOPILOT_LLM_STAGES = [
['beatSheet', 'Beat sheets'],
['beatContinuity', 'Beat continuity'],
['textStages', 'Draft text stages'],
+ ['pilotDraft', 'Draft opening issue'],
+ ['pilotReview', 'Review opening before expansion'],
['scriptVerify', 'Verify scripts'],
['editorialReview', 'Editorial review'],
['reverseOutline', 'Reverse outline'],
@@ -489,6 +491,7 @@ function Findings({ items }) {
export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate }) {
const seriesId = series?.id;
const [active, setActive] = useState(false);
+ const [attachVersion, setAttachVersion] = useState(0);
const [pausePending, setPausePending] = useState(false);
const [starting, setStarting] = useState(false);
const [mode, setMode] = useState(null);
@@ -580,6 +583,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
// live progress line names, so a run started elsewhere (or by the scheduler)
// still says which provider (and how hard it thinks) it is spending on.
const [runLlm, setRunLlm] = useState(null);
+ const [productionScope, setProductionScope] = useState('series');
// A cooperative cancel persists every non-destructive run-local LLM choice.
// Restore those choices on Resume so a model experiment does not silently
@@ -587,6 +591,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
useEffect(() => {
const paused = series?.autopilot?.status === 'paused';
const resume = paused ? series?.autopilot?.resumeOptions : null;
+ setProductionScope(resume?.productionScope || 'series');
setProviderOverride(resume?.providerOverride || '');
setModelOverride(resume?.modelOverride || '');
setEffortOverride(resume?.effortOverride || '');
@@ -599,6 +604,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
}, [
seriesId,
series?.autopilot?.status,
+ series?.autopilot?.resumeOptions?.productionScope,
series?.autopilot?.resumeOptions?.providerOverride,
series?.autopilot?.resumeOptions?.modelOverride,
series?.autopilot?.resumeOptions?.effortOverride,
@@ -776,6 +782,9 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
// fresh Run/Resume would see that stale terminal frame and immediately tear
// the new run down. Terminal frames whose runId doesn't match are ignored.
const activeRunIdRef = useRef(null);
+ const activeRunSeriesIdRef = useRef(seriesId);
+ const settledRunIdRef = useRef(null);
+ const terminalVersionRef = useRef(0);
// Read a run's `start` frame — mode (the dry-run badge), the resolved run
// provider/model, and a dry-run's plan. Shared by the SSE frame and the
@@ -796,10 +805,17 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
useEffect(() => {
if (!seriesId) return undefined;
let canceled = false;
+ const terminalVersion = terminalVersionRef.current;
getPipelineAutopilotStatus(seriesId, { silent: true })
.then((s) => {
- if (canceled || !s?.active) return;
- activeRunIdRef.current = s.autopilot?.runId || null;
+ if (canceled || terminalVersion !== terminalVersionRef.current || !s?.active) return;
+ // The live start frame owns identity; the persisted marker can still
+ // describe a previous run, and dry-runs never persist one.
+ const knownRunId = activeRunSeriesIdRef.current === seriesId ? activeRunIdRef.current : null;
+ const runId = s.start?.runId || knownRunId || null;
+ if (settledRunIdRef.current && runId === settledRunIdRef.current) return;
+ activeRunIdRef.current = runId;
+ activeRunSeriesIdRef.current = seriesId;
// SSE replays only the last frame, so the run's `start` frame comes back
// on the status payload instead — same shape, same reader.
if (s.start) applyStartFrame(s.start);
@@ -812,7 +828,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
})
.catch(() => null);
return () => { canceled = true; };
- }, [seriesId, applyStartFrame]);
+ }, [seriesId, attachVersion, applyStartFrame]);
// Capture dry-run plan + mode. The plan rides the start frame, but a fast
// dry-run can complete before the client attaches and only the terminal frame
@@ -835,6 +851,8 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
if (!active || !latest || !RUN_ENDED.has(latest.type)) return;
// Ignore a terminal frame left over from a previous run (stale `latest`).
if (activeRunIdRef.current && latest.runId && latest.runId !== activeRunIdRef.current) return;
+ settledRunIdRef.current = latest.runId || activeRunIdRef.current;
+ terminalVersionRef.current += 1;
setActive(false);
setPausePending(false);
// Freeze the map on how this run ended: a paused/errored run keeps its
@@ -847,7 +865,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
if (latest.dryRun) toast.success('Autopilot plan ready');
else if (latest.craftGapIssues > 0) toast.warning(`Autopilot complete with ${craftGapCaution(latest.craftGapIssues)}`);
else if (latest.editorialCheckErrors > 0) toast.warning(`Autopilot complete — ${editorialCheckCaution(latest.editorialCheckErrors)}`);
- else toast.success('Autopilot complete — draft is production-ready');
+ else toast.success('Autopilot complete — selected production pass finished');
}
else if (latest.type === 'canceled') toast.success('Autopilot canceled');
else if (latest.type === 'paused') toast.warning(`Autopilot paused — ${latest.reason || 'needs review'}`);
@@ -903,7 +921,8 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
} : {}),
...(Object.keys(stageLlm).length > 0 ? { stageLlm } : {}),
};
- const res = await startPipelineAutopilot(seriesId, { includeVisual, fileGaps, ...roundOverrides, ...gateOverride, ...unlockOverride, ...llmOverride }, { silent: true })
+ const scopeOverride = productionScope === 'first-issue' ? { productionScope } : {};
+ const res = await startPipelineAutopilot(seriesId, { includeVisual, fileGaps, ...scopeOverride, ...roundOverrides, ...gateOverride, ...unlockOverride, ...llmOverride }, { silent: true })
.catch((err) => { toast.error(err.message || 'Could not start autopilot'); return null; });
setStarting(false);
if (!res) return;
@@ -918,10 +937,12 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
// Track this run's id BEFORE enabling the stream so the terminal-frame
// effect can reject a stale terminal frame from the previous run.
activeRunIdRef.current = res.runId || null;
+ activeRunSeriesIdRef.current = seriesId;
+ setAttachVersion((version) => version + 1);
setActive(true);
// `options` is the single dep for every persisted option — the registry reads
// live values through refs, so no option can be forgotten here.
- }, [seriesId, includeVisual, fileGaps, unlockForRun, readinessGate, providerOverride, modelOverride, effortOverride, separateJudgeLlm, judgeProviderOverride, judgeModelOverride, judgeEffortOverride, stageLlm, options, persistRounds]);
+ }, [seriesId, includeVisual, fileGaps, productionScope, unlockForRun, readinessGate, providerOverride, modelOverride, effortOverride, separateJudgeLlm, judgeProviderOverride, judgeModelOverride, judgeEffortOverride, stageLlm, options, persistRounds]);
const cancel = useCallback(async () => {
setPausePending(false);
@@ -965,7 +986,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
<div className="flex items-center gap-2 flex-wrap p-3">
<Rocket size={15} className="text-port-accent" />
<span className="text-sm font-medium text-white">Autonomous mode</span>
- <span className="text-xs text-gray-500">drives every missing step to a production-ready draft</span>
+ <span className="text-xs text-gray-500">reviews the story before producing the selected issues</span>
<div className="ml-auto flex items-center gap-2">
{!active ? (
@@ -1014,6 +1035,26 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
</div>
{/* Options popover */}
+ {!active ? (
+ <div className="px-3 pb-3 flex flex-wrap items-center gap-2">
+ <label htmlFor="autopilot-production-scope" className="text-xs text-gray-400">Produce</label>
+ <select
+ id="autopilot-production-scope"
+ value={productionScope}
+ onChange={(event) => setProductionScope(event.target.value)}
+ disabled={starting}
+ className="max-w-full rounded border border-port-border bg-port-bg px-2 py-1.5 text-sm text-white"
+ >
+ <option value="series">All planned issues</option>
+ <option value="first-issue">First issue only</option>
+ </select>
+ <span className="text-xs text-gray-500">
+ {productionScope === 'first-issue'
+ ? 'Draft and draw the opening. Editorial repairs can still update the whole plan and any existing drafts.'
+ : 'The opening receives developmental review before later issues are drafted.'}
+ </span>
+ </div>
+ ) : null}
{showOpts && !active ? (
<div className="px-3 pb-3 flex flex-col gap-2 border-t border-port-border pt-3">
{/* Which AI actually runs. The panel used to name none of this, so the
@@ -1444,7 +1485,7 @@ export default function AutopilotPanel({ series, onSeriesUpdate, onIssuesUpdate
{ap.status === 'paused' ? (ap.currentStep ? `Paused at ${stepLabel(ap.currentStep)}` : 'Paused')
: doneWithGaps ? `Completed with ${craftGapCaution(ap.craftGapIssues)}`
: doneWithCheckErrors ? `Completed — ${editorialCheckCaution(ap.editorialCheckErrors)}`
- : ap.status === 'done' ? 'Last run completed — draft is production-ready' : 'Last run errored'}
+ : ap.status === 'done' ? 'Last run completed — selected production pass finished' : 'Last run errored'}
</span>
{ap.status === 'paused' && PAUSE_BADGES[ap.pauseKind] ? (
<Pill tone="warning" size="xs" title={PAUSE_BADGES[ap.pauseKind].title}>
diff --git a/client/src/components/pipeline/AutopilotPanel.test.jsx b/client/src/components/pipeline/AutopilotPanel.test.jsx
index 4512875b57..6423fe032c 100644
--- a/client/src/components/pipeline/AutopilotPanel.test.jsx
+++ b/client/src/components/pipeline/AutopilotPanel.test.jsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
vi.mock('../../services/api', () => ({
@@ -82,6 +82,42 @@ describe('AutopilotPanel', () => {
));
});
+ it('sends pilot scope and does not reattach a settled run from a delayed status response', async () => {
+ let resolveStatus;
+ getPipelineAutopilotStatus.mockResolvedValueOnce({ active: false })
+ .mockImplementationOnce(() => new Promise((resolve) => { resolveStatus = resolve; }));
+ const view = renderPanel({ id: 's1', targetFormat: 'comic' });
+ await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalledTimes(1));
+ fireEvent.change(screen.getByLabelText('Produce'), { target: { value: 'first-issue' } });
+ fireEvent.click(screen.getByRole('button', { name: /run autopilot/i }));
+ await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalledTimes(2));
+ expect(startPipelineAutopilot).toHaveBeenCalledWith('s1', expect.objectContaining({ productionScope: 'first-issue' }), { silent: true });
+ sseLatest = { type: 'paused', runId: 'r1', reason: 'pilot needs work' };
+ sseFrames = [sseLatest];
+ view.rerender(<MemoryRouter><AutopilotPanel series={{ id: 's1', targetFormat: 'comic' }} /></MemoryRouter>);
+ await waitFor(() => expect(toast.warning).toHaveBeenCalledTimes(1));
+ await act(async () => resolveStatus({ active: true, autopilot: null, start: { runId: 'r1', mode: 'execute', provider: 'codex', model: 'selected-model' } }));
+ expect(screen.getByRole('button', { name: /run autopilot/i })).toBeInTheDocument();
+ expect(toast.warning).toHaveBeenCalledTimes(1);
+ expect(screen.queryByRole('button', { name: /pause safely/i })).not.toBeInTheDocument();
+ });
+
+ it('keeps the started run identity when status still carries a previous marker', async () => {
+ getPipelineAutopilotStatus.mockResolvedValueOnce({ active: false })
+ .mockResolvedValueOnce({ active: true, autopilot: { runId: 'previous-run' }, start: null });
+ const view = renderPanel({ id: 's1', targetFormat: 'comic' });
+ await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalledTimes(1));
+ fireEvent.click(screen.getByRole('button', { name: /run autopilot/i }));
+ await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalledTimes(2));
+ await act(async () => {});
+ sseLatest = { type: 'paused', runId: 'r1', reason: 'pilot needs work' };
+ sseFrames = [sseLatest];
+ view.rerender(<MemoryRouter><AutopilotPanel series={{ id: 's1', targetFormat: 'comic' }} /></MemoryRouter>);
+ await waitFor(() => expect(toast.warning).toHaveBeenCalledTimes(1));
+ expect(screen.getByRole('button', { name: /run autopilot/i })).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /pause safely/i })).not.toBeInTheDocument();
+ });
+
it('passes options chosen in the popover', async () => {
renderPanel({ id: 's1', targetFormat: 'comic' });
await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalled());
@@ -640,14 +676,14 @@ describe('AutopilotPanel', () => {
it('shows the production-ready banner for a clean done marker', async () => {
renderPanel({ id: 's1', targetFormat: 'comic', autopilot: { status: 'done', craftGapIssues: 0 } });
await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalled());
- expect(screen.getByText(/draft is production-ready/i)).toBeInTheDocument();
+ expect(screen.getByText(/selected production pass finished/i)).toBeInTheDocument();
});
it('qualifies a done marker that filed script-craft gaps as a caution (#1572)', async () => {
renderPanel({ id: 's1', targetFormat: 'comic', autopilot: { status: 'done', craftGapIssues: 2, craftGapFindings: 3 } });
await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalled());
expect(screen.getByText(/Completed with 2 filed script-craft gaps — resolve before rendering/i)).toBeInTheDocument();
- expect(screen.queryByText(/draft is production-ready/i)).not.toBeInTheDocument();
+ expect(screen.queryByText(/selected production pass finished/i)).not.toBeInTheDocument();
});
it('uses the singular gap label when exactly one craft gap was filed (#1572)', async () => {
@@ -660,7 +696,7 @@ describe('AutopilotPanel', () => {
renderPanel({ id: 's1', targetFormat: 'comic', autopilot: { status: 'done', craftGapIssues: 0, editorialCheckErrors: 2 } });
await waitFor(() => expect(getPipelineAutopilotStatus).toHaveBeenCalled());
expect(screen.getByText(/2 editorial checks errored — review before trusting/i)).toBeInTheDocument();
- expect(screen.queryByText(/draft is production-ready/i)).not.toBeInTheDocument();
+ expect(screen.queryByText(/selected production pass finished/i)).not.toBeInTheDocument();
});
it('prefers the craft-gap caution over the editorial-check caution when both are present (#1573)', async () => {
diff --git a/client/src/components/pipeline/arcCanvas/VolumeNavigator.jsx b/client/src/components/pipeline/arcCanvas/VolumeNavigator.jsx
index 78e6a74ebd..c637503ac9 100644
--- a/client/src/components/pipeline/arcCanvas/VolumeNavigator.jsx
+++ b/client/src/components/pipeline/arcCanvas/VolumeNavigator.jsx
@@ -19,13 +19,13 @@ export default function VolumeNavigator({ seasons, issuesBySeason, activeSeasonI
type="button"
onClick={() => onSelect(season.id)}
aria-pressed={active}
- className={`snap-start shrink-0 w-44 text-left rounded border overflow-hidden bg-port-bg transition-colors ${
+ className={`snap-start shrink-0 w-60 flex text-left rounded border overflow-hidden bg-port-bg transition-colors ${
active
? 'border-port-accent shadow-[0_0_0_1px_rgba(59,130,246,0.35)]'
: 'border-port-border hover:border-port-accent/50'
}`}
>
- <div className="aspect-[3/4] bg-port-bg">
+ <div className="w-12 h-16 shrink-0 bg-port-bg">
<CoverArt
record={season.cover}
label={`Volume ${season.number} cover`}
@@ -33,7 +33,7 @@ export default function VolumeNavigator({ seasons, issuesBySeason, activeSeasonI
placeholderClassName="rounded-none border-0"
/>
</div>
- <div className="p-2 min-h-[72px]">
+ <div className="p-2 min-w-0">
<div className="flex items-center gap-1.5">
<span className="text-[10px] font-mono text-gray-500">V{season.number}</span>
<span className="text-[10px] uppercase tracking-wider text-gray-500">
diff --git a/client/src/lib/autopilotMilestones.js b/client/src/lib/autopilotMilestones.js
index 394f8742a4..81026086a9 100644
--- a/client/src/lib/autopilotMilestones.js
+++ b/client/src/lib/autopilotMilestones.js
@@ -34,6 +34,8 @@ export const AUTOPILOT_STEP_LABELS = Object.freeze({
beatSheet: 'Generating beat sheets',
beatContinuity: 'Beat continuity',
textStages: 'Writing prose + scripts',
+ pilotDraft: 'Drafting the opening issue',
+ pilotReview: 'Reviewing the opening before expansion',
scriptVerify: 'Verifying scripts',
editorialReview: 'Editorial review',
reverseOutline: 'Refreshing scene segmentation',
diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsx
index b58cfd6449..2eae01cba4 100644
--- a/client/src/pages/PipelineSeries.jsx
+++ b/client/src/pages/PipelineSeries.jsx
@@ -1,3 +1,4 @@
+import { compareIssuesInSeries } from '../../../server/lib/pipelineIssueOrder.js';
/**
* Pipeline — Series detail page.
*
@@ -38,6 +39,7 @@ import AuthorPicker from '../components/pipeline/AuthorPicker';
import VoiceExemplarEditor, { VOICE_EXEMPLARS_MAX } from '../components/VoiceExemplarEditor';
import { buildImporterLink } from '../lib/importerDeepLink';
import { recommendStructure, describeStructure } from '../lib/seasonStructure';
+import useDrawerTab from '../hooks/useDrawerTab';
import { useLocalStorageBool } from '../hooks/useLocalStorageBool';
import { useArcCanvasSync } from '../hooks/useArcCanvasSync';
import RecordRenderPinRow from '../components/imageGen/RecordRenderPinRow';
@@ -45,6 +47,13 @@ import CharacterEvolutionLens from '../components/character/CharacterEvolutionLe
import { EVOLUTION_STAGES, isDeclaredEvolution } from '../lib/characterEvolution.js';
import { CHARACTER_ARC_LIMITS, TRANSITION_KINDS, TRANSITION_KIND_LABELS } from '../../../server/lib/seriesCharacterArc.js';
+const EDITOR_TABS = [
+ { id: 'issues', label: 'Issues & arc' },
+ { id: 'editorial', label: 'Editorial' },
+ { id: 'autopilot', label: 'Autopilot' },
+ { id: 'branching', label: 'Branching' },
+];
+
const PIPELINE_SIDEBAR_KEY = 'portos-pipeline-series-sidebar-collapsed';
// Mirrors `STYLE_PROMPT_OVERRIDE_MODES` on the server (series.js). The
@@ -110,6 +119,7 @@ const STYLE_GUIDE_TRISTATE = [
export default function PipelineSeries() {
const { seriesId } = useParams();
const navigate = useNavigate();
+ const [editorTab, setEditorTab] = useDrawerTab('view', 'issues', EDITOR_TABS.map((tab) => tab.id));
const [series, setSeries] = useState(null);
const [issues, setIssues] = useState([]);
const [universes, setWorlds] = useState([]);
@@ -214,22 +224,8 @@ export default function PipelineSeries() {
<PanelLeftOpen size={16} />
</button>
)}
- {sidebarCollapsed ? (
- <div className="hidden lg:block overflow-hidden min-w-0" />
- ) : (
- <aside className="border-b lg:border-b-0 lg:border-r border-port-border bg-port-card/40 lg:overflow-y-auto">
- <BibleSidebar
- series={series}
- universes={universes}
- patchSeries={patchSeries}
- onSeriesUpdate={updateSeriesFromServer}
- onFlushPending={flushPending}
- onCollapse={toggleSidebar}
- />
- </aside>
- )}
- <section className="@container flex flex-col gap-4 p-4 min-h-0 lg:overflow-y-auto">
+ <section className="lg:col-start-2 lg:row-start-1 @container shrink-0 lg:shrink flex flex-col gap-4 p-4 min-h-0 lg:overflow-y-auto">
<header className={`flex items-center gap-3 flex-wrap ${sidebarCollapsed ? 'lg:pl-8' : ''}`}>
<Link to="/pipeline" className="inline-flex items-center gap-1 text-sm text-gray-400 hover:text-white">
<ArrowLeft size={14} /> All Series
@@ -303,29 +299,61 @@ export default function PipelineSeries() {
</button>
</header>
- <SeriesReviewPanel
- series={series}
- onSeriesUpdate={updateSeriesFromServer}
- onIssuesUpdate={handleIssuesUpdate}
- />
-
- <AutopilotPanel
- series={series}
- onSeriesUpdate={updateSeriesFromServer}
- onIssuesUpdate={handleIssuesUpdate}
- />
-
- <SeriesLoomsPanel series={series} />
-
- <ArcCanvas
- series={series}
- issues={issues}
- onSeriesUpdate={updateSeriesFromServer}
- onIssuesUpdate={handleIssuesUpdate}
- onFlushPending={flushPending}
- onRegisterDraftFlush={registerDraftFlush}
- />
+ <div className="flex flex-wrap items-center gap-3 text-sm">
+ {issues.length > 0 && (
+ <Link className="text-port-accent hover:underline" to={`/pipeline/issues/${[...issues].sort(compareIssuesInSeries)[0].id}`}>
+ <BookOpen size={14} className="inline mr-1" /> Open first issue
+ </Link>
+ )}
+ {series.universeId && (
+ <Link className="text-port-accent hover:underline" to={`/universes/${series.universeId}`}>
+ <Globe size={14} className="inline mr-1" /> Universe bible
+ </Link>
+ )}
+ {['running', 'paused'].includes(series.autopilot?.status) && (
+ <button type="button" className="text-amber-400 hover:underline" onClick={() => setEditorTab('autopilot')}>
+ Autopilot {series.autopilot.status} — view progress
+ </button>
+ )}
+ </div>
+ <TabPills tabs={EDITOR_TABS} activeTab={editorTab} onChange={setEditorTab}
+ ariaLabel="Series editor" controlsIdPrefix="series-editor" size="sm" />
+ {/* Keep drafts and the live autopilot subscription mounted across tabs. */}
+ <div role="tabpanel" id="series-editor-editorial" aria-labelledby="tab-editorial" hidden={editorTab !== 'editorial'}>
+ <SeriesReviewPanel series={series} onSeriesUpdate={updateSeriesFromServer} onIssuesUpdate={handleIssuesUpdate} />
+ </div>
+ <div role="tabpanel" id="series-editor-autopilot" aria-labelledby="tab-autopilot" hidden={editorTab !== 'autopilot'}>
+ <AutopilotPanel series={series} onSeriesUpdate={updateSeriesFromServer} onIssuesUpdate={handleIssuesUpdate} />
+ </div>
+ <div role="tabpanel" id="series-editor-branching" aria-labelledby="tab-branching" hidden={editorTab !== 'branching'}>
+ <SeriesLoomsPanel series={series} />
+ </div>
+ <div role="tabpanel" id="series-editor-issues" aria-labelledby="tab-issues" hidden={editorTab !== 'issues'}>
+ <ArcCanvas
+ series={series}
+ issues={issues}
+ onSeriesUpdate={updateSeriesFromServer}
+ onIssuesUpdate={handleIssuesUpdate}
+ onFlushPending={flushPending}
+ onRegisterDraftFlush={registerDraftFlush}
+ />
+ </div>
</section>
+ {sidebarCollapsed ? (
+ <div className="hidden lg:block lg:col-start-1 lg:row-start-1 overflow-hidden min-w-0" />
+ ) : (
+ <aside className="lg:col-start-1 lg:row-start-1 border-b lg:border-b-0 lg:border-r border-port-border bg-port-card/40 lg:overflow-y-auto">
+ <BibleSidebar
+ series={series}
+ universes={universes}
+ patchSeries={patchSeries}
+ onSeriesUpdate={updateSeriesFromServer}
+ onFlushPending={flushPending}
+ onCollapse={toggleSidebar}
+ />
+ </aside>
+ )}
+
</div>
</div>
);
diff --git a/client/src/pages/PipelineSeries.responsive.test.jsx b/client/src/pages/PipelineSeries.responsive.test.jsx
index 72d16d20c9..b29888e33b 100644
--- a/client/src/pages/PipelineSeries.responsive.test.jsx
+++ b/client/src/pages/PipelineSeries.responsive.test.jsx
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { render, screen } from '@testing-library/react';
+import { render, screen, fireEvent } from '@testing-library/react';
import { MemoryRouter, Route, Routes } from 'react-router';
import PipelineSeries from './PipelineSeries';
@@ -53,6 +53,19 @@ describe('Pipeline series detail — mobile layout', () => {
listUniverses.mockResolvedValue([]);
});
+ it('opens on issues, exposes direct destinations, and keeps inactive panels mounted', async () => {
+ listPipelineIssues.mockResolvedValue([{ id: 'issue-1', number: 1 }]);
+ getPipelineSeries.mockResolvedValue({ id: 'series-1', name: 'Example Series', universeId: 'universe-1' });
+ renderPage();
+ expect(await screen.findByRole('link', { name: /open first issue/i })).toHaveAttribute('href', '/pipeline/issues/issue-1');
+ expect(screen.getByRole('link', { name: /universe bible/i })).toHaveAttribute('href', '/universes/universe-1');
+ expect(screen.getByRole('tabpanel')).toHaveAttribute('id', 'series-editor-issues');
+ fireEvent.click(screen.getByRole('tab', { name: 'Autopilot' }));
+ expect(screen.getByRole('tabpanel')).toHaveAttribute('id', 'series-editor-autopilot');
+ expect(screen.getByText('arc canvas')).toBeInTheDocument();
+ expect(screen.getByText('arc canvas').closest('[role="tabpanel"]')).toHaveAttribute('hidden');
+ });
+
it('owns a page scroll region below lg after the bible reflows above the canvas', async () => {
renderPage();
diff --git a/data.reference/prompts/stages/pipeline-judge-foundation.md b/data.reference/prompts/stages/pipeline-judge-foundation.md
index bff82d5a03..511711c36d 100644
--- a/data.reference/prompts/stages/pipeline-judge-foundation.md
+++ b/data.reference/prompts/stages/pipeline-judge-foundation.md
@@ -66,7 +66,7 @@ the concrete fix restore the derived bible or plan to the protected intent.
1. **worldbuilding** *(weight 40%)* — Does the derived universe preserve the protected author intent exactly in substance, without replacing its ontology, protagonists, or core story engine? Do the world's powers have clear LIMITATIONS (not just capabilities)? Is there iceberg depth (implied history/systems beneath the named surface)? Are the pieces interconnected (magic ↔ politics ↔ geography), or a disconnected props list? Is canon coverage broad enough to draft against without inventing on the fly?
2. **character** *(weight 30%)* — Is every character linked to this series fully authored, not only the leads: explicit pronouns and age-status, personality and relevant history, motivations, likes/dislikes, mannerisms, reciprocal relationships, practical skills, distinct speech, secrets, and a clear arc type? Are the leads' Wound → Lie → Want → Need chains complete and specific (not blank, not generic)? For a graphic-novel target, does every series-linked character also have a concrete, mutually distinct visual foundation—physical description, silhouette, visual identity, and palette—so image generation will not invent them afresh from page to page? A psychologically rich lead or supporting character with blank profile/render identity is still an incomplete character foundation and cannot score above 5.
-3. **structure** *(weight 20%)* — Is the arc outline complete (logline, summary, protagonist arc, per-volume loglines + ending hooks)? Is foreshadowing balanced (setups that will pay off, not everything front-loaded or nothing planted)? Do the volume threads nest coherently toward the finale?
+3. **structure** *(weight 20%)* — Does the opening plan establish the protagonist's immediate personal want, ordinary relationships, pressure on an existing belief, a costly choice, and visible aftermath? A mission briefing, banter, inventory discovery, and cliffhanger are not a complete first-issue arc. Does each principal cause distinct turns rather than merely accompany the plot? Track relationships through setup, rupture, attempted repair, and earned change. Is the arc outline complete (logline, summary, protagonist arc, per-volume loglines + ending hooks)? Is foreshadowing balanced (setups that will pay off, not everything front-loaded or nothing planted)? Do the volume threads nest coherently toward the finale? An opening with no personal causal arc cannot score above 5, even if all outline fields are filled.
4. **craft** *(weight 10%)* — Is the declared voice/style clear and specific enough to write to (tense, POV, tone, register), or vague boilerplate a drafter would ignore?
For **each** dimension return `{ "score": <int 1-10>, "gap": "<the single weakest specific thing>", "fix": "<one concrete change that would raise this dimension>" }`.
diff --git a/data.reference/prompts/stages/pipeline-manuscript-completeness.md b/data.reference/prompts/stages/pipeline-manuscript-completeness.md
index 87176e9339..1024e18877 100644
--- a/data.reference/prompts/stages/pipeline-manuscript-completeness.md
+++ b/data.reference/prompts/stages/pipeline-manuscript-completeness.md
@@ -1,6 +1,6 @@
# 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. For comic scripts, this includes **structural completeness**: every page must have all of its content expressed in panel definitions, not left as prose in the page description.
+You are a developmental editor reading the **manuscript drafted so far**, which may be only the opening issue of a planned series. Unlike a continuity pass over a synopsis, you are reading the **actual drafted script** below. Identify what is **missing or under-developed on the page** before more issues or artwork multiply those problems. For comic scripts, this includes **structural completeness**: every page must have all of its content expressed in panel definitions, not left as prose in the page description.
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.
@@ -60,6 +60,23 @@ Each issue is delimited by a `# Issue N` header. The script may use page/panel m
## What to look for
+### Opening contract and serial scope
+
+Judge only the supplied drafted issues. The whole-series arc is context for setup and reveal order, not a demand to resolve the entire series in its pilot. Do not report unprovided future issues, a deliberately deferred mystery, or a later-volume transformation as missing manuscript. Equally, do not credit an emotional beat that exists only in the bible or outline.
+
+Apply the opening contract ONLY when the supplied manuscript contains the actual first issue of the series. A later review chunk is a continuation, not a new beginning: do not demand repeated introductions or insert pilot setup into it.
+
+The opening must give a new reader a concrete reason to care before asking them to memorize the lore. Check for:
+
+- A readable everyday situation and an immediate personal want for the viewpoint character, with enough context to understand the team's work and stakes. An action opening can do this through behavior; a prologue or exposition dump is not required.
+- A relationship demonstrated through care, friction, a shared ritual, or a broken promise. Interchangeable quips and dossier facts do not establish intimacy.
+- A costly decision that comes from the protagonist's existing belief or flaw, meets resistance, and changes the situation. Curiosity alone is insufficient motivation for a dangerous experiment when the story presents the lead as protective and competent.
+- A civilian or other affected person treated as a person with agency, and a visible consequence of what the protagonists do to them.
+- A local dramatic question answered through action, followed by emotional aftermath. A cliffhanger opens the next problem; it must not replace the entire issue's payoff.
+- Setup for later character change without completing that change early. Check references to prior events against the planned chronology; never turn a future first discovery into unexplained shared history.
+
+Missing reader orientation, a principal's causal motivation, or the opening's choice-and-consequence chain is a **high** developmental finding. These are production blockers even when the script parses and has the expected page count. Name the missing scene function and its placement. Add or restructure where necessary; deleting repetition cannot create an absent relationship or payoff. Preserve working voice and imagery, and avoid adding procedural caveats as a substitute for drama.
+
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.
diff --git a/scripts/migrations/056-manuscript-anchored-findings-prompt.js b/scripts/migrations/056-manuscript-anchored-findings-prompt.js
index 901d78956e..b060bb34c7 100644
--- a/scripts/migrations/056-manuscript-anchored-findings-prompt.js
+++ b/scripts/migrations/056-manuscript-anchored-findings-prompt.js
@@ -31,7 +31,7 @@ export const ACCEPTED_OLD_MD5 = {
// drift-catch tests require it to match the live data.reference body, not 056's
// own output.
export const NEW_SHIPPED_MD5 = {
- 'pipeline-manuscript-completeness.md': 'fd26f928c33803c12878a1bfb8561ece',
+ 'pipeline-manuscript-completeness.md': 'a08a7aaea9b57dcf12311505150672cd',
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/057-comic-structure-completeness-prompt.js b/scripts/migrations/057-comic-structure-completeness-prompt.js
index ba002b01e6..f7689c766c 100644
--- a/scripts/migrations/057-comic-structure-completeness-prompt.js
+++ b/scripts/migrations/057-comic-structure-completeness-prompt.js
@@ -35,7 +35,7 @@ export const ACCEPTED_OLD_MD5 = {
// the post-083 body. The idempotent-rerun and drift-catch tests require it to
// match the live data.reference body, not 057's own output.
export const NEW_SHIPPED_MD5 = {
- 'pipeline-manuscript-completeness.md': 'fd26f928c33803c12878a1bfb8561ece',
+ 'pipeline-manuscript-completeness.md': 'a08a7aaea9b57dcf12311505150672cd',
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/066-manuscript-finding-replacement-strategy-prompts.js b/scripts/migrations/066-manuscript-finding-replacement-strategy-prompts.js
index 95103a03f8..63d8373a70 100644
--- a/scripts/migrations/066-manuscript-finding-replacement-strategy-prompts.js
+++ b/scripts/migrations/066-manuscript-finding-replacement-strategy-prompts.js
@@ -45,7 +45,7 @@ export const ACCEPTED_OLD_MD5 = {
// (migration 083 added the with-edits `replace` field); the fix hash reflects
// the post-084 body (migration 084 made the JSON example schematic).
export const NEW_SHIPPED_MD5 = {
- 'pipeline-manuscript-completeness.md': 'fd26f928c33803c12878a1bfb8561ece',
+ 'pipeline-manuscript-completeness.md': 'a08a7aaea9b57dcf12311505150672cd',
'pipeline-manuscript-fix.md': 'e2baaf0f2f53c8aa1e934a428c0ca583',
};
diff --git a/scripts/migrations/083-completeness-with-edits-prompt.js b/scripts/migrations/083-completeness-with-edits-prompt.js
index 90abb373c6..104583d182 100644
--- a/scripts/migrations/083-completeness-with-edits-prompt.js
+++ b/scripts/migrations/083-completeness-with-edits-prompt.js
@@ -34,7 +34,7 @@ export const ACCEPTED_OLD_MD5 = {
// earlier migration that tracks the same file (056/057/066) so their drift-catch
// tests stay green.
export const NEW_SHIPPED_MD5 = {
- 'pipeline-manuscript-completeness.md': 'fd26f928c33803c12878a1bfb8561ece',
+ 'pipeline-manuscript-completeness.md': 'a08a7aaea9b57dcf12311505150672cd',
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/241-foundation-judge-repair-ownership.js b/scripts/migrations/241-foundation-judge-repair-ownership.js
index c014b3b155..04f735c3f4 100644
--- a/scripts/migrations/241-foundation-judge-repair-ownership.js
+++ b/scripts/migrations/241-foundation-judge-repair-ownership.js
@@ -20,7 +20,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-judge-foundation.md': '75714f0e41c77ff5c8b9623cb4fb0a25', // post-256 (series-linked cast)
+ 'pipeline-judge-foundation.md': 'd4abf4ddafbf84a2903e6d70d14adea1', // post-256 (series-linked cast)
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/248-foundation-judge-author-intent.js b/scripts/migrations/248-foundation-judge-author-intent.js
index c236397fb8..4c59c66ddd 100644
--- a/scripts/migrations/248-foundation-judge-author-intent.js
+++ b/scripts/migrations/248-foundation-judge-author-intent.js
@@ -20,7 +20,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-judge-foundation.md': '75714f0e41c77ff5c8b9623cb4fb0a25', // post-256 (series-linked cast)
+ 'pipeline-judge-foundation.md': 'd4abf4ddafbf84a2903e6d70d14adea1', // post-256 (series-linked cast)
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/255-character-visual-foundation.js b/scripts/migrations/255-character-visual-foundation.js
index 54262c0a4b..7e4ef476f8 100644
--- a/scripts/migrations/255-character-visual-foundation.js
+++ b/scripts/migrations/255-character-visual-foundation.js
@@ -25,7 +25,7 @@ export const ACCEPTED_OLD_MD5 = {
export const NEW_SHIPPED_MD5 = {
'pipeline-character-foundation.md': 'c606061954b23a9957c68dd068b54dc4', // post-256 (series-linked cast)
- 'pipeline-judge-foundation.md': '75714f0e41c77ff5c8b9623cb4fb0a25', // post-256 (series-linked cast)
+ 'pipeline-judge-foundation.md': 'd4abf4ddafbf84a2903e6d70d14adea1', // post-256 (series-linked cast)
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/256-series-linked-character-profiles.js b/scripts/migrations/256-series-linked-character-profiles.js
index de2134e24b..2b1b00c716 100644
--- a/scripts/migrations/256-series-linked-character-profiles.js
+++ b/scripts/migrations/256-series-linked-character-profiles.js
@@ -17,7 +17,7 @@ export const ACCEPTED_OLD_MD5 = {
export const NEW_SHIPPED_MD5 = {
'pipeline-character-foundation.md': 'c606061954b23a9957c68dd068b54dc4',
- 'pipeline-judge-foundation.md': '75714f0e41c77ff5c8b9623cb4fb0a25',
+ 'pipeline-judge-foundation.md': 'd4abf4ddafbf84a2903e6d70d14adea1',
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/364-foundation-judge-cast-integrity.js b/scripts/migrations/364-foundation-judge-cast-integrity.js
index 089d10ae42..afc3848592 100644
--- a/scripts/migrations/364-foundation-judge-cast-integrity.js
+++ b/scripts/migrations/364-foundation-judge-cast-integrity.js
@@ -17,7 +17,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-judge-foundation.md': '75714f0e41c77ff5c8b9623cb4fb0a25',
+ 'pipeline-judge-foundation.md': 'd4abf4ddafbf84a2903e6d70d14adea1',
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/377-pilot-developmental-gate.js b/scripts/migrations/377-pilot-developmental-gate.js
new file mode 100644
index 0000000000..1070082bad
--- /dev/null
+++ b/scripts/migrations/377-pilot-developmental-gate.js
@@ -0,0 +1,19 @@
+import { makePromptReplaceMigration } from './_lib.js';
+export const ACCEPTED_OLD_MD5 = {
+ "pipeline-manuscript-completeness.md": [
+ "fd26f928c33803c12878a1bfb8561ece"
+ ],
+ "pipeline-judge-foundation.md": [
+ "75714f0e41c77ff5c8b9623cb4fb0a25"
+ ]
+};
+export const NEW_SHIPPED_MD5 = {
+ "pipeline-manuscript-completeness.md": "a08a7aaea9b57dcf12311505150672cd",
+ "pipeline-judge-foundation.md": "d4abf4ddafbf84a2903e6d70d14adea1"
+};
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5, current: NEW_SHIPPED_MD5, label: 'Pilot developmental review',
+ customizedHint: filename => ` Merge the opening-contract guidance from data.reference/prompts/stages/${filename} into your customized prompt.`,
+});
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/377-pilot-developmental-gate.test.js b/scripts/migrations/377-pilot-developmental-gate.test.js
new file mode 100644
index 0000000000..a46111a6e6
--- /dev/null
+++ b/scripts/migrations/377-pilot-developmental-gate.test.js
@@ -0,0 +1,6 @@
+import { describe } from 'vitest';
+import { runPromptMigrationTests } from './_testHelpers.js';
+import migration, { applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5 } from './377-pilot-developmental-gate.js';
+describe('migration 377 — pilot developmental review', () => {
+ runPromptMigrationTests({ migration, applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5, prefix: 'migration-377-' });
+});
diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.js
index 32ae00d6a5..c15dd99d7c 100644
--- a/scripts/setup-data-drift.test.js
+++ b/scripts/setup-data-drift.test.js
@@ -44,7 +44,7 @@ const EXPECTED_STAGE_OLD = {
'universe-character-expand.md': ['ef109eb8e12ddb664c11c790271b5139', '67b6e73ed47f318451a730088b4cff14', '177b6e4e8bdf445308cf8ac423cd5ad8', '924fe8836f3014873d1789e98e997db2'],
'story-builder-idea-expand.md': ['778c86e2caa120856c36e4d5a4da3355', 'a23939626a226f7420cebfb45d47950c'],
'pipeline-editorial-analysis.md': ['14d9879697c66d51830cc798040d5369'],
- 'pipeline-manuscript-completeness.md': ['4f2b95778aed85f5fc461d71eb461b79', 'e6858c74ab2cead752d388e3f428406c', '1ee5ac936fbf1d365e0eaea99bcf1e77', 'cec8faeb75dfff74e41b8221145c2e92'],
+ 'pipeline-manuscript-completeness.md': ['fd26f928c33803c12878a1bfb8561ece', '4f2b95778aed85f5fc461d71eb461b79', 'e6858c74ab2cead752d388e3f428406c', '1ee5ac936fbf1d365e0eaea99bcf1e77', 'cec8faeb75dfff74e41b8221145c2e92'],
'pipeline-manuscript-fix.md': ['196625952f4a36f3cb962c729f60f0ee', 'c88a56304eb5e290ae0de9dadd20b310', '88199bf7b5b50155bd2e1624bd920ebd'],
'cos-agent-briefing.md': ['181b26838e526427173e4dccfc884d01', '3e1ca7f7b14b799f89a193c568003624', '699d053875472df455258724a0162bd5', '9bcd3a0167dd4aed7cfff7f404494dfb', 'af73fd50d6f29d561772474c12346e53', 'd761133753da290a0c02eca1c87709e4', 'dccb392a43cbd3dac900fee12c31619a'],
'pipeline-editorial-telling-emotion.md': ['2c5c33709732fe7ffa319d32b8755354'],
@@ -55,7 +55,7 @@ const EXPECTED_STAGE_OLD = {
'cd-plan.md': ['02354df62fe776704669d3ff06f346e4', '41a61590896d1327df2c6915557361de', '3ce871196a8fd04781b71b6780e89c86', '0768d6809645c2c1fe73cacae9740fe9', 'ef0d96f6ebde43af6c4579969d31cfb7'],
'pipeline-series-generate.md': ['bc72731124a2bd6304362f4402c6305d', '21352c21ed6d4edb7a4b7c32704eff55'],
'pipeline-character-foundation.md': ['f1c0b75a8161c0bc7f26752d148a5c1c', 'cda34127b40754ddbcc8544e3d82572b', 'd6c449c06de73a0868141c899b26e52c', '04419e382f3b46ed92bfaaa1d4f39e13', 'b7d2bac347e11171606f4c6acfcd32e1'],
- 'pipeline-judge-foundation.md': ['74c0244e641dcf7a73e9c83123ebdee9', '4c0bd349ff4d329048c9f4ac068745d4', 'edf7850d0c724c63761bc9fb667227d9', '02a8e9215ba534b333f3a29f11f3ac4f', 'e44b6c50d741bbd21fc86f481684c410'],
+ 'pipeline-judge-foundation.md': ['75714f0e41c77ff5c8b9623cb4fb0a25', '74c0244e641dcf7a73e9c83123ebdee9', '4c0bd349ff4d329048c9f4ac068745d4', 'edf7850d0c724c63761bc9fb667227d9', '02a8e9215ba534b333f3a29f11f3ac4f', 'e44b6c50d741bbd21fc86f481684c410'],
'pipeline-observer.md': ['f3dc51ac077050a887c2161ee7438181'],
'pipeline-self-improve.md': ['ed0b0df42e0690d515b8dd88911931e4'],
'fableloom-editorial-remediate.md': ['d73329e2341e7bea9935a96043ed045f'],
@@ -99,7 +99,7 @@ const EXPECTED_STAGE_NEW = {
'universe-character-expand.md': '961b73ba6e50df5d49f0cc76505e50bd',
'story-builder-idea-expand.md': 'c12d76fefaaded2838023065bfc94bb0',
'pipeline-editorial-analysis.md': 'daeb02bd54b0c099b21af659c6298cfe',
- 'pipeline-manuscript-completeness.md': 'fd26f928c33803c12878a1bfb8561ece',
+ 'pipeline-manuscript-completeness.md': 'a08a7aaea9b57dcf12311505150672cd',
'pipeline-manuscript-fix.md': 'e2baaf0f2f53c8aa1e934a428c0ca583',
'pipeline-editorial-telling-emotion.md': '871f7e8bea2a2d95f28875ab45a318e2',
'pipeline-editorial-chekhov.md': '1f8a1696b5e4f476051dc5b2e5737db9',
@@ -109,7 +109,7 @@ const EXPECTED_STAGE_NEW = {
'cd-plan.md': '8dac4102dbbaee05f2f23f37c7e80782',
'pipeline-series-generate.md': '136a21435aba2b2b212883750040b986',
'pipeline-character-foundation.md': 'c606061954b23a9957c68dd068b54dc4',
- 'pipeline-judge-foundation.md': '75714f0e41c77ff5c8b9623cb4fb0a25',
+ 'pipeline-judge-foundation.md': 'd4abf4ddafbf84a2903e6d70d14adea1',
'pipeline-observer.md': '29e0212d2252b1be3278f20e2959eb8e',
'pipeline-self-improve.md': '95b378832ff78e5976a6a63fcf328090',
'fableloom-editorial-remediate.md': 'c0cce5cfe63ec4e94047415bbe83881b',
diff --git a/server/lib/README.md b/server/lib/README.md
index 74fe7e402d..d07b21e70a 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -482,7 +482,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `noReplaceMove.js` | `moveWithoutReplace(from, to)` — publish a staged file into its final name WITHOUT ever clobbering an existing one. `fs.rename` silently replaces its destination, which is the wrong default for a derived artifact; this uses `link(2)` + `unlink(2)`, so an existing destination fails atomically with `MOVE_DEST_EXISTS` and both files survive. Refuses rather than degrading when the filesystem cannot express it (`MOVE_CROSS_DEVICE`, `MOVE_NO_REPLACE_UNSUPPORTED`) — a `stat`-then-`rename` fallback would be a race. Used by the rigging publication contract (`services/rigging/autoSkin.js`). |
| `personaTraitBlend.js` | Digital-twin persona trait-blending (M34 P7). Blends a persona's `traitAdjustments` against the base twin's communication profile + Big-Five into a "Communication Calibration" directive. A pure leaf — `client/src/lib/personaTraitBlend.js` re-exports it for the Personas UI preview. |
| `textUtils.js` | Pure dependency-free prose helpers. `isStr(v)` and `isNonBlankStr(v)` are the ONLY string predicates under `server/` (#6837) — the bare type check, and type check plus a non-empty `trim()` for ids, keys, hosts, model names and prose fields where whitespace-only is already invalid; the "no private string predicate or bounder" guard in `textUtils.test.js` fails the suite when a copy of either, or a `trimTo`-shaped bounder, is re-declared in any non-test source under `server/` or any source under `client/src/` (`client/src/lib/textUtils.js` re-exports both for the browser bundle). `countWords(text)` is the canonical whitespace-token count (`\S+`) and the only one — every server word count (Writers Room, lettering density, rapid reader, autobiography, script-video beats) and the client's (`client/src/lib/textUtils.js` re-exports it) resolve here, and the "no private countWords" guard in `textUtils.test.js` fails the suite when a re-spelled count (the whitespace-token match, a split-and-filter, or a helper under either conventional name) reappears in any non-test source under `server/` or any source under `client/src/`; the editorial prose-analysis checks deliberately count LETTER words instead, through `editorial/proseTics.js#tokenizeWords`, which owns that tokenizer the same way; `trimTo(value, max)` trims and bounds strings without coercing non-strings, and is safe for shared modules consumed by the browser; `escapeRegExp(value)` is the one to import instead of re-inlining the escape (the sibling guard in `textUtils.test.js` fails the suite when a copy reappears in any non-test source under `server/`, or in ANY source under `client/src/`, tests and `.jsx` included — `client/src/lib/textUtils.js` re-exports this module for the browser bundle); `trimToClause(v, max)` is its boundary-aware twin for PROSE fields — it backs off to the last sentence terminator, then the last clause boundary, then the last whole word, so a capped field never ends mid-thought (it lives here rather than in `storyBible.js`, which re-exports it, so the pure story-model leaves the browser bundle shares can cap prose without pulling `crypto` / `fileUtils`); `kebabCase(text)` is the canonical ASCII slug transform (PLAN.md `[slug]` ids and `planner:<model>` labels); `clampToCharLimit(text, max)` is `trimTo`'s reader-facing twin — it cuts on a sentence end (when one sits 60%+ into the allowance) or a word boundary rather than mid-word and returns `{ text, truncated }` so the caller can say the text was cut, which is what bounds an AI-enhanced render prompt to a backend's hard cap (reactor.inc fast-h3 rejects an over-length prompt outright). |
-| `pipelineIssueOrder.js` | Pure renumber algorithm for pipeline issues. |
+| `pipelineIssueOrder.js` | Volume-based renumbering and `compareIssuesInSeries` for globally ordered manuscripts and production. |
| `pipelineStages.js` | Canonical pipeline data-stage groups, visible tab order, UI/voice labels, spoken aliases, and derived voice-intent regex. |
| `postAdaptive.js` | Pure POST adaptive-difficulty policy — nudges a math drill's primary knob (`steps`/`maxDigits`/`maxExponent`/`tolerancePct`) up/down within clamped bounds from recent scored performance. Opt-in via the config Adaptive toggle. |
| `postAppliedNumeracy.js` | Pure seeded Applied Numeracy pack — everyday percentage, ratio, unit, rate, and estimation scenarios plus server-authoritative numeric/fraction/unit scoring with explicit tolerance handling. |
diff --git a/server/lib/pipelineIssueOrder.js b/server/lib/pipelineIssueOrder.js
index 025b0dc26b..7f8620006f 100644
--- a/server/lib/pipelineIssueOrder.js
+++ b/server/lib/pipelineIssueOrder.js
@@ -19,6 +19,13 @@
* any `iss.number` actually changed (callers gate their disk writes on this).
*/
+// A stored issue's number is SERIES-global; arcPosition restarts in each
+// volume. Cross-volume manuscripts and production must use number first.
+// Keep local arcPosition ordering inside an already-selected volume.
+const seriesNumber = (issue) => Number.isFinite(issue?.number) && issue.number > 0 ? issue.number : Infinity;
+export const compareIssuesInSeries = (a, b) =>
+ (seriesNumber(a) - seriesNumber(b)) || (a?.arcPosition ?? 9999) - (b?.arcPosition ?? 9999);
+
export const UNSCOPED_ANCHOR = Symbol('pipelineIssueOrder.unscopedAnchor');
const byArcPosThenCreated = (a, b) => {
diff --git a/server/routes/pipeline/autopilot.js b/server/routes/pipeline/autopilot.js
index 5859e12d21..563b12f3af 100644
--- a/server/routes/pipeline/autopilot.js
+++ b/server/routes/pipeline/autopilot.js
@@ -87,6 +87,8 @@ const autopilotStartSchema = z.object({
// run — e.g. ['comic'] produces the comic draft and skips teleplay generation.
// Absent/empty = author every format the series targets.
targetFormats: z.array(z.enum(['comic', 'tv'])).optional(),
+ // Bound production while retaining the full series plan as editorial context.
+ productionScope: z.enum(['series', 'first-issue']).optional(),
// Per-run convergence bounds for the verify/review loops (0 = skip that gate).
// When omitted, the autopilot falls back to the persisted
// pipelineEditorialChecks.{maxArcVerifyRounds,maxEditorialRounds,maxBeatContinuityRounds}
diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.js
index 54e2b1b03e..d7c09ca1fe 100644
--- a/server/services/pipeline/arcPlanner.test.js
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -3590,27 +3590,22 @@ describe('arcPlanner — manuscript completeness + derive-from-manuscript', () =
expect(out.issues[1]).toMatchObject({ issueNumber: null, anchorQuote: '' });
});
- it('collectManuscriptSections orders by arcPosition, drops empties, and collectIssueSourceText stays byte-identical', async () => {
- const s = await setupSeries();
- // Insert out of arcPosition order to prove sorting (don't assert on the
- // auto-assigned `number`, which follows creation order, not arcPosition).
- await issuesSvc.createIssue({ seriesId: s.id, title: 'Two', arcPosition: 2, stages: { teleplay: { output: 'TELE two', status: 'ready' } } });
- await issuesSvc.createIssue({ seriesId: s.id, title: 'One', arcPosition: 1, stages: { comicScript: { output: 'PAGE 1\none', status: 'ready' } } });
- await issuesSvc.createIssue({ seriesId: s.id, title: 'Empty', arcPosition: 3 });
-
+ it('collects manuscript sections and editor formats in global issue order across volumes', async () => {
+ const s = await setupSeries();
+ const v1 = await seasonsSvc.createSeason(s.id, { number: 1, title: 'V1' });
+ const v2 = await seasonsSvc.createSeason(s.id, { number: 2, title: 'V2' });
+ // Creation is shuffled; local position restarts at 1 in the second volume.
+ for (const [seasonId, arcPosition, title] of [[v2.id, 1, 'Three'], [v1.id, 2, 'Two'], [v1.id, 1, 'One'], [v2.id, 2, 'Empty']]) {
+ await issuesSvc.createIssue({ seriesId: s.id, seasonId, title, arcPosition,
+ stages: title === 'Empty' ? {} : { prose: { output: `Draft ${title}`, status: 'ready' } } });
+ }
const sections = await planner.collectManuscriptSections(s.id);
- // Empty issue dropped; remaining two ordered by arcPosition (One before Two).
- expect(sections.map((x) => x.content)).toEqual(['PAGE 1\none', 'TELE two']);
- expect(sections.map((x) => x.stageId)).toEqual(['comicScript', 'teleplay']);
- expect(sections.map((x) => x.title)).toEqual(['One', 'Two']);
- expect(planner.primaryStageIdOf(sections)).toBeDefined();
-
- // The corpus join derives from the sections — verify the invariant.
+ expect(sections.map((section) => section.title)).toEqual(['One', 'Two', 'Three']);
+ expect(sections.map((section) => section.number)).toEqual([1, 2, 3]);
+ const formats = await planner.collectManuscriptByType(s.id);
+ expect(formats.sectionsByType.prose.map((section) => section.title)).toEqual(['One', 'Two', 'Three', 'Empty']);
const corpus = await planner.collectIssueSourceText(s.id, { stageOrder: planner.MANUSCRIPT_STAGES });
- const expected = sections
- .map((x) => `# Issue ${x.number} — ${x.title} (${x.stageId})\n\n${x.content}`)
- .join('\n\n---\n\n');
- expect(corpus).toBe(expected);
+ expect(corpus).toBe(sections.map((section) => `# Issue ${section.number} — ${section.title} (${section.stageId})\n\n${section.content}`).join('\n\n---\n\n'));
});
it('deriveFromManuscript proposes a single volume + bible + zipped issue synopses', async () => {
diff --git a/server/services/pipeline/arcPlanner/beatContinuity.js b/server/services/pipeline/arcPlanner/beatContinuity.js
index 0e31b5d40a..bc1ddfa229 100644
--- a/server/services/pipeline/arcPlanner/beatContinuity.js
+++ b/server/services/pipeline/arcPlanner/beatContinuity.js
@@ -133,9 +133,11 @@ export async function resolveBeatContinuity(seriesId, options = {}) {
seriesId,
series,
shapeBeatResolutions(content?.episodes),
+ { allowedIssueIds: options.allowedIssueIds },
);
const notes = typeof content?.notes === 'string' ? content.notes.trim().slice(0, 2000) : '';
- return { series, applied: true, notes, findings, episodesResolved, runId, providerId, model };
+ const outsideScope = episodesResolved.some((edit) => edit.skipped === 'outside-production-scope');
+ return { series, applied: !outsideScope, outsideScope, notes, findings, episodesResolved, runId, providerId, model };
}
/**
@@ -158,10 +160,19 @@ export async function resolveBeatContinuity(seriesId, options = {}) {
* dropped with a log so a number-scheme mismatch is diagnosable. Never throws.
* Returns `[{ issueId, number, seasonNumber, corrected, clearedStages, skipped }]`.
*/
-export async function applyBeatResolutions(seriesId, series, episodes) {
+export async function applyBeatResolutions(seriesId, series, episodes, { allowedIssueIds } = {}) {
if (!Array.isArray(episodes) || episodes.length === 0) return [];
const issues = await listIssues({ seriesId });
const seasonIdByNumber = seasonIdByNumberOf(series);
+ // Preflight the entire candidate before writing any beats or clearing derived
+ // scripts/art. A pilot-only run cannot regenerate a later issue it invalidates.
+ if (Array.isArray(allowedIssueIds)) {
+ const allowed = new Set(allowedIssueIds);
+ const outside = episodes.map((edit) => matchIssueForEpisodeEdit(issues, seasonIdByNumber, edit))
+ .filter((issue) => issue && !allowed.has(issue.id)
+ && issue.stages?.idea?.locked !== true && issue.stages?.idea?.output?.trim());
+ if (outside.length) return outside.map((issue) => ({ issueId: issue.id, number: issue.number, skipped: 'outside-production-scope' }));
+ }
const applied = [];
for (const edit of episodes) {
// Season match required when a resolvable season was named, else
diff --git a/server/services/pipeline/arcPlanner/context.js b/server/services/pipeline/arcPlanner/context.js
index 0e2fc130a5..a671f4932b 100644
--- a/server/services/pipeline/arcPlanner/context.js
+++ b/server/services/pipeline/arcPlanner/context.js
@@ -1,3 +1,4 @@
+import { compareIssuesInSeries } from '../../../lib/pipelineIssueOrder.js';
/**
* arcPlanner/context.js — shared context-building + collection helpers.
*
@@ -200,7 +201,7 @@ export const SOURCE_STAGE_ORDER = [...MANUSCRIPT_STAGES, 'idea'];
/**
* Concatenate the richest authored artifact per issue 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.
+ * case. Issues follow their series-global numbers so volumes do not interleave.
* Returns '' when no issue has text in any of `stageOrder`.
*
* `stageOrder` selects which stages count (and their precedence). The default
@@ -214,7 +215,7 @@ export const SOURCE_STAGE_ORDER = [...MANUSCRIPT_STAGES, 'idea'];
*/
export async function collectManuscriptSections(seriesId, { stageOrder = MANUSCRIPT_STAGES } = {}) {
if (!seriesId) return [];
- const issues = (await listIssues({ seriesId }).catch(() => [])).sort(compareIssuesByPosition);
+ const issues = (await listIssues({ seriesId }).catch(() => [])).sort(compareIssuesInSeries);
const sections = [];
for (const iss of issues) {
const st = iss.stages || {};
@@ -294,7 +295,7 @@ export async function collectManuscriptByType(seriesId) {
const sectionsByType = Object.fromEntries(MANUSCRIPT_STAGES.map((t) => [t, []]));
const counts = Object.fromEntries(MANUSCRIPT_STAGES.map((t) => [t, 0]));
if (!seriesId) return { sectionsByType, availableTypes: [], detectedPrimary: null };
- const issues = (await listIssues({ seriesId }).catch(() => [])).sort(compareIssuesByPosition);
+ const issues = (await listIssues({ seriesId }).catch(() => [])).sort(compareIssuesInSeries);
for (const iss of issues) {
const st = iss.stages || {};
for (const sid of MANUSCRIPT_STAGES) {
diff --git a/server/services/pipeline/arcPlanner/manuscriptDerive.js b/server/services/pipeline/arcPlanner/manuscriptDerive.js
index c618f43d05..40ff9454ee 100644
--- a/server/services/pipeline/arcPlanner/manuscriptDerive.js
+++ b/server/services/pipeline/arcPlanner/manuscriptDerive.js
@@ -1,3 +1,4 @@
+import { compareIssuesInSeries } from '../../../lib/pipelineIssueOrder.js';
/**
* arcPlanner/manuscriptDerive.js — derive an arc from existing manuscript /
* source text and commit the derived plan. Built on ./context.js + ./arcCore.js.
@@ -8,7 +9,7 @@ import { getSeries, updateSeries } from '../series.js';
import { getIssue, listIssues, recomputeIssueNumbersForSeries, updateIssue, updateStage } from '../issues.js';
import { emitRecordUpdated, withReexportSuppressed } from '../../sharing/recordEvents.js';
import { buildSeason, sanitizeArc, sanitizeSeason } from '../../../lib/storyArc.js';
-import { ERR_VALIDATION, collectIssueSourceText, compareIssuesByPosition, makeErr, shapeSeasonOutlines } from './context.js';
+import { ERR_VALIDATION, collectIssueSourceText, makeErr, shapeSeasonOutlines } from './context.js';
import { commitSeasonsWithRemap, mergeSeasonsWithLocks } from './arcCore.js';
/**
@@ -110,7 +111,7 @@ export async function deriveFromManuscript(seriesId, { providerOverride, modelOv
const { arc, seasons, raw, runId, providerId, model } = await generateArcFromSource(seriesId, {
sourceText, providerOverride, modelOverride,
});
- const issues = (await listIssues({ seriesId })).sort(compareIssuesByPosition);
+ const issues = (await listIssues({ seriesId })).sort(compareIssuesInSeries);
const issueMapping = issues.map((iss, i) => ({
id: iss.id,
number: iss.number,
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index f9b82b6b64..7fb43f97cb 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -138,6 +138,8 @@ export const AUTOPILOT_LLM_STAGE_KINDS = Object.freeze([
'beatSheet',
'beatContinuity',
'textStages',
+ 'pilotDraft',
+ 'pilotReview',
'scriptVerify',
'editorialReview',
'reverseOutline',
@@ -184,6 +186,7 @@ const sanitizeAutopilotResumeOptions = (raw) => {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
const out = {};
if (typeof raw.includeVisual === 'boolean') out.includeVisual = raw.includeVisual;
+ if (['series', 'first-issue'].includes(raw.productionScope)) out.productionScope = raw.productionScope;
if (typeof raw.fileGaps === 'boolean') out.fileGaps = raw.fileGaps;
const baseLlm = sanitizeAutopilotLlmRoute(raw);
if (baseLlm?.providerOverride) out.providerOverride = baseLlm.providerOverride;
diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
index c0336c1a0c..a90b599a24 100644
--- a/server/services/pipeline/seriesAutopilot.test.js
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -647,7 +647,7 @@ describe('resolveNextStep (pure)', () => {
const kinds = (opts) => autopilot.__testing.buildDryRunPlan(series, issues, opts).map((p) => p.kind);
// With editorial enabled (default), the reverse-outline refresh (#1349), both
// registry checks + health gate appear.
- expect(kinds({})).toEqual(expect.arrayContaining(['editorialReview', 'reverseOutline', 'editorialChecks', 'editorialHealthGate']));
+ expect(kinds({})).toEqual(expect.arrayContaining(['pilotReview', 'reverseOutline', 'editorialChecks', 'editorialHealthGate']));
// The reverse-outline refresh is enumerated BEFORE the editorial checks it feeds.
const defaultKinds = kinds({});
expect(defaultKinds.indexOf('reverseOutline')).toBeLessThan(defaultKinds.indexOf('editorialChecks'));
@@ -689,7 +689,8 @@ describe('resolveNextStep (pure)', () => {
// an arc verify + one volume verify = 3, so the 8-call budget buys 2 → +6.
expect(byKind.verifyArc.estActions).toBe(14);
// textStages: one child action per not-yet-text-ready issue (2 here).
- expect(byKind.textStages.estActions).toBe(2);
+ expect(byKind.pilotDraft.estActions).toBe(1);
+ expect(byKind.textStages.estActions).toBe(1);
// Pure-gate steps that bill nothing against the cap are zero-cost.
expect(byKind.editorialHealthGate.estActions).toBe(0);
});
@@ -711,7 +712,7 @@ describe('resolveNextStep (pure)', () => {
expect(actionsFor({ maxArcVerifyRounds: 4, maxArcIsolationAttempts: 0 }, 'verifyArc')).toBe(11);
expect(actionsFor({ maxArcVerifyRounds: 4, maxArcResolveRetries: 0 }, 'verifyArc')).toBe(11);
// Editorial review follows the same convergence shape.
- expect(actionsFor({ maxEditorialRounds: 2 }, 'editorialReview')).toBe(3);
+ expect(actionsFor({ maxEditorialRounds: 2 }, 'pilotReview')).toBe(3);
});
it('estimates editorialChecks LLM fan-out as issues × enabled LLM checks (#1576)', () => {
@@ -808,7 +809,7 @@ describe('resolveNextStep (pure)', () => {
it('skips a season already attempted for beats (no infinite loop)', () => {
const step = resolveNextStep(comic, [issue()], { arcVerified: true, foundationGated: true, beatsAttempted: new Set(['se1']) });
// beats skipped → falls through to text stages
- expect(step).toMatchObject({ kind: 'textStages', issueId: 'iss1' });
+ expect(step).toMatchObject({ kind: 'pilotDraft', issueId: 'iss1' });
});
it('runs whole-manuscript beat continuity once beats exist, before text (#1510)', () => {
@@ -829,14 +830,14 @@ describe('resolveNextStep (pure)', () => {
it('asks for text stages once beats are continuity-checked but scripts do not exist', () => {
const step = resolveNextStep(comic, [issue({ stages: { idea: ready() } })], { arcVerified: true, foundationGated: true, beatContinuityChecked: true });
- expect(step).toMatchObject({ kind: 'textStages', issueId: 'iss1' });
+ expect(step).toMatchObject({ kind: 'pilotDraft', issueId: 'iss1' });
});
it('asks for structural script verify once comic script is ready', () => {
const step = resolveNextStep(
comic,
[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
- { arcVerified: true, foundationGated: true, beatContinuityChecked: true },
+ { arcVerified: true, foundationGated: true, beatContinuityChecked: true, pilotReviewed: true },
);
expect(step).toMatchObject({ kind: 'scriptVerify', issueId: 'iss1' });
});
@@ -845,7 +846,7 @@ describe('resolveNextStep (pure)', () => {
const step = resolveNextStep(
comic,
[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
- { arcVerified: true, foundationGated: true, beatContinuityChecked: true, scriptChecked: new Set(['iss1']) },
+ { arcVerified: true, foundationGated: true, beatContinuityChecked: true, pilotReviewed: true, scriptChecked: new Set(['iss1']) },
);
expect(step.kind).toBe('editorialReview');
});
@@ -854,7 +855,7 @@ describe('resolveNextStep (pure)', () => {
const step = resolveNextStep(
comic,
[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
- { arcVerified: true, foundationGated: true, beatContinuityChecked: true, scriptChecked: new Set(['iss1']), editorialReviewed: true },
+ { arcVerified: true, foundationGated: true, beatContinuityChecked: true, pilotReviewed: true, scriptChecked: new Set(['iss1']), editorialReviewed: true },
{ includeVisual: false },
);
expect(step.kind).toBe('reverseOutline');
@@ -864,7 +865,7 @@ describe('resolveNextStep (pure)', () => {
const step = resolveNextStep(
comic,
[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
- { arcVerified: true, foundationGated: true, beatContinuityChecked: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, reverseOutlineRefreshed: true },
+ { arcVerified: true, foundationGated: true, beatContinuityChecked: true, pilotReviewed: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, reverseOutlineRefreshed: true },
{ includeVisual: false },
);
expect(step.kind).toBe('editorialChecks');
@@ -874,7 +875,7 @@ describe('resolveNextStep (pure)', () => {
const step = resolveNextStep(
comic,
[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
- { arcVerified: true, foundationGated: true, beatContinuityChecked: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, reverseOutlineRefreshed: true, editorialChecksReviewed: true },
+ { arcVerified: true, foundationGated: true, beatContinuityChecked: true, pilotReviewed: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, reverseOutlineRefreshed: true, editorialChecksReviewed: true },
{ includeVisual: false },
);
expect(step.kind).toBe('editorialHealthGate');
@@ -884,7 +885,7 @@ describe('resolveNextStep (pure)', () => {
const step = resolveNextStep(
comic,
[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
- { arcVerified: true, foundationGated: true, beatContinuityChecked: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, reverseOutlineRefreshed: true, editorialChecksReviewed: true, editorialHealthReady: true },
+ { arcVerified: true, foundationGated: true, beatContinuityChecked: true, pilotReviewed: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, reverseOutlineRefreshed: true, editorialChecksReviewed: true, editorialHealthReady: true },
{ includeVisual: false },
);
expect(step.kind).toBe('done');
@@ -894,7 +895,7 @@ describe('resolveNextStep (pure)', () => {
const step = resolveNextStep(
comic,
[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
- { arcVerified: true, foundationGated: true, beatContinuityChecked: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, reverseOutlineRefreshed: true, editorialChecksReviewed: true, editorialHealthReady: true },
+ { arcVerified: true, foundationGated: true, beatContinuityChecked: true, pilotReviewed: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, reverseOutlineRefreshed: true, editorialChecksReviewed: true, editorialHealthReady: true },
{ includeVisual: true, target: 'text' },
);
expect(step.kind).toBe('done');
@@ -904,7 +905,7 @@ describe('resolveNextStep (pure)', () => {
const step = resolveNextStep(
comic,
[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
- { arcVerified: true, foundationGated: true, beatContinuityChecked: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, reverseOutlineRefreshed: true, editorialChecksReviewed: true, editorialHealthReady: true },
+ { arcVerified: true, foundationGated: true, beatContinuityChecked: true, pilotReviewed: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, reverseOutlineRefreshed: true, editorialChecksReviewed: true, editorialHealthReady: true },
{ includeVisual: true },
);
expect(step.kind).toBe('canonVerify');
@@ -914,7 +915,7 @@ describe('resolveNextStep (pure)', () => {
const step = resolveNextStep(
comic,
[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
- { arcVerified: true, foundationGated: true, beatContinuityChecked: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, reverseOutlineRefreshed: true, editorialChecksReviewed: true, editorialHealthReady: true, canonVerified: true },
+ { arcVerified: true, foundationGated: true, beatContinuityChecked: true, pilotReviewed: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, reverseOutlineRefreshed: true, editorialChecksReviewed: true, editorialHealthReady: true, canonVerified: true },
{ includeVisual: true },
);
expect(step).toMatchObject({ kind: 'visualDraft', issueId: 'iss1' });
@@ -933,7 +934,7 @@ describe('resolveNextStep (pure)', () => {
const step = resolveNextStep(
comic,
[issue({ stages: renderedStages })],
- { arcVerified: true, foundationGated: true, beatContinuityChecked: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, reverseOutlineRefreshed: true, editorialChecksReviewed: true, editorialHealthReady: true, canonVerified: true },
+ { arcVerified: true, foundationGated: true, beatContinuityChecked: true, pilotReviewed: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, reverseOutlineRefreshed: true, editorialChecksReviewed: true, editorialHealthReady: true, canonVerified: true },
{ includeVisual: true },
);
expect(step.kind).toBe('done');
@@ -946,7 +947,7 @@ describe('resolveNextStep (pure)', () => {
[issue({ stages: { idea: ready(), teleplay: ready() } })],
{ arcVerified: true, foundationGated: true, beatContinuityChecked: true },
);
- expect(step.kind).toBe('editorialReview');
+ expect(step.kind).toBe('pilotReview');
});
// CDO Phase 3 (#2185) — the opt-in teaser deliverable is the LAST step, after
@@ -960,7 +961,7 @@ describe('resolveNextStep (pure)', () => {
pages: [{ panels: [{ description: 'x' }], proofImage: { jobId: 'p0' } }],
},
};
- const fullyReady = { arcVerified: true, foundationGated: true, beatContinuityChecked: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, reverseOutlineRefreshed: true, editorialChecksReviewed: true, editorialHealthReady: true, canonVerified: true };
+ const fullyReady = { arcVerified: true, foundationGated: true, beatContinuityChecked: true, pilotReviewed: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, reverseOutlineRefreshed: true, editorialChecksReviewed: true, editorialHealthReady: true, canonVerified: true };
it('does NOT ask for a teaser by default (produceTeaser off) — stays done', () => {
const step = resolveNextStep(comic, [issue({ stages: rendered })], fullyReady, { includeVisual: true });
@@ -1124,7 +1125,7 @@ describe('resolveNextStep — revision cycle ordering (#2171)', () => {
const issue = (over = {}) => ({ id: 'iss1', seasonId: 'se1', number: 1, arcPosition: 1, stages: {}, ...over });
// Health-clean base runState (everything up to and including the health gate).
const healthClean = {
- arcVerified: true, foundationGated: true, beatContinuityChecked: true, scriptChecked: new Set(['iss1']),
+ arcVerified: true, foundationGated: true, beatContinuityChecked: true, pilotReviewed: true, scriptChecked: new Set(['iss1']),
editorialReviewed: true, reverseOutlineRefreshed: true, editorialChecksReviewed: true,
editorialHealthReady: true,
};
@@ -1294,7 +1295,7 @@ describe('milestone map telemetry', () => {
expect(start.mode).toBe('execute');
// Same projection the dry-run emits — the panel draws it as the milestone map.
expect(start.plan.map((p) => p.kind)).toEqual(
- expect.arrayContaining(['verifyArcSpine', 'verifyArc', 'editorialReview']),
+ expect.arrayContaining(['verifyArcSpine', 'verifyArc', 'pilotReview']),
);
expect(start.planTotals.estActions).toBeGreaterThan(0);
});
@@ -1308,7 +1309,7 @@ describe('milestone map telemetry', () => {
expect(progressFrames.length).toBeGreaterThan(0);
const final = progressFrames.at(-1);
expect(final.completed.verifyArcSpine).toBe(1);
- expect(final.completed.editorialReview).toBe(1);
+ expect(final.completed.pilotReview).toBe(1);
// …and what each gate actually validated, keyed by step kind.
expect(final.verified.verifyArcSpine).toMatchObject({ blocking: 0 });
});
@@ -1429,7 +1430,9 @@ describe('dry-run plan ↔ resolveNextStep drift guard (#1577)', () => {
case 'beatContinuity':
runState.beatContinuityChecked = true;
break;
+ case 'pilotDraft':
case 'textStages': {
+ runState.editorialReviewed = false;
// Satisfy textReady for every script format (comic + tv) so the mutator
// stays target-agnostic.
const issue = issues.find((i) => i.id === step.issueId);
@@ -1440,6 +1443,10 @@ describe('dry-run plan ↔ resolveNextStep drift guard (#1577)', () => {
case 'scriptVerify':
runState.scriptChecked.add(step.issueId);
break;
+ case 'pilotReview':
+ runState.pilotReviewed = true;
+ runState.editorialReviewed = true;
+ break;
case 'editorialReview':
runState.editorialReviewed = true;
// Mirror runEditorial: maxEditorialRounds === 0 marks the whole editorial
@@ -1648,6 +1655,29 @@ async function seedComplete({ script = VALID_SCRIPT } = {}) {
return { seriesId: series.id, seasonId, issueId: issue.id };
}
+it('blocks expansion on an unresolved pilot and confines first-issue production after it passes', async () => {
+ const { seriesId, seasonId, issueId } = await seedComplete();
+ const later = await issuesSvc.createIssue({ seriesId, seasonId, title: 'Later', number: 2 });
+ await issuesSvc.updateStage(later.id, 'idea', ready('later beats'));
+ editorialFindings = [{ severity: 'high', problem: 'The opening has no personal choice or aftermath' }];
+ await autopilot.startSeriesAutopilot(seriesId, { includeVisual: false, maxEditorialRounds: 1 });
+ await waitFor(runFinished(seriesId));
+ expect(autopilot.__testing.runs.get(seriesId).lastPayload).toMatchObject({ type: 'paused', scope: 'pilotReview' });
+ expect(autoRunnerSpies.startAutoRunTextStages).not.toHaveBeenCalled();
+ expect((await issuesSvc.getIssue(later.id)).stages.comicScript.output).toBe('');
+
+ editorialFindings = [];
+ await autopilot.startSeriesAutopilot(seriesId, { productionScope: 'first-issue', includeVisual: false });
+ await waitFor(runFinished(seriesId));
+ expect(autopilot.__testing.runs.get(seriesId).lastPayload.type).toBe('complete');
+ expect(autoRunnerSpies.startAutoRunTextStages).not.toHaveBeenCalled();
+ expect(verifyComicScript.mock.calls.map(([id]) => id)).toEqual([issueId]);
+ expect(autopilot.__testing.runs.get(seriesId).options.productionScope).toBe('first-issue');
+ const plan = autopilot.__testing.buildDryRunPlan(await seriesSvc.getSeries(seriesId), await issuesSvc.listIssues(seriesId), { productionScope: 'first-issue' });
+ expect(plan.some((step) => step.kind === 'textStages')).toBe(false);
+ expect(plan.find((step) => step.kind === 'editorialChecks').estLlmCalls).toBe(1);
+});
+
it('normalizes duplicate volume records before the conductor can seed their empty copies', async () => {
const { seriesId, seasonId } = await seedComplete();
const current = await seriesSvc.getSeries(seriesId);
@@ -2750,7 +2780,7 @@ describe('autopilot conductor', () => {
await waitFor(runFinished(seriesId));
const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
expect(last?.type).toBe('paused');
- expect(last?.scope).toBe('editorialReview');
+ expect(last?.scope).toBe('pilotReview');
});
it('posts an in-app notification when a run pauses, with a resume link (#1615)', async () => {
@@ -2797,7 +2827,7 @@ describe('autopilot conductor', () => {
expect(series.autopilot.plan.every((r) => typeof r.kind === 'string' && r.count >= 1)).toBe(true);
// …and the progress half: where it actually got to, including the step it
// stopped on (which is what the map draws as blocked).
- expect(series.autopilot?.progress?.currentStep).toBe('editorialReview');
+ expect(series.autopilot?.progress?.currentStep).toBe('pilotReview');
expect(Object.keys(series.autopilot.progress.completed).length).toBeGreaterThan(0);
});
@@ -3829,7 +3859,7 @@ describe('autopilot conductor', () => {
await waitFor(runFinished(seriesId));
const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
expect(last?.type).toBe('paused');
- expect(last?.scope).toBe('textStages');
+ expect(last?.scope).toBe('pilotDraft');
expect(last?.pauseKind).toBe('childFailed');
expect(last?.reason).toMatch(/did not produce required stage/);
// one initial attempt + one retry before the escalation pause.
@@ -3974,7 +4004,7 @@ describe('autopilot conductor', () => {
expect(arcSpies.analyzeBeatContinuity).not.toHaveBeenCalled();
const series = await seriesSvc.getSeries(seriesId);
expect(series.autopilot?.status).toBe('paused');
- expect(series.autopilot?.currentStep).toBe('scriptVerify'); // not 'verifyArc'/'beatContinuity'
+ expect(series.autopilot?.currentStep).toBe('pilotReview'); // not 'verifyArc'/'beatContinuity'
expect(series.autopilot?.lastError).toMatch(/budget/);
});
@@ -4066,7 +4096,7 @@ describe('autopilot conductor', () => {
reverseOutlineConsumed = false; // subset skips every outline-consuming check
reverseOutlineState = { status: 'complete', stale: true }; // stale, but unused
getDomainBudgetStatus.mockImplementation(async () => (
- arcSpies.analyzeManuscriptCompleteness.mock.calls.length >= 1
+ arcSpies.analyzeManuscriptCompleteness.mock.calls.length >= 1 && verifyComicScript.mock.calls.length >= 1
? { withinBudget: false, exceeded: 'actions' }
: { withinBudget: true, exceeded: null }
));
@@ -4339,7 +4369,7 @@ describe('autopilot conductor', () => {
await waitFor(runFinished(series.id));
const last = autopilot.__testing.runs.get(series.id)?.lastPayload;
expect(last?.type).toBe('paused');
- expect(last?.scope).toBe('textStages');
+ expect(last?.scope).toBe('pilotDraft');
expect(last?.reason).toMatch(/comicScript/);
});
@@ -4723,6 +4753,22 @@ describe('beat-continuity resolve (#1510)', () => {
return { series: fresh, issueId: issue.id };
}
+ it('rejects the whole candidate before clearing art when a pilot repair targets a later issue', async () => {
+ const { series, issueId } = await seedIssueWithBeats();
+ const later = await issuesSvc.createIssue({ seriesId: series.id, seasonId: series.seasons[0].id, title: 'Later', arcPosition: 2 });
+ await issuesSvc.updateStage(later.id, 'idea', ready('later beats'));
+ await issuesSvc.updateStage(later.id, 'comicScript', ready('later script'));
+ await issuesSvc.updateStage(later.id, 'comicPages', { pages: [{ panels: [{ description: 'keep' }], proofImage: { filename: 'keep.png' } }] });
+ const before = await issuesSvc.getIssue(later.id);
+ const result = await applyBeatResolutions(series.id, series, [
+ { seasonNumber: 1, episodeNumber: 1, beats: 'new pilot beats' },
+ { seasonNumber: 1, episodeNumber: 2, beats: 'new later beats' },
+ ], { allowedIssueIds: [issueId] });
+ expect(result).toEqual([{ issueId: later.id, number: 2, skipped: 'outside-production-scope' }]);
+ expect((await issuesSvc.getIssue(issueId)).stages.idea.output).toBe('old beats');
+ expect((await issuesSvc.getIssue(later.id)).stages).toEqual(before.stages);
+ });
+
it('writes the corrected beats to BOTH idea.input and idea.output so prose adapts from the fix', async () => {
const { series, issueId } = await seedIssueWithBeats();
const applied = await applyBeatResolutions(series.id, series, [{ seasonNumber: 1, episodeNumber: 1, beats: 'corrected beats' }]);
diff --git a/server/services/pipeline/seriesAutopilot/childRuns.js b/server/services/pipeline/seriesAutopilot/childRuns.js
index 734c7ae49b..afca33ebf5 100644
--- a/server/services/pipeline/seriesAutopilot/childRuns.js
+++ b/server/services/pipeline/seriesAutopilot/childRuns.js
@@ -35,7 +35,7 @@ import { createDiscardedBank } from './discardedEvidence.js';
import { createArcMutationLedger } from '../arcMutationLedger.js';
import { broadcast, budgetPause, providerOverrideOpts, providerIdOpts, roleLlm, seasonPreserveOpts } from './session.js';
import { recordModelOutcome } from './modelPerformance.js';
-import { requiredScriptStages, textReady } from './stepResolver.js';
+import { productionIssues, requiredScriptStages, textReady } from './stepResolver.js';
const MAX_PLANNING_GATE_HANDOFFS = 6;
@@ -724,8 +724,17 @@ export async function runBeatContinuity(seriesId, record) {
// single step can't overspend the daily cap mid-loop.
const beforeResolve = await budgetPause();
if (beforeResolve) return beforeResolve;
- const resolved = await resolveBeatContinuity(seriesId, { findings: blocking, ...providerOverrideOpts(record) });
+ const scopedIssues = record.options.productionScope === 'first-issue'
+ ? productionIssues(await listIssues({ seriesId }), record.options).map((issue) => issue.id)
+ : undefined;
+ const resolved = await resolveBeatContinuity(seriesId, {
+ findings: blocking, ...providerOverrideOpts(record),
+ ...(scopedIssues ? { allowedIssueIds: scopedIssues } : {}),
+ });
await recordDomainUsage('cos', { actions: 1 });
+ if (resolved?.outsideScope) {
+ return { pause: true, pauseKind: 'scope', reason: 'Continuity repair needs to rewrite a later drafted issue. Select whole-series production to rebuild its scripts and art; no beat edits were applied.', residual: blocking };
+ }
// No per-record counts here, and none missing: this resolver rewrites
// episode beats and nothing else, so `episodesEdited` IS the whole account
// of what it wrote — unlike the arc gate, whose resolver spans the arc,
@@ -1268,14 +1277,21 @@ export const runBeats = (seriesId, seasonId, record) => runChildToCompletion(ser
attemptedSet: record.runState.beatsAttempted,
kind: 'beats',
id: seasonId,
- start: () => volumeBeatsRunner.startVolumeBeatsRun(seriesId, seasonId, { mode: 'skip-existing', ...providerIdOpts(record) }),
+ start: async () => {
+ const scoped = productionIssues(await listIssues({ seriesId }), record.options);
+ return volumeBeatsRunner.startVolumeBeatsRun(seriesId, seasonId, {
+ mode: 'skip-existing',
+ ...(record.options.productionScope === 'first-issue' ? { issueIds: scoped.map((issue) => issue.id) } : {}),
+ ...providerIdOpts(record),
+ });
+ },
isActive: volumeBeatsRunner.isVolumeBeatsRunActive,
// Beats succeeded when every issue in the volume has a ready `idea` stage —
// the same predicate the resolver uses to decide a volume still needs beats.
// Before #1574 a failed beats run was silently marked attempted and only
// surfaced (if at all) when a downstream stage found `idea` empty.
checkReady: async () => {
- const inSeason = (await listIssues({ seriesId })).filter((i) => i.seasonId === seasonId);
+ const inSeason = productionIssues(await listIssues({ seriesId }), record.options).filter((i) => i.seasonId === seasonId);
const missing = inSeason.filter((i) => !isStageReady(i.stages?.idea));
if (missing.length === 0) return null;
return {
diff --git a/server/services/pipeline/seriesAutopilot/diagnosisCore.js b/server/services/pipeline/seriesAutopilot/diagnosisCore.js
index ade2db8fa2..4d6c794cc3 100644
--- a/server/services/pipeline/seriesAutopilot/diagnosisCore.js
+++ b/server/services/pipeline/seriesAutopilot/diagnosisCore.js
@@ -142,6 +142,8 @@ export const STEP_SEQUENCE = [
'verifyArc — cross-volume synopsis continuity verify → resolve loop',
'beatSheet — per-volume beat sheets',
'beatContinuity — whole-manuscript beat-level continuity loop',
+ 'pilotDraft — draft the opening issue',
+ 'pilotReview — developmental review before drafting later issues',
'textStages — per-issue prose + scripts',
'scriptVerify — structural page/panel parse gate + advisory craft gate',
'editorialReview — series-level manuscript completeness review → fix loop',
diff --git a/server/services/pipeline/seriesAutopilot/dispatch.js b/server/services/pipeline/seriesAutopilot/dispatch.js
index ee2f90b38d..b11d6218bc 100644
--- a/server/services/pipeline/seriesAutopilot/dispatch.js
+++ b/server/services/pipeline/seriesAutopilot/dispatch.js
@@ -32,8 +32,17 @@ export async function dispatchStep(sId, step, record) {
return runBeatContinuity(sId, record);
case 'foundationGate':
return runFoundationGate(sId, record);
+ case 'pilotDraft':
case 'textStages':
+ // New pages must receive their own final review, even when the opening
+ // already passed the earlier developmental checkpoint.
+ record.runState.editorialReviewed = false;
return runText(sId, step.issueId, record);
+ case 'pilotReview': {
+ const result = await runEditorial(sId, record);
+ if (!result?.pause && !result?.canceled) record.runState.pilotReviewed = true;
+ return result;
+ }
case 'scriptVerify':
return runScriptVerify(sId, step.issueId, record);
case 'editorialReview':
diff --git a/server/services/pipeline/seriesAutopilot/dryRun.js b/server/services/pipeline/seriesAutopilot/dryRun.js
index 4b94acd349..d7b9794160 100644
--- a/server/services/pipeline/seriesAutopilot/dryRun.js
+++ b/server/services/pipeline/seriesAutopilot/dryRun.js
@@ -13,7 +13,7 @@ import {
arcIsolationActions,
} from './config.js';
import { roundsNote, convergenceLoopActions, VISUAL_DRAFT_ENABLED } from './convergence.js';
-import { orderedIssues, byNumber, issueHasBeats, textReady, wantsComic, visualReady } from './stepResolver.js';
+import { orderedIssues, productionIssues, byNumber, issueHasBeats, textReady, wantsComic, visualReady } from './stepResolver.js';
import { editorialSubsetIds } from './editorialSteps.js';
import { countSeriesLocks } from './unlockPass.js';
@@ -129,8 +129,11 @@ export function buildDryRunPlan(series, issues, options, costContext = {}) {
note: `${roundsNote(arcRounds)}; whole arc + ${seasons.length} volume(s) per round`,
estActions: verificationActions,
});
+ const production = productionIssues(ordered, options);
+ const reviewedCount = ordered.filter((issue) => production.some((target) => target.id === issue.id)
+ || textReady(issue, series, options)).length;
const beatsNeeded = seasons.filter((s) =>
- ordered.some((i) => i.seasonId === s.id && !isStageReady(i.stages?.idea))).length;
+ production.some((i) => i.seasonId === s.id && !isStageReady(i.stages?.idea))).length;
if (beatsNeeded) plan.push({ kind: 'beatSheet', count: beatsNeeded, estActions: beatsNeeded });
// beatContinuity (#1510) runs once when the run will have a beat corpus to
// check: beats already exist, OR beatSheet will generate them this run. Mirror
@@ -142,15 +145,24 @@ export function buildDryRunPlan(series, issues, options, costContext = {}) {
: MAX_BEAT_CONTINUITY_ROUNDS;
plan.push({ kind: 'beatContinuity', count: 1, note: roundsNote(bcRounds), estActions: convergenceLoopActions(bcRounds) });
}
- const textNeeded = ordered.filter((i) => !textReady(i, series, options)).length;
- if (textNeeded) plan.push({ kind: 'textStages', count: textNeeded, estActions: textNeeded });
- if (wantsComic(series, options)) plan.push({ kind: 'scriptVerify', count: ordered.length, estActions: ordered.length });
+ const opening = production[0];
+ if (opening && !textReady(opening, series, options)) {
+ plan.push({ kind: 'pilotDraft', count: 1, estActions: 1 });
+ }
const edRounds = Number.isInteger(options?.maxEditorialRounds) ? options.maxEditorialRounds : MAX_EDITORIAL_ROUNDS;
+ if (opening && edRounds !== 0) {
+ plan.push({ kind: 'pilotReview', count: 1, note: `${roundsNote(edRounds)}; setup, character choices and aftermath before expanding the manuscript`, estActions: convergenceLoopActions(edRounds) });
+ }
+ const textNeeded = production.slice(1).filter((i) => !textReady(i, series, options)).length;
+ if (textNeeded) plan.push({ kind: 'textStages', count: textNeeded, estActions: textNeeded });
+ if (wantsComic(series, options)) plan.push({ kind: 'scriptVerify', count: production.length, estActions: production.length });
// Editorial review is a verify→auto-fix convergence loop like the arc gate, so
// the per-round estimate mirrors it (analyze + one resolve batch / round). The
// per-comment auto-fixes within a round bill additionally and scale with the
// number of blocking findings, which isn't knowable at plan time.
- plan.push({ kind: 'editorialReview', count: 1, note: roundsNote(edRounds), estActions: convergenceLoopActions(edRounds) });
+ if (textNeeded || !opening || edRounds === 0) {
+ plan.push({ kind: 'editorialReview', count: 1, note: roundsNote(edRounds), estActions: convergenceLoopActions(edRounds) });
+ }
// maxEditorialRounds === 0 skips the whole editorial gate in execute mode
// (runEditorial marks editorialReviewed + editorialChecksReviewed +
// editorialHealthReady), so the plan must not advertise the registry checks or
@@ -170,7 +182,9 @@ export function buildDryRunPlan(series, issues, options, costContext = {}) {
const llmCheckCount = Number.isInteger(costContext?.editorialLlmCheckCount)
? costContext.editorialLlmCheckCount
: 1;
- const estLlmCalls = ordered.length * llmCheckCount;
+ // Only manuscripts already drafted or produced by THIS run reach these
+ // checks. Synopsis placeholders are context, not 31 extra manuscripts.
+ const estLlmCalls = reviewedCount * llmCheckCount;
const checksNote = editorialSubset
? `per-run subset of ${editorialSubset.length} editorial check(s) (#1575)`
: 'enabled editorial checks (#1284)';
@@ -201,7 +215,7 @@ export function buildDryRunPlan(series, issues, options, costContext = {}) {
kind: 'revisionCycle',
count: rev.revisionMaxCycles,
note: `iterate-to-quality (up to ${rev.revisionMaxCycles} cycle(s), min ${rev.revisionMinCycles}, plateau Δ ${rev.revisionPlateauDelta})`,
- estActions: rev.revisionMaxCycles * (ordered.length + 2),
+ estActions: rev.revisionMaxCycles * (reviewedCount + 2),
});
}
if (VISUAL_DRAFT_ENABLED && wantsVisual(options) && wantsComic(series, options)) {
@@ -210,7 +224,7 @@ export function buildDryRunPlan(series, issues, options, costContext = {}) {
// snapshot cannot know that future script reference set, so keep the base
// estimate at zero and name the conditional spend explicitly.
plan.push({ kind: 'canonVerify', count: 1, note: 'descriptive integrity of drawn nouns (may spend one LLM call per affected issue to backfill strictly from prose)', estActions: 0 });
- const visualNeeded = ordered.filter((i) => !visualReady(i)).length;
+ const visualNeeded = production.filter((i) => !visualReady(i)).length;
// Each draft render bills one cos action: cover + back per issue, plus one per
// interior page. The interior-page count isn't known until the script parses,
// so the estimate counts the two covers and notes the per-page additions.
@@ -218,7 +232,7 @@ export function buildDryRunPlan(series, issues, options, costContext = {}) {
// Teaser deliverable (#2185, opt-in, default off): one CD video project per
// issue. Each mint+start bills one cos action for the treatment LLM call; the
// CD project's own render spend is gated on the creative/cos budget its side.
- if (wantsTeaser(options)) plan.push({ kind: 'produceTeaser', count: ordered.length, note: 'mint + start a Creative Director teaser video per issue (opt-in)', estActions: ordered.length });
+ if (wantsTeaser(options)) plan.push({ kind: 'produceTeaser', count: production.length, note: 'mint + start a Creative Director teaser video per issue (opt-in)', estActions: production.length });
}
return plan;
}
diff --git a/server/services/pipeline/seriesAutopilot/orchestrator.js b/server/services/pipeline/seriesAutopilot/orchestrator.js
index 6d6c175d5e..e73e6fd650 100644
--- a/server/services/pipeline/seriesAutopilot/orchestrator.js
+++ b/server/services/pipeline/seriesAutopilot/orchestrator.js
@@ -188,6 +188,7 @@ export async function startSeriesAutopilot(sId, options = {}) {
// routes here at most once per run.
foundationGated: false,
beatContinuityChecked: false,
+ pilotReviewed: false,
editorialReviewed: false,
reverseOutlineRefreshed: false,
editorialChecksReviewed: false,
diff --git a/server/services/pipeline/seriesAutopilot/session.js b/server/services/pipeline/seriesAutopilot/session.js
index 85d60762a5..76391f1fcc 100644
--- a/server/services/pipeline/seriesAutopilot/session.js
+++ b/server/services/pipeline/seriesAutopilot/session.js
@@ -156,6 +156,7 @@ export async function persistMarker(seriesId, patch) {
const resumable = ['running', 'paused', 'error'].includes(patch.status) && run?.options
? {
includeVisual: run.options.includeVisual !== false,
+ ...(run.options.productionScope ? { productionScope: run.options.productionScope } : {}),
fileGaps: run.options.fileGaps === true,
...(run.options.providerOverride ? { providerOverride: run.options.providerOverride } : {}),
...(run.options.modelOverride ? { modelOverride: run.options.modelOverride } : {}),
@@ -366,7 +367,9 @@ export const roleLlm = (record, role = 'creative') => {
const roleRoute = role === 'judge'
? inheritLlmRoute(options.judgeLlm, base)
: base;
- const stageRoute = options.stageLlm?.[record?.currentStep]?.[role];
+ const inheritedStep = { pilotDraft: 'textStages', pilotReview: 'editorialReview' }[record?.currentStep];
+ const stageRoute = options.stageLlm?.[record?.currentStep]?.[role]
+ || options.stageLlm?.[inheritedStep]?.[role];
if (stageRoute && typeof stageRoute === 'object' && Object.keys(stageRoute).length > 0) {
return inheritLlmRoute(stageRoute, roleRoute);
}
diff --git a/server/services/pipeline/seriesAutopilot/stepResolver.js b/server/services/pipeline/seriesAutopilot/stepResolver.js
index 1b6cf89cc9..d9fb4c24b2 100644
--- a/server/services/pipeline/seriesAutopilot/stepResolver.js
+++ b/server/services/pipeline/seriesAutopilot/stepResolver.js
@@ -1,3 +1,4 @@
+import { compareIssuesInSeries } from '../../../lib/pipelineIssueOrder.js';
/**
* Series Autopilot — deterministic step resolution (#2842 split of
* seriesAutopilot.js). Pure: given the series, its issues and the run state,
@@ -6,7 +7,7 @@
import { parseComicScript } from '../../../lib/comicScriptParser.js';
import { isStageReady } from '../issues.js';
-import { compareIssuesByPosition, hasDuplicateSeasonNumbers } from '../arcPlanner.js';
+import { hasDuplicateSeasonNumbers } from '../arcPlanner.js';
import { wantsTeaser, wantsVisual } from './config.js';
import { VISUAL_DRAFT_ENABLED } from './convergence.js';
@@ -18,6 +19,14 @@ const setHas = (s, v) => (s instanceof Set ? s.has(v) : Array.isArray(s) ? s.inc
export const byNumber = (a, b) => (a?.number ?? 9999) - (b?.number ?? 9999);
+// Production can stop at the opening issue while the foundation and continuity
+// passes still see the whole series plan. A pilot should prove the story works
+// before an author commits to drafting and drawing every planned issue.
+export function productionIssues(issues, options = {}) {
+ const ordered = orderedIssues(issues);
+ return options.productionScope === 'first-issue' ? ordered.slice(0, 1) : ordered;
+}
+
// The script stages a series must have drafted to be "story-ready", derived
// from its targetFormat. prose is the intermediate source the scripts adapt
// from — we gate on the final scripts so a script-first import (prose empty,
@@ -72,7 +81,7 @@ export function wantsComic(series, options = {}) {
export function orderedIssues(issues) {
- return [...(Array.isArray(issues) ? issues : [])].sort(compareIssuesByPosition);
+ return [...(Array.isArray(issues) ? issues : [])].sort(compareIssuesInSeries);
}
export function textReady(issue, series, options = {}) {
@@ -143,6 +152,7 @@ export function visualReady(issue) {
export function resolveNextStep(series, issues, runState = {}, options = {}) {
const seasons = Array.isArray(series?.seasons) ? [...series.seasons].sort(byNumber) : [];
const ordered = orderedIssues(issues);
+ const production = productionIssues(issues, options);
// STEP 0 — unlock everything this series owns (opt-in, see unlockPass.js).
// Must run BEFORE any generation step: a locked arc makes generateArc /
@@ -230,7 +240,7 @@ export function resolveNextStep(series, issues, runState = {}, options = {}) {
// STEP 4a — per-volume beat sheets (skip volumes already attempted this run).
for (const season of seasons) {
if (setHas(runState.beatsAttempted, season.id)) continue;
- const inSeason = ordered.filter((i) => i.seasonId === season.id);
+ const inSeason = production.filter((i) => i.seasonId === season.id);
if (inSeason.some((i) => !isStageReady(i.stages?.idea))) {
return { kind: 'beatSheet', seasonId: season.id, reason: `beats missing in volume ${season.number ?? '?'}` };
}
@@ -248,8 +258,20 @@ export function resolveNextStep(series, issues, runState = {}, options = {}) {
return { kind: 'beatContinuity', reason: 'whole-manuscript beat continuity not yet checked this run' };
}
+ // Review the opening before multiplying its problems into later scripts.
+ // The same developmental editor used at the end runs against the manuscript
+ // drafted so far; later drafting invalidates that final editorial checkpoint.
+ const opening = production[0];
+ if (opening && !textReady(opening, series, options) && !setHas(runState.textAttempted, opening.id)) {
+ return { kind: 'pilotDraft', issueId: opening.id, reason: 'draft the opening for developmental review' };
+ }
+ if (opening && textReady(opening, series, options) && !runState.pilotReviewed
+ && options.maxEditorialRounds !== 0) {
+ return { kind: 'pilotReview', issueId: opening.id, reason: 'review the opening before drafting later issues' };
+ }
+
// STEP 4b — per-issue text stages (prose + required scripts).
- for (const issue of ordered) {
+ for (const issue of production) {
if (setHas(runState.textAttempted, issue.id)) continue;
if (!textReady(issue, series, options)) {
return { kind: 'textStages', issueId: issue.id, reason: 'prose / scripts not ready' };
@@ -261,7 +283,7 @@ export function resolveNextStep(series, issues, runState = {}, options = {}) {
// comic-script verification with no comicScript (which would pause on an
// unparseable script).
if (wantsComic(series, options)) {
- for (const issue of ordered) {
+ for (const issue of production) {
if (setHas(runState.scriptChecked, issue.id)) continue;
return { kind: 'scriptVerify', issueId: issue.id, reason: 'comic script not yet structurally verified' };
}
@@ -323,7 +345,7 @@ export function resolveNextStep(series, issues, runState = {}, options = {}) {
// STEP 6 — draft visuals (cover + back + all interior pages).
if (VISUAL_DRAFT_ENABLED && wantsVisual(options) && wantsComic(series, options)) {
- for (const issue of ordered) {
+ for (const issue of production) {
if (setHas(runState.visualDrafted, issue.id)) continue;
if (visualReady(issue)) continue;
return { kind: 'visualDraft', issueId: issue.id, reason: 'comic pages not yet drafted' };
@@ -336,7 +358,7 @@ export function resolveNextStep(series, issues, runState = {}, options = {}) {
// itself requires visuals). Attempted-once per issue this run so a started (or
// failed) teaser can't re-loop the resolver back here.
if (VISUAL_DRAFT_ENABLED && wantsTeaser(options) && wantsComic(series, options)) {
- for (const issue of ordered) {
+ for (const issue of production) {
if (setHas(runState.teaserProduced, issue.id)) continue;
return { kind: 'produceTeaser', issueId: issue.id, reason: 'teaser video not yet produced' };
}
diff --git a/server/services/pipeline/volumeBeatsRunner.js b/server/services/pipeline/volumeBeatsRunner.js
index ba4e53fd92..b0ff0bb5f5 100644
--- a/server/services/pipeline/volumeBeatsRunner.js
+++ b/server/services/pipeline/volumeBeatsRunner.js
@@ -75,6 +75,7 @@ export async function startVolumeBeatsRun(seriesId, seasonId, options = {}) {
const all = await listIssues({ seriesId });
const volumeIssues = all
.filter((i) => i.seasonId === seasonId)
+ .filter((i) => !Array.isArray(options.issueIds) || options.issueIds.includes(i.id))
.sort(compareIssuesByPosition);
broadcast({
diff --git a/server/services/pipeline/volumeBeatsRunner.test.js b/server/services/pipeline/volumeBeatsRunner.test.js
index 8165f5cbc1..b40224c5d5 100644
--- a/server/services/pipeline/volumeBeatsRunner.test.js
+++ b/server/services/pipeline/volumeBeatsRunner.test.js
@@ -94,6 +94,14 @@ describe('pipeline volume beat-sheet runner', () => {
expect(generated.every((g) => g.stageId === 'idea')).toBe(true);
});
+ it('generates only selected pilot beats without expanding later issue placeholders', async () => {
+ const { series, season, issues } = await seed();
+ await runner.startVolumeBeatsRun(series.id, season.id, { issueIds: [issues[0].id] });
+ await waitFor(() => runner.__testing.runs.get(season.id)?.lastPayload?.type === 'complete');
+ expect(generated.map((entry) => entry.issueId)).toEqual([issues[0].id]);
+ expect((await issuesSvc.getIssue(issues[1].id)).stages.idea.output).toBe('');
+ });
+
it("skip-existing mode skips issues whose idea stage has output (status: 'ready' / 'edited')", async () => {
const { series, season, issues } = await seed({ issueCount: 3 });
await issuesSvc.updateStage(issues[1].id, 'idea', { status: 'ready', output: 'PREFILLED-BEATS' });