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

add Series Autopilot: drive a series to story-ready autonomously (Phase 1)

[._.]/ Adam Eivyc2221a7eeb0b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index b2652727f9..3dff0eaedc 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,10 @@
## Added
+- **Series Autopilot — drive a whole series toward "story-ready" autonomously (Phase 1).** A new `POST /api/pipeline/series/:id/autopilot/start` runs a *conductor* that inspects the series' current state and walks every missing step in order — generate arc → generate episodes per volume → verify arc → per-issue beat sheets → per-issue text stages (prose + scripts) → structural comic-script gate → series-level editorial review — by composing the existing pipeline service functions (it never re-implements generation). The "what's next" decision is a **pure resolver over the canonical records**, so it is non-destructive and resumable: anything already `ready`/`edited` is skipped (every pass runs `force:false`), and on restart you just start again and it picks up at the first still-missing step (a partially-built series is never clobbered). Progress streams over SSE (`/autopilot/progress`); `/autopilot/cancel` stops it (propagating to the active child runner); `/autopilot/status` exposes a thin persisted `series.autopilot` marker for resume/paused UI. Gated on the **cos** autonomy domain: `off` rejects the start (409), `dry-run` emits a no-side-effect `plan` of what it would do, `execute` runs and meters the daily cos action budget (pausing when exhausted). The arc-verify and editorial loops are **bounded** and **pause for human review** when they can't converge (arc verification can surface fresh findings every pass) — the residual findings are persisted on the marker. Boot recovery demotes a marker stuck at `running` to `paused`. Known scope: comic-script verification is a structural parse gate only (a craft-level LLM verify is a follow-up), and draft cover/page rendering plus CoS gap-filing are Phase 2/3. (`server/services/pipeline/seriesAutopilot.js`, `server/routes/pipeline/autopilot.js`, `server/routes/pipeline/index.js`, `server/services/pipeline/series.js`, `server/index.js`)
+
+- **"Describe from prose" button on the Nouns stage backfills missing descriptions — and flags the nouns the manuscript can't describe.** Extracted nouns (characters/places/objects) often land with a name but no description, so a generated reference image has nothing to work from but the name. The new button writes a description for every undescribed noun that appears in the issue, using **only** what the prose actually establishes — and, crucially, it does **not** invent. This is the inverse of "Extract from prose" (which commits opinionated, renderable choices when the prose is silent so it never leaves a blank): a noun the manuscript names but never describes comes back graded `none` and stays blank, surfacing in a persistent red-flag banner ("The manuscript is thin on description for N nouns…") rather than being papered over with a fabricated look. Nouns the prose describes only in passing are graded `thin` (the grounded fragment is filled, with a note on what's missing). Strictly prose-grounded descriptions double as a manuscript-quality check: if the story can't describe its own people and places, that's a signal the prose needs enriching, not the bible. Fills only empty, unlocked entries (never clobbers an existing description or a locked one), re-reads freshest state at write time, and persists the gap report on the prose stage so the banner survives reload. Driven by a new strictly-grounded `pipeline-canon-describe-from-prose` stage prompt. (`data.reference/prompts/stages/pipeline-canon-describe-from-prose.md`, `scripts/migrations/089-canon-describe-from-prose-stage.js`, `server/services/universeCanon.js`, `server/routes/pipeline/issues.js`, `server/services/pipeline/issues.js`, `client/src/services/apiPipeline.js`, `client/src/components/pipeline/stages/NounsStage.jsx`)
+
- **"Generate with AI" button on the New Series form invents a fresh story in the chosen universe.** Creating a series previously pulled the universe's own logline/premise into the form, which nudged every series toward being a retelling of the world rather than a distinct story within it. The new button (enabled once a universe is picked) asks the configured AI provider to invent a *different* series — a fresh **name, logline, premise, and recommended Vonnegut story shape** — using the universe premise, style notes, embrace/avoid influences, and canon (characters/places/objects) as seed material, and is explicitly told to diverge from the universe's existing series (their names + loglines are passed in so it doesn't duplicate a premise). The concept pre-fills the form for the user to edit before creating — nothing is persisted by the generate call itself; a malformed/unknown story shape is dropped rather than poisoning the form, and the one-line rationale surfaces in the success toast. Driven by a new `pipeline-series-generate` stage prompt. (`data.reference/prompts/stages/pipeline-series-generate.md`, `server/services/pipeline/seriesGenerate.js`, `server/routes/pipeline/series.js`, `client/src/services/apiPipeline.js`, `client/src/pages/Pipeline.jsx`)
- **The AI Providers page now shows runtime availability, not just the enable toggle.** An enabled provider can still be *benched* (runtime-unavailable) after a failure — a usage limit, auth error, or `model-not-found` — and silently skipped in favor of a fallback, which made "but it's enabled!" confusing. Each enabled-but-unavailable provider now shows an **UNAVAILABLE · {reason}** badge plus a detail panel with the underlying error message ("Why: …"), the auto-retry ETA, and a **Recover now** button (clears the bench so the next call retries it — though a persistent cause like an invalid model id will simply re-bench on the next failure). The availability map refreshes every 20s so a badge appears/clears on its own. Reads the existing `GET /api/providers/status` (`available`/`reason`/`message`/`timeUntilRecovery`) — `enabled` is the user toggle, this is the separate runtime-health state the fallback router acts on. (`client/src/pages/AIProviders.jsx`)
diff --git a/docs/plans/2026-06-16-series-autopilot.md b/docs/plans/2026-06-16-series-autopilot.md
new file mode 100644
index 0000000000..ac0c82307a
--- /dev/null
+++ b/docs/plans/2026-06-16-series-autopilot.md
@@ -0,0 +1,280 @@
+# Series Pipeline — Full Autonomous Mode ("Series Autopilot")
+
+## Context
+
+The Series Pipeline today is a sequence of manually-triggered LLM/render steps: generate arc → generate
+issues → verify/resolve arc → per-issue text stages (idea → prose → comicScript/teleplay) → editorial review
+→ comic cover + pages. Every step is its own button/endpoint. Driving a whole graphic novel to completion
+means a human babysitting dozens of clicks across many issues.
+
+The ask: a single **"Run Autonomously to Completion"** control that takes a series and drives it from
+*wherever it currently is* to a terminal **story-ready + draft visuals** state, going through every missing
+step automatically. Per the user's steer — *"most of the pipeline itself can be a script that just triggers
+each of the APIs"* — the orchestrator is a **conductor that composes the existing service functions**, not a
+re-implementation of generation logic.
+
+Two hard constraints from the user:
+1. **Never undo in-progress work.** The real test series
+ `https://null.taile8179.ts.net:5555/pipeline/series/ser-b74601a3-221d-4491-b037-bad51df8460a` already has a
+ partially-generated arc and a partially-built first issue. Autopilot must inspect current state and resume
+ from the first *missing* step, never regenerate what exists.
+2. **Arc verification may never fully converge** — re-running verify surfaces *new* findings even after
+ fixing all prior ones. The resolve loop must be bounded and must **pause for human review** when it can't
+ reach clean, rather than spinning or silently proceeding.
+
+Decisions from the user:
+- **Scope:** one run targets the **entire series** — walk every season/volume in order.
+- **Visuals:** render **cover + back cover + all interior pages** in draft mode.
+- **Non-convergence:** **pause for human review** after the bounded rounds.
+
+## Design principle: resume is a pure function of current state
+
+The heart of the orchestrator is a **pure next-step resolver** — `resolveNextStep(series, issues, runState)`
+— that returns the first unmet step given the series' canonical records. Because "what to do next" is derived
+from state (not a stored cursor), the design is naturally **resumable and non-destructive**: it skips any
+stage that's already `ready`/`edited` (`isStageReady`), runs every generation with `force:false`, and on a
+crash/restart simply resumes at the first still-missing step. This is exactly what satisfies constraint #1 on
+the live test series.
+
+## Verified building blocks (reuse — do not reinvent)
+
+Service layer (`server/services/pipeline/`):
+- `arcPlanner` barrel → `generateArcOverview`, `commitSeasonsWithRemap`, `generateSeasonEpisodes`,
+ `commitEpisodesToIssues`, `verifyArc(seriesId,opts)` (arcCore.js:231), `verifyVolume` (arcCore.js:292),
+ `resolveVerifyIssues(seriesId,{findings,...})` (arcCore.js:322). verify* return
+ `{ issues:[{severity,location,problem,suggestion}], runId, ... }`.
+- `volumeBeatsRunner.startVolumeBeatsRun(seriesId,seasonId,{mode,providerId,model})` — **serial** per-issue
+ idea/beat generation (neighbor context), SSE keyed by seasonId, `isVolumeBeatsRunActive`,
+ `cancelVolumeBeatsRun`, `VOLUME_BEATS_MODES`.
+- `autoRunner.startAutoRunTextStages(issueId,{force,includeVideo})` — idea→prose→(comicScript+teleplay), SSE
+ keyed by issueId, `isAutoRunActive`, `cancelAutoRun`, `recoverStuckAutoRuns()` (autoRunner.js:201).
+- `textStages.generateStage`; `issues.isStageReady` (issues.js:117), `STAGE_IDS`/`TEXT_STAGE_IDS`/
+ `VISUAL_STAGE_IDS` (101-108), `ISSUE_STATUSES` (123), `queueSeriesIssuesWrite` (57),
+ `getIssue/listIssues/updateIssue/updateStage`.
+- Editorial: `editorialAnalysis.analyzeIssue` (179); `manuscriptReview.seedReviewFromFindings` (175);
+ `manuscriptFix.generateManuscriptFix` (461) / `acceptManuscriptFix` (559).
+- Visual/draft terminal: `visualStages.enqueueComicCover` (504), `enqueueComicBackCover` (517),
+ `enqueueVisualComicPage` (752); page/cover extraction service behind route
+ `POST /issues/:id/stages/comicPages/extract-pages` (requires comicScript output; parses pages + cover
+ concepts), cover render routes in `covers.js` (187/204/217).
+- Series shape: `TARGET_FORMATS` ['comic','tv','comic+tv'] (series.js:72), `series.arc`, `series.seasons[]`,
+ `series.locked`, `series.primaryManuscriptType`.
+
+Infra: `sseUtils` (`broadcastSse`,`attachSseClient`,`closeJobAfterDelay`,`SSE_CLEANUP_DELAY_MS`);
+`cosTaskStore.addTask(data, taskType, {raw})` (already dedups pending/in_progress by description+app,
+cosTaskStore.js:130); `domainAutonomy.getDomainMode(config,'cos')`;
+`domainUsage.getDomainBudgetStatus('cos')` / `recordDomainUsage('cos',{actions})` (gating precedent
+cosJobScheduler.js:207-238); `useSseProgress` hook (client).
+
+**Pattern to mirror exactly:** `editorialAnalysisRunner.js` — most complete runner lifecycle (`finished`
+flag, `cleanupTimer`, restart-replace, single permitted try/catch boundary in the fire-and-forget IIFE,
+cancel flag between steps, `export const __testing = { runs }`).
+
+## "Script verification" is a known gap (called out, not silently solved)
+
+There is **no dedicated comic-script verify endpoint** today. For MVP, define "script ready" as:
+1. **Structural gate (pure, no LLM):** comicScript `isStageReady` AND the extract-pages parser yields ≥1
+ page with ≥1 panel + a cover concept (reuse the parser the extract-pages route already imports).
+2. **Editorial gate:** run `analyzeIssue`; treat **high-severity** findings as blocking and auto-resolve via
+ `seedReviewFromFindings` → `generateManuscriptFix` → `acceptManuscriptFix`, bounded.
+
+A real LLM `pipeline-script-verify` prompt + migration is an explicit **Phase 3 follow-up**, documented in
+code comments so the gap isn't assumed solved.
+
+## 1. Orchestrator — `server/services/pipeline/seriesAutopilot.js` (NEW)
+
+In-memory `runs` Map keyed by **seriesId** (one autopilot per series; a second start while active resolves to
+the existing runId). Fire-and-forget IIFE with the single permitted try/catch boundary; cancel flag checked
+between every step. Mirror `editorialAnalysisRunner.js` structure.
+
+### 1a. Pure resolver — `resolveNextStep(series, issues, runState)` (highest-value unit)
+
+No I/O; caller passes fresh `series` + `issues[]` + accumulated `runState` (verify flags). Returns a
+discriminated step `{ kind, seasonId?, issueId?, reason }` or `{ kind:'done' }`. First unmet wins, **whole
+series**:
+
+```
+STEP 1 no arc -> !series.arc?.logline && !series.arc?.summary => generateArc
+STEP 2 season w/ 0 issues (in season order) => generateEpisodes(seasonId)
+STEP 3 arc not verified-clean this run (runState.arcVerified !== true) => verifyArc
+STEP 4 per issue, ordered by season then arcPosition/number, first where:
+ a) idea not ready => beatSheet(seasonId) (serial volume run)
+ b) prose / comicScript / teleplay not ready (per primaryManuscriptType) => textStages(issueId)
+ c) script not structurally+editorially ready => scriptVerify(issueId)
+ d) comicPages empty (cover+back+pages) => visualDraft(issueId)
+STEP 5 nothing unmet => done
+```
+
+Readiness reuses `isStageReady`. Re-run after every completed step against freshly re-read records →
+resumable, non-destructive.
+
+### 1b. Run loop (conductor)
+
+`startSeriesAutopilot(seriesId, options)` → `{ runId, alreadyRunning, mode, sseUrl }`. Inside the IIFE:
+`while (!cancel)` re-read series+issues → `resolveNextStep` → dispatch:
+
+- **generateArc:** `generateArcOverview` → `commitSeasonsWithRemap`.
+- **generateEpisodes(seasonId):** `generateSeasonEpisodes` → `commitEpisodesToIssues`.
+- **verifyArc:** bounded loop `MAX_ARC_VERIFY_ROUNDS` (default 3): `verifyArc` → if high/medium findings →
+ `resolveVerifyIssues({findings})` → re-verify. Clean → set `runState.arcVerified=true`. **Rounds
+ exhausted with residual findings → set `series.autopilot.status='paused'`, emit `paused` frame listing the
+ residual findings, stop the run.** (Per user: pause for human review on non-convergence.)
+- **beatSheet(seasonId):** delegate to `volumeBeatsRunner.startVolumeBeatsRun` and await completion via a thin
+ `await` on `isVolumeBeatsRunActive(seasonId)` poll-to-false. Serial by design — never parallelize volumes.
+- **textStages(issueId):** `startAutoRunTextStages(issueId,{force:false})`, await via `isAutoRunActive`
+ poll-to-false. **Issues processed serially** (bounds LLM/GPU spend; avoids issueId-keyed runner
+ collisions). A `concurrency` option (default 1) can lift this later.
+- **scriptVerify(issueId):** structural parse gate + `analyzeIssue`; bounded editorial-fix loop
+ `MAX_EDITORIAL_ROUNDS` (default 2): seed high-severity findings → per-comment generate+accept fix →
+ re-analyze. Unresolved high-severity after rounds → **pause for review** (consistent with arc-verify
+ choice); medium/low → warn and continue.
+- **visualDraft(issueId):** call the extract-pages service to seed pages + cover concepts, then
+ `enqueueComicCover` + `enqueueComicBackCover` + per-page `enqueueVisualComicPage` for **all pages** in
+ **draft** quality. These are async media jobs — fire kickoffs, record jobIds, broadcast, and do **not**
+ block autopilot on pixel completion (mirrors autoRunner's episodeVideo fire-and-forget, autoRunner.js:123).
+ Budget gate (below) caps how many render jobs fire before pausing.
+- **done:** broadcast `complete`; set `series.autopilot.status='done'`.
+
+### 1c. CoS gap-filling (Phase 3)
+
+Triggers: (a) a step throws the same error ≥2 consecutive times (missing tool/capability); (b) a required
+ability is absent (e.g. teleplay requested but no prompt); (c) script-verify gap when `fileGaps` opted in.
+Payload via `addTask({ description:'Autopilot: <gap> for <series title>', context:'<id, step, error,
+runId>', app:'pipeline', priority:'medium', metadata:{taskType:'pipeline-autopilot-gap', seriesId, step} },
+'user')`. Dedup via stable description prefix per (seriesId, gapKind) — `addTask` already dedups
+pending/in_progress by description+app. Gated behind `getDomainMode('cos') !== 'off'` + CoS budget.
+
+## 2. Execution & persistence — in-memory runner + derive-resume + thin marker
+
+A whole-series run is long and **will** span restarts. The pure resolver means **no persisted step cursor is
+needed** — resume is "click Run again; it picks up at the first missing step." Persist only a thin marker:
+
+- New optional field on the **series** record: `series.autopilot = { status:'idle'|'running'|'paused'|'done'
+ |'error', runId, currentStep, residualFindings?, lastError, updatedAt }`, written through the series write
+ queue, throttled to step transitions only (~250ms debounce, not per SSE frame). Survives restart, powers
+ "resume available" UI and the pause states.
+- **Boot recovery:** `recoverStuckAutopilots()` (mirror `recoverStuckAutoRuns`, autoRunner.js:201) demotes
+ any `series.autopilot.status==='running'` to `'paused'` on boot (the in-memory run is gone). Wire in
+ `server/index.js` next to the existing `recoverStuckAutoRuns()` call (~:569). The existing
+ `recoverStuckAutoRuns` also unsticks child issues left in `status:'running'`.
+
+Drive as a **dedicated pipeline runner, not a CoS job** — it composes internal service fns and needs SSE like
+its sibling runners; the CoS-job path is for scheduled shell/agent spawns. It *cooperates* with CoS (consults
+autonomy+budget, files gap tasks) without being one.
+
+## 3. Autonomy + budget gating (cos domain)
+
+- At start: `mode = getDomainMode(config,'cos')`.
+ - `off` → reject start **409** ("autonomous spend disabled").
+ - `dry-run` → resolver-only walk: emit a `plan` frame listing every step it *would* take (counts of beat
+ sheets / text runs / verifies / render jobs) with **no** side effects. This is preview/plan mode.
+ - `execute` → full run.
+- Before each *billable* step: check `getDomainBudgetStatus('cos')`; if exhausted → `status='paused'`, emit
+ `paused` ("daily CoS budget reached"), stop. After each billable step: `recordDomainUsage('cos',{actions:1})`.
+ Mirrors cosJobScheduler.js:207-238.
+- Cancel: `cancelSeriesAutopilot(seriesId)` sets the flag (checked between steps) and also calls the active
+ child cancel (`cancelVolumeBeatsRun` / `cancelAutoRun`) so cancel is responsive mid-delegation.
+
+## 4. Routes — `server/routes/pipeline/autopilot.js` (NEW, mounted in pipeline/index.js after arcRoutes)
+
+All under `/api/pipeline`. Zod via `validateRequest`; errors bubble to middleware (no try/catch in routes).
+
+```
+POST /series/:id/autopilot/start
+ body: z.object({ ...providerOverrideShape,
+ includeVisual: z.boolean().default(true), // cover+back+all pages draft (user choice)
+ target: z.enum(['auto','text','visual']).default('auto'),
+ fileGaps: z.boolean().default(false),
+ maxArcVerifyRounds: z.number().int().min(0).max(5).optional(),
+ maxEditorialRounds: z.number().int().min(0).max(5).optional() })
+ -> { runId, alreadyRunning, mode, sseUrl } (404 if series missing; 409 if mode==='off')
+GET /series/:id/autopilot/progress -> SSE (attachClient(seriesId,res); 404 if no active run)
+POST /series/:id/autopilot/cancel -> { canceled }
+GET /series/:id/autopilot/status -> { autopilot } (reads series.autopilot marker; resume/pause UI)
+```
+
+SSE frames (mirror volumeBeatsRunner's documented header): `start{runId,target,mode,plan?}`,
+`step:start{kind,seasonId?,issueId?,ordinal}`, `step:complete{kind,...}`, `step:skip{kind,reason}`,
+`verify:round{scope,round,findings}`, `gap:filed{taskId,gapKind}`, `paused{reason,residualFindings?}`,
+`canceled{runId}`, `complete{runId,summary}`, `error{runId,error}`. Add the route list to the index.js header.
+
+## 5. Client
+
+- **Launcher:** "Run Autonomously to Completion" button on `PipelineSeries.jsx` (series-scoped) — placed in
+ `ArcCanvas.jsx` alongside the existing arc-gen/verify controls, with a small popover for
+ target/includeVisual/fileGaps. Add a visible **resume / paused banner** that reads `series.autopilot` so a
+ paused run (non-convergent verify, budget, boot recovery) is obvious and re-runnable.
+- **API wrappers** in `client/src/services/apiPipeline.js`: `startAutopilot`, `cancelAutopilot`,
+ `getAutopilotStatus`, + the progress SSE URL.
+- **Progress UI:** reuse `useSseProgress` (same hook the beats/editorial runners use). Render a step timeline
+ (arc → episodes → verify → per-issue beats/prose/script/visual) with the current step highlighted; render
+ the dry-run `plan` when `mode==='dry-run'`; surface residual findings on `paused`.
+- A modal/drawer is enough for MVP → **no new page**, so no `NAV_COMMANDS`/`PALETTE_ACTIONS` churn. (If a
+ dedicated page is wanted later, add the navManifest + palette entries then.)
+
+## 6. Migrations / prompts
+
+- **MVP: no new prompt** (script-verify reuses analyzeIssue + structural parse).
+- `series.autopilot` is an optional additive field — `sanitizeSeries` gains a `sanitizeAutopilot` arm
+ (null/idle default), back-compat with existing rows (mirrors how `targetFormat`/`locked` default in
+ series.js). No data migration needed. Series stays PostgreSQL-primary per docs/STORAGE.md.
+- **Phase 3 only:** real LLM script verification → `data.reference/prompts/stages/pipeline-script-verify.md`
+ + `scripts/migrations/NNN-*.js` seeding it via setup-data.js. Out of MVP.
+
+## 7. Tests
+
+- **Highest value — `resolveNextStep` (pure):** table-driven over synthetic (series, issues): empty arc;
+ arc-but-no-issues; season-with-empty-issues; idea-only; prose-ready/script-missing;
+ script-ready/editorial-blocking; comic target with empty comicPages; fully done. No DB, no LLM.
+- **Bounded loops:** mock verify to always return one high finding → assert arc loop stops at
+ `MAX_ARC_VERIFY_ROUNDS` and **pauses** (status=paused, residual findings emitted); same for editorial loop.
+- **Autonomy gating:** off→reject (409); dry-run→plan-only (assert mocked generators **not** invoked);
+ execute→runs.
+- **Runner lifecycle (mirror editorialAnalysisRunner tests):** start returns runId; second start while active
+ → `alreadyRunning`; cancel sets flag; `recoverStuckAutopilots` demotes running→paused.
+- **DB-test pitfalls:** mock the service modules (`generateArcOverview`, `startVolumeBeatsRun`,
+ `startAutoRunTextStages`, etc.) so tests never touch PostgreSQL; resolver tests use plain objects. Use
+ `export const __testing = { runs }` for white-box assertions. (Do not run `*.db.test.js` against real
+ `portos`.)
+
+## 8. Phasing (MVP first)
+
+- **Phase 1 (MVP — backend conductor + API):** `resolveNextStep` + `seriesAutopilot.js` composing
+ generateArc / episodes / verifyArc(bounded, pause-on-non-convergence) / volume-beats / text-stages /
+ script-verify(structural+editorial). **Text-ready terminal** (no visuals yet). Autonomy+budget gating
+ (off/dry-run/execute). Routes start/progress/cancel/status. `series.autopilot` marker + boot recovery.
+ Unit tests for resolver + bounded loops + gating. Delivers "drive a whole series to story-ready."
+- **Phase 2 (client + visual draft):** ArcCanvas launcher + SSE progress + resume/paused banner + apiPipeline
+ wrappers. Add `includeVisual` path: extract-pages → draft cover+back+all-pages enqueue (fire-and-forget).
+- **Phase 3 (CoS gap-filling + real script verify):** `addTask` gap creation w/ dedup + budget gate; optional
+ `pipeline-script-verify` prompt + migration replacing the editorial-only script gate.
+
+## Verification (end-to-end)
+
+1. **Unit:** `cd server && npm test` — resolver table tests, bounded-loop pause tests, gating tests,
+ runner-lifecycle tests all green without touching Postgres.
+2. **Dry-run on the live test series:** start autopilot with cos domain in `dry-run` against
+ `ser-b74601a3-221d-4491-b037-bad51df8460a`; confirm the `plan` frame lists only the *missing* steps
+ (arc-completion, remaining first-issue stages, untouched later issues) and that **no** existing
+ ready stages appear as work — proving non-destructive resume.
+3. **Execute (text terminal, Phase 1):** flip cos to `execute`, start; watch SSE drive the series to
+ story-ready; intentionally leave an unresolvable arc finding (or set `maxArcVerifyRounds:1`) and confirm it
+ **pauses** with residual findings rather than looping.
+4. **Restart mid-run:** kill/restart the server during a run; confirm boot recovery demotes it to `paused`
+ and that clicking Run again resumes from the next missing step (no regeneration of completed stages).
+5. **Phase 2 visual:** with `includeVisual:true`, confirm cover/back/all-page draft render jobs enqueue and
+ the run completes without blocking on pixel completion; verify the budget gate pauses when the daily CoS
+ action budget is hit.
+
+## Critical files
+
+- `server/services/pipeline/seriesAutopilot.js` (NEW — conductor + `resolveNextStep`)
+- `server/routes/pipeline/autopilot.js` (NEW — routes) + mount in `server/routes/pipeline/index.js`
+- `server/services/pipeline/editorialAnalysisRunner.js` (runner pattern to mirror)
+- `server/services/pipeline/issues.js` (`isStageReady`, stage model, `queueSeriesIssuesWrite`)
+- `server/services/pipeline/arcPlanner/arcCore.js` (verify/resolve signatures)
+- `server/services/pipeline/series.js` (`sanitizeSeries` → add `sanitizeAutopilot`, `TARGET_FORMATS`)
+- `server/lib/domainAutonomy.js` / `server/services/domainUsage.js` (gating)
+- `server/index.js` (wire `recoverStuckAutopilots()` ~:569)
+- `client/src/components/pipeline/ArcCanvas.jsx`, `client/src/services/apiPipeline.js`,
+ `client/src/hooks/useSseProgress.js` (Phase 2)
diff --git a/server/index.js b/server/index.js
index efa9c5f2c6..025bc1bb6e 100644
--- a/server/index.js
+++ b/server/index.js
@@ -159,6 +159,7 @@ import { startBrainScheduler } from './services/brainScheduler.js';
import { recoverStuckClassifications } from './services/brain.js';
import { recoverStuckAnalyses } from './services/writersRoom/evaluator.js';
import { recoverStuckAutoRuns } from './services/pipeline/autoRunner.js';
+import { recoverStuckAutopilots } from './services/pipeline/seriesAutopilot.js';
import { startOrphanShellGc } from './services/importerOrphanGc.js';
import { startImageRefsGc } from './services/imageRefsGc.js';
import { initBridge as initBrainMemoryBridge } from './services/brainMemoryBridge.js';
@@ -567,6 +568,7 @@ try {
// corrupt peer cursors.
recoverStuckAnalyses().catch(err => console.error(`❌ Writers Room recovery failed: ${err.message}`));
recoverStuckAutoRuns().catch(err => console.error(`❌ Pipeline auto-run recovery failed: ${err.message}`));
+recoverStuckAutopilots().catch(err => console.error(`❌ Pipeline autopilot recovery failed: ${err.message}`));
// Initialize brain scheduler for daily digests and weekly reviews
startBrainScheduler();
// Initialize brain→memory bridge (mirrors brain data into CoS memory for semantic search)
diff --git a/server/routes/pipeline/autopilot.js b/server/routes/pipeline/autopilot.js
new file mode 100644
index 0000000000..652dde528c
--- /dev/null
+++ b/server/routes/pipeline/autopilot.js
@@ -0,0 +1,74 @@
+/**
+ * Pipeline Autopilot routes — full autonomous mode.
+ *
+ * Drives a whole series from its current state to story-ready by composing the
+ * existing pipeline passes (server/services/pipeline/seriesAutopilot.js).
+ *
+ * POST /series/:id/autopilot/start → { runId, alreadyRunning, mode, sseUrl }
+ * (404 series missing; 409 cos domain off)
+ * GET /series/:id/autopilot/progress → SSE (text/event-stream)
+ * POST /series/:id/autopilot/cancel → { canceled }
+ * GET /series/:id/autopilot/status → { autopilot } (resume / paused UI)
+ */
+
+import { Router } from 'express';
+import { z } from 'zod';
+import { asyncHandler, ServerError } from '../../lib/errorHandler.js';
+import { validateRequest } from '../../lib/validation.js';
+import * as seriesSvc from '../../services/pipeline/series.js';
+import * as autopilot from '../../services/pipeline/seriesAutopilot.js';
+import { mapServiceError, providerOverrideShape } from './shared.js';
+
+const router = Router();
+
+const autopilotStartSchema = z.object({
+ ...providerOverrideShape,
+ // Draft cover + all interior pages once a story is ready. Accepted now;
+ // honored when VISUAL_DRAFT_ENABLED ships (Phase 2). Defaults true per the
+ // product decision (whole-series, full draft visuals).
+ includeVisual: z.boolean().optional().default(true),
+ // 'auto' derives the terminal from the series targetFormat.
+ target: z.enum(['auto', 'text', 'visual']).optional().default('auto'),
+ // Create CoS tasks for capability gaps (Phase 3).
+ fileGaps: z.boolean().optional().default(false),
+ // Convergence bounds for the verify/review loops (0 = skip that gate).
+ maxArcVerifyRounds: z.number().int().min(0).max(5).optional(),
+ maxEditorialRounds: z.number().int().min(0).max(5).optional(),
+});
+
+router.post('/series/:id/autopilot/start', asyncHandler(async (req, res) => {
+ // 404 before we kick off if the series doesn't exist.
+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const body = validateRequest(autopilotStartSchema, req.body ?? {});
+ const result = await autopilot.startSeriesAutopilot(req.params.id, body)
+ .catch((err) => { throw mapServiceError(err); });
+ if (result.rejected) {
+ throw new ServerError(
+ 'Autonomous spend is disabled — set the CoS auto-run domain to dry-run or execute to run autopilot.',
+ { status: 409, code: 'PIPELINE_AUTOPILOT_DISABLED' },
+ );
+ }
+ res.json({
+ ...result,
+ sseUrl: `/api/pipeline/series/${req.params.id}/autopilot/progress`,
+ });
+}));
+
+router.get('/series/:id/autopilot/progress', (req, res) => {
+ const attached = autopilot.attachClient(req.params.id, res);
+ if (!attached) {
+ throw new ServerError('No active autopilot run for this series', { status: 404 });
+ }
+});
+
+router.post('/series/:id/autopilot/cancel', asyncHandler(async (req, res) => {
+ const canceled = autopilot.cancelSeriesAutopilot(req.params.id);
+ res.json({ canceled });
+}));
+
+router.get('/series/:id/autopilot/status', asyncHandler(async (req, res) => {
+ const series = await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ res.json({ autopilot: series.autopilot || null, active: autopilot.isAutopilotActive(req.params.id) });
+}));
+
+export default router;
diff --git a/server/routes/pipeline/index.js b/server/routes/pipeline/index.js
index abe736987b..5282906df2 100644
--- a/server/routes/pipeline/index.js
+++ b/server/routes/pipeline/index.js
@@ -20,6 +20,10 @@
* POST /issues/:id/auto-run-text → { runId, alreadyRunning, sseUrl }
* GET /issues/:id/auto-run-text/progress → SSE (text/event-stream)
* POST /issues/:id/auto-run-text/cancel → { canceled }
+ * POST /series/:id/autopilot/start → { runId, alreadyRunning, mode, sseUrl }
+ * GET /series/:id/autopilot/progress → SSE (text/event-stream)
+ * POST /series/:id/autopilot/cancel → { canceled }
+ * GET /series/:id/autopilot/status → { autopilot, active }
*
* Assembled from domain sub-routers (mirrors the cos.js pattern). Mount
* order preserves the original single-file registration order; the only
@@ -36,6 +40,7 @@ import manuscriptRoutes from './manuscript.js';
import coverRoutes from './covers.js';
import issueRoutes from './issues.js';
import editorialRoutes from './editorial.js';
+import autopilotRoutes from './autopilot.js';
const router = Router();
@@ -46,5 +51,6 @@ router.use(manuscriptRoutes);
router.use(coverRoutes);
router.use(issueRoutes);
router.use(editorialRoutes);
+router.use(autopilotRoutes);
export default router;
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index 6981759227..2f3989fbc3 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -90,6 +90,47 @@ export const ARC_LOCKABLE_FIELDS = Object.freeze([
'logline', 'summary', 'protagonistArc', 'themes', 'shape', 'readerMap',
]);
+// Series Autopilot run marker (full autonomous mode). A thin, persisted
+// breadcrumb of the in-memory orchestrator run (server/services/pipeline/
+// seriesAutopilot.js) — NOT a step cursor. Resume is derived from the
+// canonical series/issue state by the pure resolver, so all this needs to do
+// is survive a restart for the "resume available / paused" UI and the
+// boot-recovery demotion (running → paused). Persisted only when set so a
+// series that never uses autopilot keeps its on-disk + wire shape stable
+// (mirrors the `ephemeral` / `importDraft` conditional-spread convention).
+export const AUTOPILOT_STATUSES = Object.freeze(['idle', 'running', 'paused', 'done', 'error']);
+export const AUTOPILOT_STEP_MAX = 80;
+export const AUTOPILOT_ERROR_MAX = 1000;
+const AUTOPILOT_FINDING_SEVERITIES = ['high', 'medium', 'low'];
+
+export const sanitizeAutopilot = (raw) => {
+ if (!raw || typeof raw !== 'object') return null;
+ const status = AUTOPILOT_STATUSES.includes(raw.status) ? raw.status : 'idle';
+ const residualFindings = Array.isArray(raw.residualFindings)
+ ? raw.residualFindings
+ .map((f) => {
+ if (!f || typeof f !== 'object') return null;
+ const problem = trimTo(f.problem, 2000);
+ if (!problem) return null;
+ return {
+ ...(AUTOPILOT_FINDING_SEVERITIES.includes(f.severity) ? { severity: f.severity } : {}),
+ location: trimTo(f.location, 200),
+ problem,
+ };
+ })
+ .filter(Boolean)
+ .slice(0, 50)
+ : [];
+ return {
+ status,
+ runId: trimTo(raw.runId, 64) || null,
+ currentStep: trimTo(raw.currentStep, AUTOPILOT_STEP_MAX) || null,
+ residualFindings,
+ lastError: trimTo(raw.lastError, AUTOPILOT_ERROR_MAX) || null,
+ updatedAt: isStr(raw.updatedAt) ? raw.updatedAt : null,
+ };
+};
+
const sanitizeSeriesLocked = (raw = {}) => {
if (!raw || typeof raw !== 'object') return {};
const out = {};
@@ -123,6 +164,7 @@ const sanitizeSeries = (raw) => {
: { provider: null, model: null };
const createdAt = isStr(raw.createdAt) ? raw.createdAt : new Date().toISOString();
const updatedAt = isStr(raw.updatedAt) ? raw.updatedAt : createdAt;
+ const autopilot = sanitizeAutopilot(raw.autopilot);
return {
id: raw.id,
name,
@@ -178,6 +220,11 @@ const sanitizeSeries = (raw) => {
// commitImport clears it. Server-set only — never from a route body — and
// persisted only when true so every other record's shape stays stable.
...(raw.importDraft === true ? { importDraft: true } : {}),
+ // Autopilot run marker — persisted only when present so series that never
+ // run the autonomous pipeline keep their on-disk + wire shape unchanged.
+ // Older peers' sanitizeSeries simply drops the unknown field (forward/
+ // back-compatible).
+ ...(autopilot ? { autopilot } : {}),
};
};
@@ -382,6 +429,10 @@ export async function updateSeries(id, patch = {}) {
// Importer-orphan marker (issue #727) — commitImport clears it via
// `{ importDraft: false }`; sanitizer normalizes non-true back to absent.
...('importDraft' in patch ? { importDraft: patch.importDraft } : {}),
+ // Autopilot run marker — server-set by seriesAutopilot.js (and the
+ // boot-recovery demotion). Wholesale replace; sanitizer normalizes a
+ // non-object back to absent.
+ ...('autopilot' in patch ? { autopilot: patch.autopilot } : {}),
llm: mergedLlm,
updatedAt: new Date().toISOString(),
});
diff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.js
new file mode 100644
index 0000000000..670a09d00c
--- /dev/null
+++ b/server/services/pipeline/seriesAutopilot.js
@@ -0,0 +1,618 @@
+/**
+ * Pipeline — Series Autopilot (full autonomous mode)
+ *
+ * A *conductor* that drives a whole series from its current state to a terminal
+ * "story-ready" state by composing the already-shipped pipeline service
+ * functions (arc gen, episode gen, arc verify/resolve, volume beats, per-issue
+ * text stages, structural script gate, manuscript editorial review). It does NOT
+ * re-implement any generation logic — every step delegates to the same service
+ * the manual route calls.
+ *
+ * Resume is a PURE FUNCTION of current state. `resolveNextStep(series, issues,
+ * runState, options)` returns the first unmet step from the canonical records,
+ * so the orchestrator never persists a step cursor: on restart the user just
+ * starts again and it picks up at the first missing thing. Anything already
+ * `ready`/`edited` is skipped (`isStageReady`) and every generation runs with
+ * `force:false`, so an in-progress series is never clobbered.
+ *
+ * Lifecycle mirrors editorialAnalysisRunner.js: a single in-memory `runs` map
+ * keyed by `seriesId`, a `finished` flag + cleanup timer for terminal-frame
+ * replay, the one permitted try/catch boundary inside the fire-and-forget IIFE,
+ * and a cancel flag checked between every step.
+ *
+ * Autonomy: gated on the **cos** domain (server/lib/domainAutonomy.js).
+ * - off → start is rejected (route → 409).
+ * - dry-run → emit a `plan` frame of what it WOULD do; no side effects.
+ * - execute → full run, charging the cos daily action budget per step and
+ * pausing when the budget is exhausted.
+ *
+ * Two convergence guards stop unbounded LLM spend (a real observed condition —
+ * arc verify can surface fresh findings every pass): the arc-verify and
+ * editorial-review loops are bounded and, when they can't reach clean, set the
+ * run to `paused` with the residual findings for human review rather than
+ * looping forever.
+ *
+ * KNOWN GAP — "script verification": there is no dedicated comic-script verify
+ * endpoint. The scriptVerify step is a STRUCTURAL gate only (does the comic
+ * script parse into pages+panels). A real craft-level LLM script-verify prompt
+ * is a deliberate Phase-3 follow-up, not silently assumed solved.
+ *
+ * NOT YET IMPLEMENTED — draft visuals (cover + all interior pages). The render
+ * endpoints persist their job ids at the ROUTE layer (the enqueue helpers only
+ * return a jobId the caller must record), so faithful draft rendering needs that
+ * persistence replicated per slot. Gated behind VISUAL_DRAFT_ENABLED (false) so
+ * the Phase-1 terminal is "text-ready + editorial review"; flip the flag and
+ * implement `runVisualDraft` in Phase 2.
+ */
+
+import { randomUUID } from 'crypto';
+import { broadcastSse, attachSseClient, SSE_CLEANUP_DELAY_MS } from '../../lib/sseUtils.js';
+import { getDomainMode } from '../../lib/domainAutonomy.js';
+import { parseComicScript } from '../../lib/comicScriptParser.js';
+import { loadState } from '../cosState.js';
+import { getDomainBudgetStatus, recordDomainUsage } from '../domainUsage.js';
+import { getSeries, updateSeries } from './series.js';
+import { listIssues, getIssue, isStageReady } from './issues.js';
+import { compareIssuesByPosition } from './arcPlanner.js';
+import {
+ generateArcOverview,
+ commitSeasonsWithRemap,
+ generateSeasonEpisodes,
+ commitEpisodesToIssues,
+ verifyArc,
+ resolveVerifyIssues,
+ analyzeManuscriptCompleteness,
+} from './arcPlanner.js';
+import * as volumeBeatsRunner from './volumeBeatsRunner.js';
+import * as autoRunner from './autoRunner.js';
+import { seedReviewFromFindings, getReview } from './manuscriptReview.js';
+import { generateManuscriptFix, acceptManuscriptFix } from './manuscriptFix.js';
+
+// runs: Map<seriesId, { runId, clients[], lastPayload, cancelRequested, finished,
+// cleanupTimer, startedAt, mode, options, runState, activeChild }>
+const runs = new Map();
+
+// Bounded convergence loops — re-verify/re-review at most this many rounds, then
+// pause for human review with the residual findings (see module header).
+export const MAX_ARC_VERIFY_ROUNDS = 3;
+export const MAX_EDITORIAL_ROUNDS = 2;
+
+// Phase-2 flag — see module header. While false the terminal is text + editorial.
+export const VISUAL_DRAFT_ENABLED = false;
+
+// Severities that block a verify/review gate (low is informational).
+const ARC_BLOCKING = new Set(['high', 'medium']);
+const EDITORIAL_BLOCKING = new Set(['high']);
+
+// Poll cadence while awaiting a delegated child runner (volume beats / auto-run).
+const CHILD_POLL_MS = 750;
+
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+// ---------------------------------------------------------------------------
+// Pure next-step resolver — the heart of the conductor (no I/O; unit-tested).
+// ---------------------------------------------------------------------------
+
+const setHas = (s, v) => (s instanceof Set ? s.has(v) : Array.isArray(s) ? s.includes(v) : false);
+
+const byNumber = (a, b) => (a?.number ?? 9999) - (b?.number ?? 9999);
+
+// 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,
+// script authored) is already considered ready and never regenerated.
+export function requiredScriptStages(series) {
+ const fmt = series?.targetFormat || 'comic+tv';
+ if (fmt === 'comic') return ['comicScript'];
+ if (fmt === 'tv') return ['teleplay'];
+ return ['comicScript', 'teleplay'];
+}
+
+export function isComicTarget(series) {
+ return (series?.targetFormat || 'comic+tv').includes('comic');
+}
+
+function orderedIssues(issues) {
+ return [...(Array.isArray(issues) ? issues : [])].sort(compareIssuesByPosition);
+}
+
+function textReady(issue, series) {
+ return requiredScriptStages(series).every((stageId) => isStageReady(issue.stages?.[stageId]));
+}
+
+// Structural script gate (pure): does the comic script parse into >=1 page with
+// >=1 panel? Cheap, no LLM — this is the Phase-1 "verify the scripts work".
+export function scriptStructurallyReady(issue) {
+ const output = issue.stages?.comicScript?.output || '';
+ if (!output.trim()) return false;
+ const { pages } = parseComicScript(output);
+ if (!Array.isArray(pages) || pages.length === 0) return false;
+ return pages.some((p) => Array.isArray(p.panels) && p.panels.length > 0);
+}
+
+/**
+ * Return the first unmet step for a series given its canonical records and the
+ * in-run accumulator (`runState`). Pure — caller supplies fresh state.
+ *
+ * runState fields consulted (all optional): arcVerified, editorialReviewed
+ * (booleans); beatsAttempted, textAttempted, scriptChecked (Set|array of ids).
+ * The *attempted* sets stop a perpetually-failing step (an issue whose LLM run
+ * keeps erroring) from looping forever — the conductor records an attempt even
+ * on failure, so the resolver moves past it within one run.
+ */
+export function resolveNextStep(series, issues, runState = {}, options = {}) {
+ const seasons = Array.isArray(series?.seasons) ? [...series.seasons].sort(byNumber) : [];
+ const ordered = orderedIssues(issues);
+
+ // STEP 1 — arc.
+ if (!series?.arc?.logline && !series?.arc?.summary) {
+ return { kind: 'generateArc', reason: 'series has no arc' };
+ }
+
+ // STEP 2 — a season with zero issues (in season order).
+ for (const season of seasons) {
+ const inSeason = ordered.filter((i) => i.seasonId === season.id);
+ if (inSeason.length === 0) {
+ return { kind: 'generateEpisodes', seasonId: season.id, reason: `volume ${season.number ?? '?'} has no issues` };
+ }
+ }
+
+ // STEP 3 — arc verification (once per run; bounded loop happens in dispatch).
+ if (!runState.arcVerified) {
+ return { kind: 'verifyArc', reason: 'arc not yet verified this run' };
+ }
+
+ // 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);
+ if (inSeason.some((i) => !isStageReady(i.stages?.idea))) {
+ return { kind: 'beatSheet', seasonId: season.id, reason: `beats missing in volume ${season.number ?? '?'}` };
+ }
+ }
+
+ // STEP 4b — per-issue text stages (prose + required scripts).
+ for (const issue of ordered) {
+ if (setHas(runState.textAttempted, issue.id)) continue;
+ if (!textReady(issue, series)) {
+ return { kind: 'textStages', issueId: issue.id, reason: 'prose / scripts not ready' };
+ }
+ }
+
+ // STEP 4c — structural script gate (comic targets only).
+ if (isComicTarget(series)) {
+ for (const issue of ordered) {
+ if (setHas(runState.scriptChecked, issue.id)) continue;
+ return { kind: 'scriptVerify', issueId: issue.id, reason: 'comic script not yet structurally verified' };
+ }
+ }
+
+ // STEP 5 — series-level editorial review via the manuscript editor (once).
+ if (!runState.editorialReviewed) {
+ return { kind: 'editorialReview', reason: 'editorial review not yet run this run' };
+ }
+
+ // STEP 6 — draft visuals (Phase 2; gated off for now).
+ if (VISUAL_DRAFT_ENABLED && options.includeVisual && isComicTarget(series)) {
+ for (const issue of ordered) {
+ if (setHas(runState.visualDrafted, issue.id)) continue;
+ return { kind: 'visualDraft', issueId: issue.id, reason: 'comic pages not yet drafted' };
+ }
+ }
+
+ return { kind: 'done' };
+}
+
+// ---------------------------------------------------------------------------
+// Run registry helpers (mirror editorialAnalysisRunner.js).
+// ---------------------------------------------------------------------------
+
+export function isAutopilotActive(seriesId) {
+ const run = runs.get(seriesId);
+ return !!run && !run.finished;
+}
+
+export function attachClient(seriesId, res) {
+ return attachSseClient(runs, seriesId, res);
+}
+
+export function cancelSeriesAutopilot(seriesId) {
+ const run = runs.get(seriesId);
+ if (!run || run.finished) return false;
+ run.cancelRequested = true;
+ // Propagate to the currently-delegated child so cancel is responsive
+ // mid-step instead of only between steps.
+ const child = run.activeChild;
+ if (child?.kind === 'beats') volumeBeatsRunner.cancelVolumeBeatsRun(child.id);
+ else if (child?.kind === 'text') autoRunner.cancelAutoRun(child.id);
+ return true;
+}
+
+function broadcast(seriesId, payload) {
+ const run = runs.get(seriesId);
+ if (!run) return;
+ broadcastSse(run, payload);
+}
+
+function scheduleCleanup(seriesId, record) {
+ record.cleanupTimer = setTimeout(() => {
+ if (runs.get(seriesId) !== record) return;
+ for (const c of record.clients) c.end();
+ runs.delete(seriesId);
+ }, SSE_CLEANUP_DELAY_MS);
+}
+
+// Thin persisted marker for resume/paused UI + boot recovery. NOT a step
+// cursor — see module header. Best-effort; a marker write must never abort a run.
+async function persistMarker(seriesId, patch) {
+ await updateSeries(seriesId, {
+ autopilot: { ...patch, updatedAt: new Date().toISOString() },
+ }).catch((err) => {
+ console.log(`⚠️ autopilot: marker write failed for ${seriesId.slice(0, 12)}: ${err.message}`);
+ });
+}
+
+// Two override shapes because the delegated services disagree on field names:
+// the arc/episode/verify passes take { providerOverride, modelOverride }; the
+// child runners (volumeBeatsRunner, autoRunner) take { providerId, model }.
+const providerOverrideOpts = (record) => ({
+ providerOverride: record.options.providerOverride,
+ modelOverride: record.options.modelOverride,
+});
+const providerIdOpts = (record) => ({
+ providerId: record.options.providerOverride,
+ model: record.options.modelOverride,
+});
+
+// ---------------------------------------------------------------------------
+// Step dispatch.
+// ---------------------------------------------------------------------------
+
+async function waitForChild(isActive, record) {
+ while (isActive()) {
+ if (record.cancelRequested) return;
+ await sleep(CHILD_POLL_MS);
+ }
+}
+
+async function runArcVerify(seriesId, record) {
+ const maxRounds = Number.isInteger(record.options.maxArcVerifyRounds)
+ ? record.options.maxArcVerifyRounds
+ : MAX_ARC_VERIFY_ROUNDS;
+ // maxRounds === 0 means "skip verification entirely" — accept the arc as-is.
+ if (maxRounds === 0) {
+ record.runState.arcVerified = true;
+ return {};
+ }
+ for (let round = 1; round <= maxRounds; round += 1) {
+ if (record.cancelRequested) return { canceled: true };
+ const { issues } = await verifyArc(seriesId, providerOverrideOpts(record));
+ await recordDomainUsage('cos', { actions: 1 });
+ const blocking = issues.filter((i) => ARC_BLOCKING.has(i.severity));
+ broadcast(seriesId, {
+ type: 'verify:round', scope: 'arc', round, findings: issues.length, blocking: blocking.length,
+ });
+ if (blocking.length === 0) {
+ record.runState.arcVerified = true;
+ return {};
+ }
+ if (round === maxRounds) {
+ return { pause: true, reason: `arc verification did not converge after ${maxRounds} rounds`, residual: blocking };
+ }
+ if (record.cancelRequested) return { canceled: true };
+ await resolveVerifyIssues(seriesId, { findings: blocking, ...providerOverrideOpts(record) });
+ await recordDomainUsage('cos', { actions: 1 });
+ }
+ return {};
+}
+
+// Delegate to a child SSE runner and block until it finishes: mark the work as
+// attempted (so a perpetually-failing child can't loop the resolver), start it,
+// expose it as activeChild for responsive cancel, poll to completion, then bill
+// one action. Shared by the beats and text steps.
+async function runChildToCompletion(record, { attemptedSet, kind, id, start, isActive }) {
+ attemptedSet.add(id);
+ await start();
+ record.activeChild = { kind, id };
+ await waitForChild(() => isActive(id), record);
+ record.activeChild = null;
+ await recordDomainUsage('cos', { actions: 1 });
+ return {};
+}
+
+const runBeats = (seriesId, seasonId, record) => runChildToCompletion(record, {
+ attemptedSet: record.runState.beatsAttempted,
+ kind: 'beats',
+ id: seasonId,
+ start: () => volumeBeatsRunner.startVolumeBeatsRun(seriesId, seasonId, { mode: 'skip-existing', ...providerIdOpts(record) }),
+ isActive: volumeBeatsRunner.isVolumeBeatsRunActive,
+});
+
+const runText = (issueId, record) => runChildToCompletion(record, {
+ attemptedSet: record.runState.textAttempted,
+ kind: 'text',
+ id: issueId,
+ start: () => autoRunner.startAutoRunTextStages(issueId, { force: false }),
+ isActive: autoRunner.isAutoRunActive,
+});
+
+async function runScriptVerify(sId, issueId, record) {
+ record.runState.scriptChecked.add(issueId);
+ const issue = await getIssue(issueId);
+ if (!scriptStructurallyReady(issue)) {
+ // Structural gap — surface it but don't block the run (Phase 3 will file a
+ // CoS task / run a craft-level LLM verify). Not billable.
+ broadcast(sId, {
+ type: 'step:skip',
+ kind: 'scriptVerify',
+ issueId,
+ reason: 'comic script did not parse into pages/panels — flagged for review',
+ });
+ }
+ return {};
+}
+
+async function runEditorial(sId, record) {
+ const maxRounds = Number.isInteger(record.options.maxEditorialRounds)
+ ? record.options.maxEditorialRounds
+ : MAX_EDITORIAL_ROUNDS;
+ // maxRounds === 0 means "skip the editorial gate entirely".
+ if (maxRounds === 0) {
+ record.runState.editorialReviewed = true;
+ return {};
+ }
+ for (let round = 1; round <= maxRounds; round += 1) {
+ if (record.cancelRequested) return { canceled: true };
+ const { issues, runId } = await analyzeManuscriptCompleteness(sId, {
+ withEdits: true,
+ ...providerOverrideOpts(record),
+ });
+ await recordDomainUsage('cos', { actions: 1 });
+ const blocking = (issues || []).filter((i) => EDITORIAL_BLOCKING.has(i.severity));
+ broadcast(sId, {
+ type: 'verify:round', scope: 'editorial', round, findings: (issues || []).length, blocking: blocking.length,
+ });
+ // Seed the manuscript-review comment set so the findings are visible in the
+ // manuscript editor regardless of auto-fix outcome.
+ await seedReviewFromFindings(sId, issues || [], { runId, mode: 'fresh' }).catch((err) => {
+ console.log(`⚠️ autopilot: seed editorial review failed for ${sId.slice(0, 12)}: ${err.message}`);
+ });
+ if (blocking.length === 0) {
+ record.runState.editorialReviewed = true;
+ return {};
+ }
+ if (round === maxRounds) {
+ return { pause: true, reason: `editorial review did not converge after ${maxRounds} round(s)`, residual: blocking };
+ }
+ // Bounded auto-fix: apply a fix for each open high-severity comment, then
+ // the loop re-analyzes. Each fix is wrapped so one bad anchor doesn't abort
+ // the pass (boundary use of try/catch — these call into LLM/file paths).
+ const review = await getReview(sId).catch(() => ({ comments: [] }));
+ const open = (review.comments || []).filter((c) => c.status === 'open' && EDITORIAL_BLOCKING.has(c.severity));
+ for (const comment of open) {
+ if (record.cancelRequested) return { canceled: true };
+ try {
+ if (!comment.fix) await generateManuscriptFix(sId, { commentId: comment.id });
+ await acceptManuscriptFix(sId, { commentId: comment.id });
+ } catch (err) {
+ console.log(`⚠️ autopilot: editorial fix ${comment.id} failed: ${(err?.message || err)}`);
+ }
+ }
+ await recordDomainUsage('cos', { actions: 1 });
+ }
+ return {};
+}
+
+async function dispatchStep(sId, step, record) {
+ switch (step.kind) {
+ case 'generateArc': {
+ const r = await generateArcOverview(sId, providerOverrideOpts(record));
+ const cur = await getSeries(sId);
+ await commitSeasonsWithRemap(cur, { arc: r.arc, seasons: r.seasons });
+ await recordDomainUsage('cos', { actions: 1 });
+ return {};
+ }
+ case 'generateEpisodes': {
+ const r = await generateSeasonEpisodes(sId, step.seasonId, providerOverrideOpts(record));
+ const cur = await getSeries(sId);
+ await commitEpisodesToIssues(sId, step.seasonId, r.episodes, { preloadedSeries: cur });
+ await recordDomainUsage('cos', { actions: 1 });
+ return {};
+ }
+ case 'verifyArc':
+ return runArcVerify(sId, record);
+ case 'beatSheet':
+ return runBeats(sId, step.seasonId, record);
+ case 'textStages':
+ return runText(step.issueId, record);
+ case 'scriptVerify':
+ return runScriptVerify(sId, step.issueId, record);
+ case 'editorialReview':
+ return runEditorial(sId, record);
+ default:
+ return {};
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Dry-run planning — enumerate what execute WOULD do, no side effects.
+// ---------------------------------------------------------------------------
+
+// Mirrors resolveNextStep's step ordering, but enumerates the FULL remaining
+// plan (counts of every unmet step) rather than returning only the next one —
+// so it can't reuse the single-step resolver. Kept deliberately in sync by
+// hand; they share the same predicates (textReady, isComicTarget, isStageReady).
+function buildDryRunPlan(series, issues, options) {
+ const plan = [];
+ const ordered = orderedIssues(issues);
+ const seasons = Array.isArray(series?.seasons) ? [...series.seasons].sort(byNumber) : [];
+ if (!series?.arc?.logline && !series?.arc?.summary) plan.push({ kind: 'generateArc', count: 1 });
+ const emptySeasons = seasons.filter((s) => !ordered.some((i) => i.seasonId === s.id));
+ if (emptySeasons.length) plan.push({ kind: 'generateEpisodes', count: emptySeasons.length });
+ plan.push({ kind: 'verifyArc', count: 1, note: `up to ${MAX_ARC_VERIFY_ROUNDS} rounds` });
+ const beatsNeeded = seasons.filter((s) =>
+ ordered.some((i) => i.seasonId === s.id && !isStageReady(i.stages?.idea))).length;
+ if (beatsNeeded) plan.push({ kind: 'beatSheet', count: beatsNeeded });
+ const textNeeded = ordered.filter((i) => !textReady(i, series)).length;
+ if (textNeeded) plan.push({ kind: 'textStages', count: textNeeded });
+ if (isComicTarget(series)) plan.push({ kind: 'scriptVerify', count: ordered.length });
+ plan.push({ kind: 'editorialReview', count: 1, note: `up to ${MAX_EDITORIAL_ROUNDS} rounds` });
+ if (VISUAL_DRAFT_ENABLED && options.includeVisual && isComicTarget(series)) {
+ plan.push({ kind: 'visualDraft', count: ordered.length });
+ }
+ return plan;
+}
+
+// ---------------------------------------------------------------------------
+// Public entrypoint.
+// ---------------------------------------------------------------------------
+
+/**
+ * Start (or no-op resume of) the autopilot for a series. Returns immediately;
+ * progress lands via SSE. When the cos domain is `off`, returns
+ * `{ rejected:true, mode:'off' }` WITHOUT starting (route maps to 409).
+ */
+export async function startSeriesAutopilot(sId, options = {}) {
+ const existing = runs.get(sId);
+ if (existing && !existing.finished) {
+ return { runId: existing.runId, alreadyRunning: true, mode: existing.mode };
+ }
+
+ const state = await loadState().catch(() => ({ config: {} }));
+ const mode = getDomainMode(state.config, 'cos');
+ if (mode === 'off') {
+ return { rejected: true, mode: 'off' };
+ }
+
+ if (existing) {
+ // A finished run still in its replay window — evict it so this fresh run
+ // fully replaces it (mirrors editorialAnalysisRunner).
+ if (existing.cleanupTimer) clearTimeout(existing.cleanupTimer);
+ for (const c of existing.clients) c.end();
+ }
+
+ const runId = randomUUID();
+ const record = {
+ runId,
+ clients: [],
+ lastPayload: null,
+ cancelRequested: false,
+ finished: false,
+ cleanupTimer: null,
+ startedAt: new Date().toISOString(),
+ mode,
+ options,
+ runState: {
+ arcVerified: false,
+ editorialReviewed: false,
+ beatsAttempted: new Set(),
+ textAttempted: new Set(),
+ scriptChecked: new Set(),
+ visualDrafted: new Set(),
+ },
+ activeChild: null,
+ };
+ runs.set(sId, record);
+
+ // Fire-and-forget coordinator. The try/catch is the permitted boundary use —
+ // an unhandled LLM rejection here would crash the process on Node ≥15.
+ (async () => {
+ try {
+ // DRY-RUN: enumerate the plan, no side effects.
+ if (mode === 'dry-run') {
+ const series = await getSeries(sId);
+ const issues = await listIssues({ seriesId: sId });
+ const plan = buildDryRunPlan(series, issues, options);
+ broadcast(sId, { type: 'start', runId, mode, target: series.targetFormat, plan });
+ broadcast(sId, { type: 'complete', runId, dryRun: true, steps: plan.length, completedAt: new Date().toISOString() });
+ console.log(`🧭 autopilot dry-run — series=${sId.slice(0, 12)} steps=${plan.length}`);
+ return;
+ }
+
+ // EXECUTE.
+ const series0 = await getSeries(sId);
+ broadcast(sId, { type: 'start', runId, mode, target: series0.targetFormat });
+ await persistMarker(sId, { status: 'running', runId, currentStep: null, residualFindings: [], lastError: null });
+ if (options.includeVisual && !VISUAL_DRAFT_ENABLED) {
+ broadcast(sId, { type: 'note', message: 'Draft visual rendering is not enabled in this build — running to text-ready + editorial review.' });
+ }
+
+ let ordinal = 0;
+ while (!record.cancelRequested) {
+ const series = await getSeries(sId);
+ const issues = await listIssues({ seriesId: sId });
+ const step = resolveNextStep(series, issues, record.runState, options);
+
+ if (step.kind === 'done') {
+ await persistMarker(sId, { status: 'done', runId, currentStep: null });
+ broadcast(sId, { type: 'complete', runId, steps: ordinal, completedAt: new Date().toISOString() });
+ console.log(`✅ autopilot complete — series=${sId.slice(0, 12)} steps=${ordinal}`);
+ return;
+ }
+
+ // Budget gate (mirrors cosJobScheduler) — pause when today's cos action
+ // budget is exhausted rather than burning past it.
+ const budget = await getDomainBudgetStatus('cos');
+ if (!budget.withinBudget) {
+ await persistMarker(sId, { status: 'paused', runId, currentStep: step.kind, lastError: `daily cos ${budget.exceeded} budget reached` });
+ broadcast(sId, { type: 'paused', runId, reason: `daily cos ${budget.exceeded} budget reached`, completedAt: new Date().toISOString() });
+ console.log(`⏸️ autopilot paused (budget) — series=${sId.slice(0, 12)} after ${ordinal} steps`);
+ return;
+ }
+
+ ordinal += 1;
+ await persistMarker(sId, { status: 'running', runId, currentStep: step.kind });
+ broadcast(sId, { type: 'step:start', kind: step.kind, seasonId: step.seasonId, issueId: step.issueId, ordinal, reason: step.reason });
+
+ const result = await dispatchStep(sId, step, record);
+
+ if (result?.canceled || record.cancelRequested) break;
+ if (result?.pause) {
+ await persistMarker(sId, { status: 'paused', runId, currentStep: step.kind, residualFindings: result.residual || [], lastError: result.reason });
+ broadcast(sId, { type: 'paused', runId, scope: step.kind, reason: result.reason, residualFindings: result.residual || [], completedAt: new Date().toISOString() });
+ console.log(`⏸️ autopilot paused (${step.kind}) — series=${sId.slice(0, 12)}: ${result.reason}`);
+ return;
+ }
+ broadcast(sId, { type: 'step:complete', kind: step.kind, seasonId: step.seasonId, issueId: step.issueId, ordinal });
+ }
+
+ // Cancelled.
+ await persistMarker(sId, { status: 'paused', runId, currentStep: null, lastError: 'canceled by user' });
+ broadcast(sId, { type: 'canceled', runId, steps: ordinal, completedAt: new Date().toISOString() });
+ console.log(`🛑 autopilot canceled — series=${sId.slice(0, 12)} after ${ordinal} steps`);
+ } catch (err) {
+ const message = (err?.message || String(err)).slice(0, 1000);
+ console.error(`❌ autopilot failed — series=${sId.slice(0, 12)} ${message}`);
+ await persistMarker(sId, { status: 'error', runId, lastError: message });
+ broadcast(sId, { type: 'error', runId, error: message, failedAt: new Date().toISOString() });
+ } finally {
+ record.finished = true;
+ scheduleCleanup(sId, record);
+ }
+ })();
+
+ return { runId, alreadyRunning: false, mode };
+}
+
+/**
+ * Boot-time recovery: the in-memory run map is lost on restart, so any series
+ * whose persisted marker still says `running` is demoted to `paused` (the user
+ * can click Run to resume from the next missing step). Mirrors
+ * recoverStuckAutoRuns in autoRunner.js. Best-effort; never blocks boot.
+ */
+export async function recoverStuckAutopilots() {
+ const { listSeries } = await import('./series.js');
+ const all = await listSeries().catch(() => []);
+ const stuck = all.filter((s) => s.autopilot?.status === 'running');
+ if (stuck.length === 0) return 0;
+ for (const s of stuck) {
+ await updateSeries(s.id, {
+ autopilot: { ...s.autopilot, status: 'paused', lastError: 'interrupted by server restart', updatedAt: new Date().toISOString() },
+ }).catch(() => null);
+ }
+ console.log(`📝 autopilot: recovered ${stuck.length} stuck run${stuck.length === 1 ? '' : 's'} on boot`);
+ return stuck.length;
+}
+
+// Export internals for tests.
+export const __testing = { runs, buildDryRunPlan };
diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
new file mode 100644
index 0000000000..8daa63f7f5
--- /dev/null
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -0,0 +1,303 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { mockNoPeerSync, mockNoPeers } from '../../lib/mockPathsDataRoot.js';
+
+// ---- File-backed store (like autoRunner.test.js) so the REAL series/issues
+// services run against an in-memory map instead of Postgres. ------------------
+const fileStore = new Map();
+vi.mock('../../lib/fileUtils.js', () => ({
+ tryReadFile: vi.fn().mockResolvedValue(null),
+ PATHS: { data: '/mock/data', cos: '/mock/data/cos' },
+ ensureDir: vi.fn().mockResolvedValue(undefined),
+ atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
+ readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),
+}));
+
+let uuidCounter = 0;
+vi.mock('crypto', async () => {
+ const actual = await vi.importActual('crypto');
+ return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };
+});
+
+vi.mock('../instances.js', () => mockNoPeers());
+vi.mock('../sharing/peerSync.js', () => mockNoPeerSync());
+
+// ---- Controllable test doubles for the autonomy + LLM-calling deps. ----------
+let cosMode = 'execute';
+vi.mock('../cosState.js', () => ({
+ loadState: vi.fn(async () => ({ config: { domainAutonomy: { cos: cosMode } } })),
+}));
+
+let budgetStatus = { withinBudget: true, exceeded: null };
+const recordDomainUsage = vi.fn(async () => {});
+vi.mock('../domainUsage.js', () => ({
+ getDomainBudgetStatus: vi.fn(async () => budgetStatus),
+ recordDomainUsage,
+}));
+
+// arcPlanner: keep the REAL barrel (for compareIssuesByPosition) and override
+// only the LLM-calling passes with spies whose return values the tests drive.
+let verifyFindings = [];
+let editorialFindings = [];
+const arcSpies = {
+ generateArcOverview: vi.fn(async () => ({ arc: { logline: 'A', summary: 'S' }, seasons: [] })),
+ commitSeasonsWithRemap: vi.fn(async (series) => ({ series })),
+ generateSeasonEpisodes: vi.fn(async () => ({ episodes: [] })),
+ commitEpisodesToIssues: vi.fn(async () => []),
+ verifyArc: vi.fn(async () => ({ issues: verifyFindings })),
+ resolveVerifyIssues: vi.fn(async () => ({ applied: true })),
+ analyzeManuscriptCompleteness: vi.fn(async () => ({ issues: editorialFindings, runId: 'run-comp' })),
+};
+vi.mock('./arcPlanner.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, ...arcSpies };
+});
+
+const volumeBeatsSpies = {
+ startVolumeBeatsRun: vi.fn(async () => ({ runId: 'vb', alreadyRunning: false })),
+ isVolumeBeatsRunActive: vi.fn(() => false),
+ cancelVolumeBeatsRun: vi.fn(() => true),
+};
+vi.mock('./volumeBeatsRunner.js', () => volumeBeatsSpies);
+
+const autoRunnerSpies = {
+ startAutoRunTextStages: vi.fn(async () => ({ runId: 'ar', alreadyRunning: false })),
+ isAutoRunActive: vi.fn(() => false),
+ cancelAutoRun: vi.fn(() => true),
+};
+vi.mock('./autoRunner.js', () => autoRunnerSpies);
+
+vi.mock('./manuscriptReview.js', () => ({
+ seedReviewFromFindings: vi.fn(async () => ({ comments: [] })),
+ getReview: vi.fn(async () => ({ comments: [] })),
+}));
+vi.mock('./manuscriptFix.js', () => ({
+ generateManuscriptFix: vi.fn(async () => ({})),
+ acceptManuscriptFix: vi.fn(async () => ({})),
+}));
+
+// Real services + the unit under test (imported AFTER the mocks above).
+const seriesSvc = await import('./series.js');
+const seasonsSvc = await import('./seasons.js');
+const issuesSvc = await import('./issues.js');
+const autopilot = await import('./seriesAutopilot.js');
+const { resolveNextStep, requiredScriptStages, scriptStructurallyReady } = autopilot;
+
+// A comic script string that parseComicScript turns into >=1 page/panel.
+const VALID_SCRIPT = 'PAGE 1\nPANEL 1\nA scene.';
+
+const ready = (output = 'x') => ({ status: 'ready', output });
+const empty = () => ({ status: 'empty', output: '' });
+
+const waitFor = async (predicate, { timeoutMs = 2000, intervalMs = 5 } = {}) => {
+ const start = Date.now();
+ while (Date.now() - start < timeoutMs) {
+ if (predicate()) return;
+ await new Promise((r) => setTimeout(r, intervalMs));
+ }
+ throw new Error('waitFor: predicate never became true');
+};
+const runFinished = (sId) => () => autopilot.__testing.runs.get(sId)?.finished === true;
+
+beforeEach(() => {
+ fileStore.clear();
+ uuidCounter = 0;
+ cosMode = 'execute';
+ budgetStatus = { withinBudget: true, exceeded: null };
+ verifyFindings = [];
+ editorialFindings = [];
+ autopilot.__testing.runs.clear();
+ vi.clearAllMocks();
+});
+
+// ---------------------------------------------------------------------------
+// Pure resolver — the highest-value unit (no I/O, table-driven).
+// ---------------------------------------------------------------------------
+describe('resolveNextStep (pure)', () => {
+ const comic = { targetFormat: 'comic', arc: { logline: 'L', summary: 'S' }, seasons: [{ id: 'se1', number: 1 }] };
+ const issue = (over = {}) => ({ id: 'iss1', seasonId: 'se1', number: 1, arcPosition: 1, stages: {}, ...over });
+
+ it('asks for arc generation when there is no arc', () => {
+ expect(resolveNextStep({ targetFormat: 'comic', seasons: [] }, []).kind).toBe('generateArc');
+ });
+
+ it('treats a present arc summary (no logline) as having an arc', () => {
+ const step = resolveNextStep({ targetFormat: 'comic', arc: { summary: 'S' }, seasons: [] }, []);
+ expect(step.kind).not.toBe('generateArc');
+ });
+
+ it('asks to generate episodes for a season with no issues', () => {
+ const step = resolveNextStep(comic, []);
+ expect(step).toMatchObject({ kind: 'generateEpisodes', seasonId: 'se1' });
+ });
+
+ it('verifies the arc before drafting issues', () => {
+ const step = resolveNextStep(comic, [issue()]);
+ expect(step.kind).toBe('verifyArc');
+ });
+
+ it('asks for beat sheets when an issue has no idea (post-verify)', () => {
+ const step = resolveNextStep(comic, [issue()], { arcVerified: true });
+ expect(step).toMatchObject({ kind: 'beatSheet', seasonId: 'se1' });
+ });
+
+ it('skips a season already attempted for beats (no infinite loop)', () => {
+ const step = resolveNextStep(comic, [issue()], { arcVerified: true, beatsAttempted: new Set(['se1']) });
+ // beats skipped → falls through to text stages
+ expect(step).toMatchObject({ kind: 'textStages', issueId: 'iss1' });
+ });
+
+ it('asks for text stages once beats exist but scripts do not', () => {
+ const step = resolveNextStep(comic, [issue({ stages: { idea: ready() } })], { arcVerified: true });
+ expect(step).toMatchObject({ kind: 'textStages', 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 },
+ );
+ expect(step).toMatchObject({ kind: 'scriptVerify', issueId: 'iss1' });
+ });
+
+ it('asks for editorial review once all issues are script-checked', () => {
+ const step = resolveNextStep(
+ comic,
+ [issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
+ { arcVerified: true, scriptChecked: new Set(['iss1']) },
+ );
+ expect(step.kind).toBe('editorialReview');
+ });
+
+ it('is done once editorial review has run', () => {
+ const step = resolveNextStep(
+ comic,
+ [issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
+ { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true },
+ );
+ expect(step.kind).toBe('done');
+ });
+
+ it('does not run script verify for a tv-only target', () => {
+ const tv = { targetFormat: 'tv', arc: { logline: 'L' }, seasons: [{ id: 'se1', number: 1 }] };
+ const step = resolveNextStep(
+ tv,
+ [issue({ stages: { idea: ready(), teleplay: ready() } })],
+ { arcVerified: true },
+ );
+ expect(step.kind).toBe('editorialReview');
+ });
+});
+
+describe('requiredScriptStages / scriptStructurallyReady', () => {
+ it('maps targetFormat to required scripts', () => {
+ expect(requiredScriptStages({ targetFormat: 'comic' })).toEqual(['comicScript']);
+ expect(requiredScriptStages({ targetFormat: 'tv' })).toEqual(['teleplay']);
+ expect(requiredScriptStages({ targetFormat: 'comic+tv' })).toEqual(['comicScript', 'teleplay']);
+ expect(requiredScriptStages({})).toEqual(['comicScript', 'teleplay']);
+ });
+
+ it('passes a parseable comic script and fails an unparseable one', () => {
+ expect(scriptStructurallyReady({ stages: { comicScript: ready(VALID_SCRIPT) } })).toBe(true);
+ expect(scriptStructurallyReady({ stages: { comicScript: ready('just some prose, no pages') } })).toBe(false);
+ expect(scriptStructurallyReady({ stages: {} })).toBe(false);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Conductor lifecycle + gating (uses real series/issues against file store).
+// ---------------------------------------------------------------------------
+async function seedComplete() {
+ const series = await seriesSvc.createSeries({ name: 'S', logline: 'L', premise: 'P', targetFormat: 'comic' });
+ await seriesSvc.updateSeries(series.id, { arc: { logline: 'A', summary: 'S' } });
+ const season = await seasonsSvc.createSeason(series.id, { number: 1, title: 'V1' });
+ const seasonId = season.id;
+ const issue = await issuesSvc.createIssue({ seriesId: series.id, seasonId, title: 'I1', number: 1 });
+ await issuesSvc.updateStage(issue.id, 'idea', ready('beats'));
+ await issuesSvc.updateStage(issue.id, 'comicScript', ready(VALID_SCRIPT));
+ return { seriesId: series.id, seasonId, issueId: issue.id };
+}
+
+describe('autopilot conductor', () => {
+ it('rejects start when the cos domain is off (no run created)', async () => {
+ cosMode = 'off';
+ const { seriesId } = await seedComplete();
+ const res = await autopilot.startSeriesAutopilot(seriesId, {});
+ expect(res).toMatchObject({ rejected: true, mode: 'off' });
+ expect(autopilot.__testing.runs.has(seriesId)).toBe(false);
+ });
+
+ it('dry-run emits a plan without calling any generator', async () => {
+ cosMode = 'dry-run';
+ const { seriesId } = await seedComplete();
+ const { runId } = await autopilot.startSeriesAutopilot(seriesId, {});
+ expect(runId).toBeTruthy();
+ await waitFor(runFinished(seriesId));
+ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
+ expect(last?.type).toBe('complete');
+ expect(last?.dryRun).toBe(true);
+ expect(arcSpies.generateArcOverview).not.toHaveBeenCalled();
+ expect(arcSpies.verifyArc).not.toHaveBeenCalled();
+ });
+
+ it('drives a ready series to done in execute mode', async () => {
+ const { seriesId } = await seedComplete();
+ await autopilot.startSeriesAutopilot(seriesId, {});
+ await waitFor(runFinished(seriesId));
+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('complete');
+ expect(arcSpies.verifyArc).toHaveBeenCalled();
+ expect(arcSpies.analyzeManuscriptCompleteness).toHaveBeenCalled();
+ const series = await seriesSvc.getSeries(seriesId);
+ expect(series.autopilot?.status).toBe('done');
+ });
+
+ it('pauses for review when arc verify never converges', async () => {
+ verifyFindings = [{ severity: 'high', problem: 'plot hole', location: 'V1' }];
+ const { seriesId } = await seedComplete();
+ await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 2 });
+ await waitFor(runFinished(seriesId));
+ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
+ expect(last?.type).toBe('paused');
+ expect(last?.scope).toBe('verifyArc');
+ // bounded: verifyArc called exactly maxRounds times, resolve called rounds-1.
+ expect(arcSpies.verifyArc).toHaveBeenCalledTimes(2);
+ expect(arcSpies.resolveVerifyIssues).toHaveBeenCalledTimes(1);
+ const series = await seriesSvc.getSeries(seriesId);
+ expect(series.autopilot?.status).toBe('paused');
+ expect(series.autopilot?.residualFindings?.[0]?.problem).toBe('plot hole');
+ });
+
+ it('pauses when the cos daily budget is exhausted', async () => {
+ budgetStatus = { withinBudget: false, exceeded: 'actions' };
+ const { seriesId } = await seedComplete();
+ await autopilot.startSeriesAutopilot(seriesId, {});
+ await waitFor(runFinished(seriesId));
+ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
+ expect(last?.type).toBe('paused');
+ expect(last?.reason).toMatch(/budget/);
+ expect(arcSpies.verifyArc).not.toHaveBeenCalled();
+ });
+
+ it('a second start while active resolves to alreadyRunning', async () => {
+ // Hold the run open by making the verify loop wait on a never-converging
+ // finding plus a slow child so the first run is still active.
+ verifyFindings = [{ severity: 'high', problem: 'x' }];
+ arcSpies.resolveVerifyIssues.mockImplementationOnce(() => new Promise(() => {})); // never resolves
+ const { seriesId } = await seedComplete();
+ const first = await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 5 });
+ expect(first.alreadyRunning).toBe(false);
+ const second = await autopilot.startSeriesAutopilot(seriesId, {});
+ expect(second.alreadyRunning).toBe(true);
+ expect(second.runId).toBe(first.runId);
+ autopilot.cancelSeriesAutopilot(seriesId);
+ });
+
+ it('recoverStuckAutopilots demotes a running marker to paused', async () => {
+ const series = await seriesSvc.createSeries({ name: 'S', logline: 'L', premise: 'P' });
+ await seriesSvc.updateSeries(series.id, { autopilot: { status: 'running', runId: 'dead' } });
+ const n = await autopilot.recoverStuckAutopilots();
+ expect(n).toBe(1);
+ const fresh = await seriesSvc.getSeries(series.id);
+ expect(fresh.autopilot?.status).toBe('paused');
+ });
+});