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 craft-level LLM comic-script verify to Series Autopilot

[._.]/ Adam Eivy947648598355
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 8d86583be6..5ad2c7e3f8 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,7 +2,7 @@
## Added
-- **Series Autopilot — drive a whole series end-to-end autonomously.** 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 → **draft cover + back cover + all interior comic pages** — 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`/rendered 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 — every draft render is one budget-gated action, since a comic is many GPU jobs). 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. Draft renders are fire-and-forget proof-quality jobs whose in-flight job ids are persisted onto each cover/page slot (so a resumed run never re-renders an already-queued slot). Boot recovery demotes a marker stuck at `running` to `paused`. With opt-in `fileGaps`, capability/quality gaps the run can't resolve on its own — an unparseable script, a failing render, a stalled verify/editorial gate, a run-ending error — are filed as **deduped CoS tasks** (scoped to the pipeline app) so they're tracked rather than silently swallowed. Remaining follow-up: a dedicated craft-level LLM comic-script verify (today's per-issue script gate is a structural parse only; deeper craft is already caught by the series-level editorial pass) — see PLAN.md. (`server/services/pipeline/seriesAutopilot.js`, `server/routes/pipeline/autopilot.js`, `server/routes/pipeline/index.js`, `server/services/pipeline/series.js`, `server/index.js`)
+- **Series Autopilot — drive a whole series end-to-end autonomously.** 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 → **draft cover + back cover + all interior comic pages** — 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`/rendered 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 — every draft render is one budget-gated action, since a comic is many GPU jobs). 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. Draft renders are fire-and-forget proof-quality jobs whose in-flight job ids are persisted onto each cover/page slot (so a resumed run never re-renders an already-queued slot). Boot recovery demotes a marker stuck at `running` to `paused`. With opt-in `fileGaps`, capability/quality gaps the run can't resolve on its own — an unparseable script, a failing render, a stalled verify/editorial gate, a run-ending error — are filed as **deduped CoS tasks** (scoped to the pipeline app) so they're tracked rather than silently swallowed. The per-issue script gate runs two checks: a structural parse gate (does the script become pages/panels) and a craft-level LLM verify (`pipeline-script-verify` — un-renderable panels, panel-to-panel flow, dialogue/art balance, within-issue continuity, page-turn placement); the craft gate is advisory (surfaces + files blocking findings without hard-pausing, since the gating quality pass is the series-level editorial review). (`server/services/pipeline/seriesAutopilot.js`, `server/services/pipeline/scriptVerify.js`, `data.reference/prompts/stages/pipeline-script-verify.md`, `scripts/migrations/090-script-verify-stage.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`)
diff --git a/PLAN.md b/PLAN.md
index ee89f5fc1c..cd8dbc85d2 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -20,8 +20,6 @@ independently.
<!-- reference-watch proposals: slug-tagged, picked up by /claim later -->
-- [ ] [autopilot-llm-script-verify] **Add a dedicated craft-level LLM comic-script verify pass to Series Autopilot's `scriptVerify` step.** Surfaced 2026-06-16 building Series Autopilot (`server/services/pipeline/seriesAutopilot.js` `runScriptVerify`). Today the per-issue script gate is a *structural* parse only (`scriptStructurallyReady` → does the comic script parse into ≥1 page/≥1 panel via `parseComicScript`); deeper craft issues are caught indirectly by the series-level editorial completeness pass. A dedicated pass would verify the script reads as a working comic *script* (panel-to-panel flow, page turns/beats, dialogue/art balance, clarity of action) in isolation, per issue, before pages are extracted. Needs: a new `data.reference/prompts/stages/pipeline-script-verify.md` stage prompt + `stage-config.json` entry + a `scripts/migrations/NNN-*.js` that seeds it (mind the prompt-migration drift cross-sync discipline — resync NEW/ACCEPTED_OLD hashes in earlier migrations that track the file), a `verifyComicScript(issueId, opts)` service returning `{issues:[{severity,location,problem,suggestion}]}`, and wiring into `runScriptVerify` (high-severity → seed into manuscriptReview + pause for human review, consistent with the arc/editorial gates). Deferred from the autopilot PR because the editorial completeness pass already covers comic-script craft and a new stage prompt carries real cross-install migration maintenance for marginal added value. Estimated scope: medium.
-
- [ ] [brain-memory-delete-hard-prune-vector] **Hard-delete the mapped pgvector row when a brain memory is deleted by the user (vs a peer-sync tombstone), instead of soft-archiving it forever.** Surfaced 2026-06-14 while wiring ChatGPT-import embeddings. Deleting a brain memory emits `{type}:deleted` → the bridge's `archiveMappedMemory` does `UPDATE memories SET status='archived'` (`brainMemoryBridge.js:373`). That correctly hides it from search (search filters `status='active'`), but the row + its 768-dim embedding **stay in Postgres forever** — nothing ever hard-prunes bridge-archived rows (`memoryDB.deleteMemory(id, hard=true)` exists but the bridge never calls it). For a 1482-record ChatGPT import that's later cleared, that's ~1482 dead vectors lingering. Fix: distinguish a **real local delete** (user action via `remove()` → genuine tombstone) from a **sync-driven archive** (peer delete, recoverable — must stay soft so resurrection works, see the reactivation path at `brainMemoryBridge.js:~193`). On a real local delete, hard-`DELETE` the mapped memory row + drop its bridge-map entry; keep soft-archive for the sync path. The signal is available: `handleEntityDeleted`/`resyncBrainRecord` know whether they're handling a local `:deleted` event vs a `sync:applied` resync. Add a test asserting a local delete removes the row (not just archives) while a synced delete still soft-archives. Note: the `*.db.test.js` real-Postgres guard applies. Estimated scope: small-medium.
- [ ] [media-jobs-survive-pm2-server-restart] **Isolate long media-job subprocesses (LoRA training, video gen) from pm2's restart SIGINT via spawn-side double-fork.** Surfaced 2026-06-14: a 9B LoRA training run died repeatedly with `SIGINT`/`KeyboardInterrupt` at the exact second of a `pm2 restart portos-server`. Root cause: pm2's `TreeKill.js` does `ps -e -o pid=,ppid=` and walks the **parent→child tree**, SIGINT-ing every descendant on restart/stop — and portos-server restarts routinely (was a hardcoded `max_memory_restart: 2G`, now raised + `PORTOS_SERVER_MAX_MEMORY`-configurable, default 4G). `detached: true` does NOT help (TreeKill keys on ppid, not process group); `treekill: false` on the app does NOT work either (pm2 then fails to reap the old node process → it lingers on :5555 → new instance EADDRINUSE crash-loops — tried and reverted). The correct fix is spawn-side: **double-fork the trainer/video-gen child so it reparents to launchd/init (ppid=1) and leaves pm2's tree**, while still streaming stdout for progress (e.g. an intermediate `setsid` launcher that pipes through a fifo/file the parent tails, or a tiny detached supervisor). Apply to BOTH `server/services/loraTraining/index.js:~501` AND `server/services/videoGen/local.js:~918` (same vulnerability). Validate: note the child pid, `pm2 restart portos-server`, confirm the SAME pid keeps running and the job completes. Until then, the raised memory ceiling minimizes restarts and checkpoint-resume recovers any that slip through. Estimated scope: medium.
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index 824843ec98..76e249f651 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -354,6 +354,13 @@
"returnsJson": true,
"variables": []
},
+ "pipeline-script-verify": {
+ "name": "Pipeline — Comic Script Verification",
+ "description": "Craft pass over ONE issue's comic script before art: catches un-renderable panels, missing/malformed page-panel structure, panel-to-panel flow breaks, dialogue/art imbalance, within-issue continuity, and page-turn/beat placement. Used by Series Autopilot's per-issue script gate (advisory — surfaces findings, doesn't auto-rewrite). Returns actionable { severity, location, problem, suggestion } issues — empty list means sound.",
+ "model": "heavy",
+ "returnsJson": true,
+ "variables": []
+ },
"pipeline-manuscript-completeness": {
"name": "Pipeline — Manuscript Completeness",
"description": "Developmental editor pass over the ACTUAL drafted manuscript (comic script / prose / teleplay across all issues), not synopses. Surfaces what's missing to FINISH a near-complete draft: missing-content (beats/pages/scenes), arc-gap (themes/protagonist turns the draft doesn't yet deliver), character-gap (under-developed cast), pacing, and continuity. Returns categorized { severity, category, issueNumber, anchorQuote, location, problem, suggestion } findings — issueNumber + anchorQuote anchor each finding to a manuscript spot so the editor can jump to it; empty list means complete.",
diff --git a/data.reference/prompts/stages/pipeline-script-verify.md b/data.reference/prompts/stages/pipeline-script-verify.md
new file mode 100644
index 0000000000..6dac8ccec9
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-script-verify.md
@@ -0,0 +1,51 @@
+# Pipeline — Comic Script Verification
+
+You are a comics script editor doing a craft pass on ONE issue's comic script **before** it goes to art. Your job is to catch problems that would make the script fail to *function as a comic script* — page/panel structure, visual storytelling, and clarity — so the production pipeline doesn't render broken or un-renderable pages. This is NOT a creative critique: don't suggest "make it darker" or rewrite the story. Only flag concrete craft breaks an artist or letterer would trip over.
+
+## Issue
+
+- **Series:** {{series.name}}
+- **Logline:** {{series.logline}}
+- **Issue:** #{{issue.number}} — {{issue.title}}
+
+## Comic script
+
+```
+{{script}}
+```
+
+## What to look for
+
+Read the script page by page, panel by panel. Flag only concrete, fixable problems:
+
+1. **Un-renderable panels.** A panel whose description gives the artist nothing to draw (pure interiority with no visual — "she realizes she was wrong"), or that crams multiple distinct moments into one panel that can't be a single image.
+2. **Missing or malformed structure.** A page with no panels, a panel with no description, dialogue attributed to no one, or a page that's actually prose paragraphs rather than panel breakdowns.
+3. **Panel-to-panel flow breaks.** A jump where the reader loses the thread between panels (an action with no establishing panel, a reaction with no cause shown, a location change with no re-establish).
+4. **Dialogue/art imbalance.** A panel buried under more dialogue/caption than a single image can carry (wall-of-text balloons), or a key beat with no dialogue *and* no clear visual.
+5. **Continuity within the issue.** A character/prop/setting that appears, changes, or vanishes between panels without explanation (a gun drawn in panel 2 gone in panel 3 with no beat).
+6. **Page-turn / beat placement.** A cliffhanger or reveal placed mid-page where a page turn would land it harder, or a page so overloaded it can't be drawn at the implied panel count.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary. Each `issues[]` entry must be **actionable** — name the page/panel, name the problem, and propose the smallest concrete fix:
+
+```json
+{
+ "issues": [
+ {
+ "severity": "high",
+ "location": "page 3 / panel 2",
+ "problem": "string (what's wrong, with the specific evidence from the script)",
+ "suggestion": "string (the smallest edit that resolves it)"
+ }
+ ]
+}
+```
+
+`severity` must be one of `high` / `medium` / `low`:
+
+- **`high`** — the panel/page can't be drawn or read as written (no description, no panels, un-renderable interiority, lost thread).
+- **`medium`** — would make the page read poorly (wall-of-text balloon, weak panel-to-panel flow, mid-page reveal).
+- **`low`** — opportunity to tighten (a slightly overloaded page, a missed page-turn beat).
+
+Return `{ "issues": [] }` if the script is sound. Do NOT pad with low-confidence "consider also..." entries.
diff --git a/scripts/migrations/090-script-verify-stage.js b/scripts/migrations/090-script-verify-stage.js
new file mode 100644
index 0000000000..c502b97ef0
--- /dev/null
+++ b/scripts/migrations/090-script-verify-stage.js
@@ -0,0 +1,75 @@
+/**
+ * Seed the `pipeline-script-verify` stage into existing installs.
+ *
+ * Mirrors `088-series-generate-stage.js`: copies the `.md` template from
+ * `data.reference/prompts/stages/` and merges the stage-config entry into
+ * `data/prompts/stage-config.json`. Boot runs migrations (server/index.js) but
+ * NOT `setup-data.js`, so an upgrade that pulls + `pm2 restart`s (rather than
+ * running `update.sh`) would otherwise leave the new comic-script verify stage
+ * unseeded and Series Autopilot's `verifyComicScript` would throw
+ * "Stage not found" the first time the script gate runs.
+ */
+
+import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';
+import { dirname, join } from 'path';
+
+const FILENAME = 'pipeline-script-verify.md';
+const STAGE_KEY = 'pipeline-script-verify';
+
+export default {
+ async up({ rootDir }) {
+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ await mkdir(stagesDir, { recursive: true });
+
+ const dataPath = join(stagesDir, FILENAME);
+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', FILENAME);
+
+ const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);
+ if (exists) {
+ console.log(`📝 pipeline-script-verify prompt: already present`);
+ } else {
+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
+ if (!sampleExists) {
+ console.warn(`⚠️ pipeline-script-verify: sample missing for ${FILENAME} — skipping copy`);
+ } else {
+ try {
+ await copyFile(samplePath, dataPath);
+ console.log(`✅ seeded ${FILENAME}`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-script-verify: copy failed for ${FILENAME}: ${err.message}`);
+ }
+ }
+ }
+
+ const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);
+ if (!sampleConfigExists) {
+ console.warn('⚠️ pipeline-script-verify: data.reference stage-config.json missing — cannot resolve entry; skipping config write');
+ return;
+ }
+ try {
+ const sample = JSON.parse(await readFile(sampleConfigPath, 'utf8'));
+ const installedExists = await access(installedConfigPath, constants.F_OK).then(() => true, () => false);
+ const installed = installedExists
+ ? JSON.parse(await readFile(installedConfigPath, 'utf8'))
+ : { stages: {} };
+ installed.stages = installed.stages || {};
+ if (installed.stages[STAGE_KEY]) {
+ console.log(`📝 pipeline-script-verify stage-config: already present`);
+ return;
+ }
+ if (!sample?.stages?.[STAGE_KEY]) {
+ console.warn(`⚠️ pipeline-script-verify: sample stage-config missing ${STAGE_KEY} — skipping`);
+ return;
+ }
+ installed.stages[STAGE_KEY] = sample.stages[STAGE_KEY];
+ await mkdir(dirname(installedConfigPath), { recursive: true });
+ await writeFile(installedConfigPath, JSON.stringify(installed, null, 2) + '\n', 'utf8');
+ const action = installedExists ? 'merged' : 'created';
+ console.log(`📝 pipeline-script-verify stage-config (${action}): 1 added`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-script-verify: stage-config merge failed: ${err.message}`);
+ }
+ },
+};
diff --git a/server/services/pipeline/scriptVerify.js b/server/services/pipeline/scriptVerify.js
new file mode 100644
index 0000000000..1b1a5d8ae5
--- /dev/null
+++ b/server/services/pipeline/scriptVerify.js
@@ -0,0 +1,68 @@
+/**
+ * Pipeline — Comic Script Verification (craft pass)
+ *
+ * Runs the `pipeline-script-verify` stage over ONE issue's comic script to
+ * catch craft breaks that would make the script fail to function as a comic
+ * script (un-renderable panels, malformed page/panel structure, panel-to-panel
+ * flow breaks, dialogue/art imbalance, within-issue continuity, page-turn
+ * placement) — before the visual pipeline burns GPU on broken pages.
+ *
+ * Extraction-only, mirrors `verifyArc` (arcCore.js): returns the shaped issues
+ * list; the caller (Series Autopilot's scriptVerify step) decides what to do
+ * with them. Content is budgeted to the target model's context window the same
+ * way editorialAnalysis does, so a big script isn't truncated harder than
+ * necessary.
+ */
+
+import { runStagedLLM, resolveStageContext } from '../../lib/stageRunner.js';
+import { usableInputTokens, estimateTokens, CHARS_PER_TOKEN } from '../../lib/contextBudget.js';
+import { getIssue } from './issues.js';
+import { getSeries } from './series.js';
+import { shapeVerifyIssues } from './arcPlanner.js';
+
+const STAGE = 'pipeline-script-verify';
+const CONTENT_MAX = 48_000;
+const OUTPUT_RESERVE_TOKENS = 2_000;
+
+/**
+ * Verify the comic script of one issue. Returns
+ * `{ issues:[{severity,location,problem,suggestion}], raw, runId, providerId,
+ * model }`, or `{ issues: [], skipped }` when there's no comic script to check.
+ */
+export async function verifyComicScript(issueId, { providerId, model } = {}) {
+ const issue = await getIssue(issueId);
+ const script = (issue.stages?.comicScript?.output || '').trim();
+ if (!script) return { issues: [], skipped: 'no-comic-script' };
+
+ const series = await getSeries(issue.seriesId).catch(() => null);
+
+ // Scale the content cap to the target model's context window — never below
+ // CONTENT_MAX (so we never truncate more than the historical floor), but a
+ // big-context model gets the whole script. Mirrors editorialAnalysis.
+ const { contextWindow } = await resolveStageContext(STAGE, { providerOverride: providerId, modelOverride: model });
+ const overheadTokens = 1_200 + estimateTokens([series?.name, series?.logline, issue.title].filter(Boolean).join(' '));
+ const budgetChars = usableInputTokens({
+ contextWindow,
+ overheadTokens,
+ outputReserveTokens: OUTPUT_RESERVE_TOKENS,
+ }) * CHARS_PER_TOKEN;
+ const contentMax = Math.max(CONTENT_MAX, budgetChars);
+ const content = script.length > contentMax
+ ? `${script.slice(0, contentMax)}\n\n[script truncated for verification — ${script.length} chars total]`
+ : script;
+
+ const ctx = {
+ series: { name: series?.name || 'Untitled series', logline: series?.logline || '' },
+ issue: { number: issue.number ?? '', title: issue.title || '' },
+ script: content,
+ };
+
+ const { content: parsed, runId, providerId: pid, model: m } = await runStagedLLM(STAGE, ctx, {
+ returnsJson: true,
+ providerOverride: providerId,
+ modelOverride: model,
+ source: 'pipeline-script-verify',
+ });
+
+ return { issues: shapeVerifyIssues(parsed?.issues), raw: parsed, runId, providerId: pid, model: m };
+}
diff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.js
index cc84253cce..0171a58d47 100644
--- a/server/services/pipeline/seriesAutopilot.js
+++ b/server/services/pipeline/seriesAutopilot.js
@@ -38,12 +38,13 @@
* error — it files a deduped CoS task (`fileGap`) so the gap is tracked instead
* of silently swallowed.
*
- * 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); deeper craft issues are caught by the
- * series-level editorial completeness pass, which already analyzes comic
- * scripts. A dedicated craft-level LLM script-verify prompt is a deferred
- * follow-up (see PLAN.md), not silently assumed solved.
+ * SCRIPT VERIFICATION — the per-issue scriptVerify step has two gates: a
+ * STRUCTURAL gate (does the script parse into pages/panels — a failure blocks
+ * page extraction, so it files a gap) and a CRAFT gate (the
+ * `pipeline-script-verify` LLM pass via verifyComicScript). The craft gate is
+ * ADVISORY: script craft is subjective and the gating quality pass is the
+ * series-level editorial review, so blocking craft findings are surfaced + filed
+ * (not auto-rewritten, not a hard pause) and the run keeps moving toward a draft.
*
* DRAFT VISUALS (Phase 2, VISUAL_DRAFT_ENABLED): once a story is text-ready,
* extract comic pages from the script (if not already), then enqueue PROOF
@@ -83,6 +84,7 @@ import * as volumeBeatsRunner from './volumeBeatsRunner.js';
import * as autoRunner from './autoRunner.js';
import { seedReviewFromFindings, getReview } from './manuscriptReview.js';
import { generateManuscriptFix, acceptManuscriptFix } from './manuscriptFix.js';
+import { verifyComicScript } from './scriptVerify.js';
// runs: Map<seriesId, { runId, clients[], lastPayload, cancelRequested, finished,
// cleanupTimer, startedAt, mode, options, runState, activeChild }>
@@ -403,8 +405,10 @@ const runText = (issueId, record) => runChildToCompletion(record, {
async function runScriptVerify(sId, issueId, record) {
record.runState.scriptChecked.add(issueId);
const issue = await getIssue(issueId);
+
+ // Gate 1 — STRUCTURAL (pure, cheap): does the script parse into pages/panels?
+ // A structural failure blocks page extraction, so surface + file a gap.
if (!scriptStructurallyReady(issue)) {
- // Structural gap — surface it but don't block the run. Not billable.
broadcast(sId, {
type: 'step:skip',
kind: 'scriptVerify',
@@ -417,6 +421,33 @@ async function runScriptVerify(sId, issueId, record) {
summary: 'The comic script for this issue does not parse into pages/panels, so comic pages can\'t be extracted. It likely needs a manual fix or regeneration of the comicScript stage.',
context: `issueId=${issueId}`,
});
+ return {};
+ }
+
+ // Gate 2 — CRAFT (LLM): does the script function as a comic script? This is
+ // ADVISORY — unlike arc continuity, script craft is subjective and the
+ // gating quality pass is the series-level editorial review, so blocking
+ // findings are surfaced + filed (not auto-rewritten, not a hard pause) and
+ // the autopilot keeps moving toward a draft. Wrapped so an LLM failure
+ // downgrades to a skip instead of aborting the whole run.
+ let issues = [];
+ try {
+ const result = await verifyComicScript(issueId, providerIdOpts(record));
+ issues = result.issues || [];
+ await recordDomainUsage('cos', { actions: 1 });
+ } catch (err) {
+ broadcast(sId, { type: 'step:skip', kind: 'scriptVerify', issueId, reason: `craft verify unavailable: ${(err?.message || err).toString().slice(0, 200)}` });
+ return {};
+ }
+ const blocking = issues.filter((i) => i.severity === 'high');
+ broadcast(sId, { type: 'verify:round', scope: 'script', issueId, round: 1, findings: issues.length, blocking: blocking.length });
+ if (blocking.length) {
+ await fileGap(record, sId, {
+ gapKind: 'script-craft',
+ issueId,
+ summary: `Comic script craft review found ${blocking.length} blocking issue(s): ${blocking.map((b) => b.problem).join(' | ').slice(0, 600)}`,
+ context: JSON.stringify(blocking).slice(0, 1000),
+ });
}
return {};
}
diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
index 2424aa711c..1aeaf76089 100644
--- a/server/services/pipeline/seriesAutopilot.test.js
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -86,6 +86,10 @@ let nextTaskId = 0;
const addTask = vi.fn(async () => ({ id: `task-gap-${++nextTaskId}` }));
vi.mock('../cosTaskStore.js', () => ({ addTask }));
+let scriptVerifyFindings = [];
+const verifyComicScript = vi.fn(async () => ({ issues: scriptVerifyFindings }));
+vi.mock('./scriptVerify.js', () => ({ verifyComicScript }));
+
// Real services + the unit under test (imported AFTER the mocks above).
const seriesSvc = await import('./series.js');
const seasonsSvc = await import('./seasons.js');
@@ -116,6 +120,7 @@ beforeEach(() => {
budgetStatus = { withinBudget: true, exceeded: null };
verifyFindings = [];
editorialFindings = [];
+ scriptVerifyFindings = [];
nextTaskId = 0;
autopilot.__testing.runs.clear();
vi.clearAllMocks();
@@ -399,6 +404,25 @@ describe('autopilot conductor', () => {
expect(addTask).not.toHaveBeenCalled();
});
+ it('runs the LLM craft script verify and continues (advisory) when it is clean', async () => {
+ const { seriesId } = await seedComplete();
+ await autopilot.startSeriesAutopilot(seriesId, { includeVisual: false });
+ await waitFor(runFinished(seriesId));
+ expect(verifyComicScript).toHaveBeenCalledTimes(1);
+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('complete');
+ });
+
+ it('files a gap for blocking script-craft findings but does not block the run', async () => {
+ scriptVerifyFindings = [{ severity: 'high', problem: 'page 2 panel 1 has no description' }];
+ const { seriesId } = await seedComplete();
+ await autopilot.startSeriesAutopilot(seriesId, { fileGaps: true, includeVisual: false });
+ await waitFor(runFinished(seriesId));
+ // advisory: run still completes
+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('complete');
+ const gapKinds = addTask.mock.calls.map((c) => c[0].description);
+ expect(gapKinds.some((d) => /script-craft/.test(d))).toBe(true);
+ });
+
it('files a CoS gap task when a verify gate stalls (fileGaps)', async () => {
verifyFindings = [{ severity: 'high', problem: 'unresolved plot hole' }];
const { seriesId } = await seedComplete();