Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
add canon descriptive-integrity gate before visual production
[._.]/ Adam Eivydcf6824611df
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 5ad2c7e3f8..f6a61a3e69 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. 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`)+- **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 → **canon descriptive-integrity gate** → **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). Before any visual production it also runs a **canon descriptive-integrity gate**: every canon noun (character/place/object) that appears where it would be *drawn* — the comic-script panel descriptions, not prose narration — must have a description, or the run **pauses for human review** (an artist can't render a name). The visual-source distinction is deliberate: an off-page character named only in narration is never drawn, so it's a Nouns-stage quality note, not a production blocker. The same check is exposed for the pipeline UI via `GET /api/pipeline/issues/:id/canon-readiness` and `GET /api/pipeline/series/:id/canon-readiness` (read-only, deterministic — reuses the committed canon name-matchers and `getSeriesCanon`). (`server/services/pipeline/seriesAutopilot.js`, `server/services/pipeline/scriptVerify.js`, `server/services/pipeline/canonReadiness.js`, `server/routes/pipeline/canon.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/server/routes/pipeline/canon.js b/server/routes/pipeline/canon.jsnew file mode 100644index 0000000000..19a48a61c2--- /dev/null+++ b/server/routes/pipeline/canon.js@@ -0,0 +1,32 @@+/**+ * Pipeline canon-readiness routes — descriptive-integrity check for the canon+ * entities (characters/places/objects) an issue or series will actually render.+ * Read-only; powers the production sign-off gate (and the same check Series+ * Autopilot runs before drafting visuals).+ *+ * GET /issues/:id/canon-readiness → { issueId, referenced, none[], thin[], ready }+ * GET /series/:id/canon-readiness → { seriesId, ready, issues[], blockingIssues[], undescribed[] }+ */++import { Router } from 'express';+import { asyncHandler } from '../../lib/errorHandler.js';+import * as seriesSvc from '../../services/pipeline/series.js';+import * as issuesSvc from '../../services/pipeline/issues.js';+import { checkIssueCanonReadiness, checkSeriesCanonReadiness } from '../../services/pipeline/canonReadiness.js';+import { mapServiceError } from './shared.js';++const router = Router();++router.get('/issues/:id/canon-readiness', asyncHandler(async (req, res) => {+ await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });+ const report = await checkIssueCanonReadiness(req.params.id).catch((err) => { throw mapServiceError(err); });+ res.json(report);+}));++router.get('/series/:id/canon-readiness', asyncHandler(async (req, res) => {+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });+ const report = await checkSeriesCanonReadiness(req.params.id).catch((err) => { throw mapServiceError(err); });+ res.json(report);+}));++export default router;diff --git a/server/routes/pipeline/index.js b/server/routes/pipeline/index.jsindex 5282906df2..cdd10ed45c 100644--- a/server/routes/pipeline/index.js+++ b/server/routes/pipeline/index.js@@ -24,6 +24,8 @@* GET /series/:id/autopilot/progress → SSE (text/event-stream)* POST /series/:id/autopilot/cancel → { canceled }* GET /series/:id/autopilot/status → { autopilot, active }+ * GET /issues/:id/canon-readiness → { referenced, none, thin, ready }+ * GET /series/:id/canon-readiness → { ready, issues, blockingIssues, undescribed }** Assembled from domain sub-routers (mirrors the cos.js pattern). Mount* order preserves the original single-file registration order; the only@@ -41,6 +43,7 @@ import coverRoutes from './covers.js';import issueRoutes from './issues.js';import editorialRoutes from './editorial.js';import autopilotRoutes from './autopilot.js';+import canonRoutes from './canon.js';const router = Router();@@ -52,5 +55,6 @@ router.use(coverRoutes);router.use(issueRoutes);router.use(editorialRoutes);router.use(autopilotRoutes);+router.use(canonRoutes);export default router;diff --git a/server/services/pipeline/canonReadiness.js b/server/services/pipeline/canonReadiness.jsnew file mode 100644index 0000000000..c495768220--- /dev/null+++ b/server/services/pipeline/canonReadiness.js@@ -0,0 +1,138 @@+/**+ * Pipeline — Canon descriptive-integrity readiness.+ *+ * Before the visual pipeline renders comic pages / storyboards, the canon+ * entities (characters / places / objects) that actually get DRAWN must be+ * adequately described — an artist can't render "Kai" from a name alone. This+ * is the production-readiness counterpart to the Nouns stage's per-noun gap+ * flagging: it gates *visual sign-off*, not authoring.+ *+ * The check matches canon against the VISUAL SOURCE text (the comic script's+ * panel descriptions for comics, the teleplay for TV) — NOT the prose. That+ * distinction matters: a character merely name-dropped in narration but never+ * shown in a panel (an off-page character) is never rendered, so a missing+ * description for it is a manuscript-quality note (surfaced on the Nouns page),+ * not a visual production blocker. Only nouns that appear where they'd be drawn+ * gate rendering.+ *+ * Deterministic — presence + length grading, no LLM. (The concurrent+ * "describe from prose" feature BACKFILLS descriptions with an LLM; this+ * VALIDATES that they exist before production. They're complementary.)+ */++import { getIssue, listIssues } from './issues.js';+import { getSeries } from './series.js';+import { getSeriesCanon } from './seriesCanon.js';+import { matchCharactersInText, matchPlacesInText, matchObjectsInText } from '../../lib/scenePrompt.js';++// Below this many characters a description is "thin" — present but too sparse to+// reliably render from. Advisory only; `none` (no description at all) is the+// blocking grade.+export const CANON_THIN_CHARS = 40;++// Per-kind: where the canon list lives, how to find references in text, and how+// to read the entity's renderable description (mirrors NounsStage's `descFor`).+const KINDS = [+ {+ kind: 'character',+ listKey: 'characters',+ match: matchCharactersInText,+ descOf: (e) => e.physicalDescription || e.description || '',+ },+ {+ kind: 'place',+ listKey: 'places',+ match: matchPlacesInText,+ descOf: (e) => [e.description, e.palette, e.recurringDetails].filter(Boolean).join('. '),+ },+ {+ kind: 'object',+ listKey: 'objects',+ match: matchObjectsInText,+ descOf: (e) => e.description || e.significance || '',+ },+];++export function gradeCanonDescription(descOf, entry, thinChars = CANON_THIN_CHARS) {+ const desc = (descOf(entry) || '').trim();+ if (!desc) return 'none';+ if (desc.length < thinChars) return 'thin';+ return 'sufficient';+}++/**+ * PURE: grade every canon noun that appears in `text`. Returns+ * `{ referenced, none[], thin[], ready }`. `none`/`thin` entries carry+ * `{ id, name, kind, locked }`. No I/O — caller supplies the text + canon.+ */+export function gradeReferencedNouns(text, canon, thinChars = CANON_THIN_CHARS) {+ const none = [];+ const thin = [];+ let referenced = 0;+ if (text && text.trim()) {+ for (const { kind, listKey, match, descOf } of KINDS) {+ const list = Array.isArray(canon?.[listKey]) ? canon[listKey] : [];+ for (const entry of match(text, list)) {+ referenced += 1;+ const grade = gradeCanonDescription(descOf, entry, thinChars);+ if (grade === 'none') none.push({ id: entry.id, name: entry.name, kind, locked: entry.locked === true });+ else if (grade === 'thin') thin.push({ id: entry.id, name: entry.name, kind, locked: entry.locked === true });+ }+ }+ }+ return { referenced, none, thin, ready: none.length === 0 };+}++// The text where nouns are actually depicted, by target format. Comic targets+// draw from the comic-script panel descriptions; TV from the teleplay. Fall+// back to prose only when the visual source is empty so a not-yet-adapted issue+// can still be sanity-checked.+function visualSourceText(issue, series) {+ const fmt = series?.targetFormat || 'comic+tv';+ const comic = issue.stages?.comicScript?.output || '';+ const tele = issue.stages?.teleplay?.output || '';+ const prose = issue.stages?.prose?.output || '';+ if (fmt === 'tv') return tele || prose;+ return comic || tele || prose;+}++/**+ * Canon readiness for one issue. Pass `canon`/`series` to avoid re-reads when+ * checking many issues. Returns+ * `{ issueId, number, title, referenced, none[], thin[], ready }`.+ */+export async function checkIssueCanonReadiness(issueId, { canon = null, series = null, thinChars = CANON_THIN_CHARS } = {}) {+ const issue = await getIssue(issueId);+ const ser = series || await getSeries(issue.seriesId).catch(() => null);+ const c = canon || (ser ? await getSeriesCanon(ser).catch(() => null) : null) || { characters: [], places: [], objects: [] };+ const text = visualSourceText(issue, ser);+ const { referenced, none, thin, ready } = gradeReferencedNouns(text, c, thinChars);+ return { issueId, number: issue.number, title: issue.title, referenced, none, thin, ready };+}++/**+ * Canon readiness across a whole series. Returns the per-issue reports plus a+ * series-level roll-up: `ready` (no issue has an undescribed drawn noun),+ * `blockingIssues[]`, and the de-duplicated `undescribed[]` noun list.+ */+export async function checkSeriesCanonReadiness(seriesId, { thinChars = CANON_THIN_CHARS } = {}) {+ const series = await getSeries(seriesId);+ const canon = await getSeriesCanon(series).catch(() => ({ characters: [], places: [], objects: [] }));+ const issues = await listIssues({ seriesId });+ const perIssue = [];+ for (const issue of issues) {+ perIssue.push(await checkIssueCanonReadiness(issue.id, { canon, series, thinChars }));+ }+ const blocking = perIssue.filter((r) => !r.ready);+ const noneById = new Map();+ for (const r of perIssue) {+ for (const n of r.none) if (!noneById.has(n.id)) noneById.set(n.id, n);+ }+ return {+ seriesId,+ ready: blocking.length === 0,+ issues: perIssue,+ blockingIssues: blocking.map((r) => ({ issueId: r.issueId, number: r.number, title: r.title, none: r.none })),+ undescribed: [...noneById.values()],+ };+}diff --git a/server/services/pipeline/canonReadiness.test.js b/server/services/pipeline/canonReadiness.test.jsnew file mode 100644index 0000000000..8d1de9bf40--- /dev/null+++ b/server/services/pipeline/canonReadiness.test.js@@ -0,0 +1,130 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { mockNoPeerSync, mockNoPeers } from '../../lib/mockPathsDataRoot.js';++// File-backed store so real series/issues run in-memory (mirrors autopilot test).+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)),+}));+vi.mock('../instances.js', () => mockNoPeers());+vi.mock('../sharing/peerSync.js', () => mockNoPeerSync());++// Control the canon returned for a series without standing up a real universe.+let canon = { characters: [], places: [], objects: [] };+vi.mock('./seriesCanon.js', () => ({ getSeriesCanon: vi.fn(async () => canon) }));++const seriesSvc = await import('./series.js');+const issuesSvc = await import('./issues.js');+const readiness = await import('./canonReadiness.js');+const { gradeCanonDescription, gradeReferencedNouns, checkIssueCanonReadiness, checkSeriesCanonReadiness } = readiness;++const charDescOf = (e) => e.physicalDescription || e.description || '';++beforeEach(() => {+ fileStore.clear();+ canon = { characters: [], places: [], objects: [] };+ vi.clearAllMocks();+});++describe('gradeCanonDescription (pure)', () => {+ it('grades none / thin / sufficient by description presence + length', () => {+ expect(gradeCanonDescription(charDescOf, { physicalDescription: '' })).toBe('none');+ expect(gradeCanonDescription(charDescOf, { physicalDescription: ' ' })).toBe('none');+ expect(gradeCanonDescription(charDescOf, { physicalDescription: 'tall, red hair' })).toBe('thin');+ expect(gradeCanonDescription(charDescOf, {+ physicalDescription: 'A tall woman with close-cropped silver hair, a scar over her left eye, and a long grey coat.',+ })).toBe('sufficient');+ });++ it('falls back from physicalDescription to description for characters', () => {+ expect(gradeCanonDescription(charDescOf, { description: 'A tall woman with a long grey weathered coat and boots.' })).toBe('sufficient');+ });+});++describe('gradeReferencedNouns (pure)', () => {+ const canonFixture = {+ characters: [+ { id: 'c1', name: 'Maggie', physicalDescription: 'A wiry hacker in a hoodie with restless hands and tired eyes.' },+ { id: 'c2', name: 'Kai', physicalDescription: '' }, // off-page, never described+ ],+ places: [{ id: 'p1', name: 'The Vault', description: '' }],+ objects: [{ id: 'o1', name: 'the backdoor', description: '' }],+ };++ it('flags referenced-but-undescribed nouns as `none` and ready=false', () => {+ const text = 'Maggie opens the backdoor inside The Vault.';+ const out = gradeReferencedNouns(text, canonFixture);+ expect(out.ready).toBe(false);+ const noneIds = out.none.map((n) => n.id).sort();+ expect(noneIds).toEqual(['o1', 'p1']); // The Vault + the backdoor+ expect(out.none.find((n) => n.id === 'p1')).toMatchObject({ name: 'The Vault', kind: 'place' });+ });++ it('does NOT flag a noun that is never referenced in the text (off-page Kai)', () => {+ // Kai is undescribed but absent from THIS panel text → not a blocker here.+ const text = 'Maggie types at her terminal.';+ const out = gradeReferencedNouns(text, {+ characters: [canonFixture.characters[0], canonFixture.characters[1]],+ places: [], objects: [],+ });+ expect(out.none).toHaveLength(0);+ expect(out.ready).toBe(true);+ });++ it('is ready when every referenced noun is described', () => {+ const text = 'Maggie types.';+ const out = gradeReferencedNouns(text, { characters: [canonFixture.characters[0]], places: [], objects: [] });+ expect(out.ready).toBe(true);+ expect(out.referenced).toBe(1);+ });++ it('returns ready for empty text', () => {+ expect(gradeReferencedNouns('', canonFixture).ready).toBe(true);+ });+});++describe('checkIssueCanonReadiness (matches the visual source)', () => {+ async function seedIssue({ comicScript, prose }) {+ const series = await seriesSvc.createSeries({ name: 'S', logline: 'L', premise: 'P', targetFormat: 'comic' });+ const issue = await issuesSvc.createIssue({ seriesId: series.id, title: 'I1', number: 1 });+ if (comicScript) await issuesSvc.updateStage(issue.id, 'comicScript', { status: 'ready', output: comicScript });+ if (prose) await issuesSvc.updateStage(issue.id, 'prose', { status: 'ready', output: prose });+ return issue.id;+ }++ it('flags a character drawn in a panel but undescribed', async () => {+ canon = { characters: [{ id: 'c1', name: 'Aria', physicalDescription: '' }], places: [], objects: [] };+ const issueId = await seedIssue({ comicScript: 'PAGE 1\nPANEL 1\nAria stands in the doorway.' });+ const report = await checkIssueCanonReadiness(issueId);+ expect(report.ready).toBe(false);+ expect(report.none.map((n) => n.name)).toContain('Aria');+ });++ it('does NOT flag an off-page character (in prose only, not in panels)', async () => {+ // Aria appears only in prose narration, never in the comic-script panels.+ canon = { characters: [{ id: 'c1', name: 'Aria', physicalDescription: '' }], places: [], objects: [] };+ const issueId = await seedIssue({+ comicScript: 'PAGE 1\nPANEL 1\nA dark server room, no one in frame.',+ prose: 'Maggie thought about Aria, who had built the backdoor years ago.',+ });+ const report = await checkIssueCanonReadiness(issueId);+ expect(report.ready).toBe(true); // Aria never drawn → not a visual blocker+ });+});++describe('checkSeriesCanonReadiness (roll-up)', () => {+ it('aggregates undescribed drawn nouns across issues', async () => {+ canon = { characters: [{ id: 'c1', name: 'Aria', physicalDescription: '' }], places: [], objects: [] };+ const series = await seriesSvc.createSeries({ name: 'S', logline: 'L', premise: 'P', targetFormat: 'comic' });+ const i1 = await issuesSvc.createIssue({ seriesId: series.id, title: 'I1', number: 1 });+ await issuesSvc.updateStage(i1.id, 'comicScript', { status: 'ready', output: 'PAGE 1\nPANEL 1\nAria enters.' });+ const report = await checkSeriesCanonReadiness(series.id);+ expect(report.ready).toBe(false);+ expect(report.undescribed.map((n) => n.name)).toContain('Aria');+ expect(report.blockingIssues).toHaveLength(1);+ });+});diff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.jsindex 0171a58d47..b3b57ff890 100644--- a/server/services/pipeline/seriesAutopilot.js+++ b/server/services/pipeline/seriesAutopilot.js@@ -46,6 +46,13 @@* 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.*+* CANON GATE: before any visual production, a series-level canonVerify step+ * (canonReadiness.js) checks that every canon noun appearing where it'd be+ * DRAWN (comic-script panels / teleplay) has a description. Undescribed drawn+ * nouns pause the run for human review — an artist can't render a name. (An+ * off-page noun named only in prose narration is never drawn, so it doesn't+ * block here; it's a Nouns-stage quality note.)+ ** 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* (draft) renders for the front cover, back cover, and every interior page —@@ -85,6 +92,7 @@ import * as autoRunner from './autoRunner.js';import { seedReviewFromFindings, getReview } from './manuscriptReview.js';import { generateManuscriptFix, acceptManuscriptFix } from './manuscriptFix.js';import { verifyComicScript } from './scriptVerify.js';+import { checkSeriesCanonReadiness } from './canonReadiness.js';// runs: Map<seriesId, { runId, clients[], lastPayload, cancelRequested, finished,// cleanupTimer, startedAt, mode, options, runState, activeChild }>@@ -239,6 +247,14 @@ export function resolveNextStep(series, issues, runState = {}, options = {}) {return { kind: 'editorialReview', reason: 'editorial review not yet run this run' };}+ // STEP 5.5 — canon descriptive integrity. Before ANY visual production, every+ // canon noun that appears where it'd be drawn must be described (an artist+ // can't render a name). Runs once per run; the gate blocks (pauses) on+ // undescribed drawn nouns. Only relevant when visuals will be produced.+ if (VISUAL_DRAFT_ENABLED && options.includeVisual && isComicTarget(series) && !runState.canonVerified) {+ return { kind: 'canonVerify', reason: 'canon descriptive integrity not yet verified this run' };+ }+// STEP 6 — draft visuals (cover + back + all interior pages).if (VISUAL_DRAFT_ENABLED && options.includeVisual && isComicTarget(series)) {for (const issue of ordered) {@@ -614,6 +630,37 @@ async function runVisualDraft(sId, issueId, record) {return {};}+// Canon descriptive-integrity gate — deterministic (no LLM), so not billable.+// Pauses for human review when a canon noun that appears in the visual source+// has no description (it can't be drawn). Marks canonVerified when clean so the+// run proceeds to visual drafting.+async function runCanonVerify(sId, record) {+ const report = await checkSeriesCanonReadiness(sId);+ broadcast(sId, {+ type: 'verify:round', scope: 'canon', round: 1,+ findings: report.undescribed.length, blocking: report.undescribed.length,+ });+ if (report.ready) {+ record.runState.canonVerified = true;+ return {};+ }+ const residual = report.undescribed.map((n) => ({+ severity: 'high',+ location: `${n.kind} "${n.name}"`,+ problem: 'Appears where it would be drawn but has no description — can\'t be rendered.',+ }));+ await fileGap(record, sId, {+ gapKind: 'canon-undescribed',+ summary: `${report.undescribed.length} canon noun(s) appear in panels/scenes with no description: ${report.undescribed.map((n) => n.name).join(', ').slice(0, 400)}. Describe them on the Nouns stage before generating pages.`,+ context: JSON.stringify(report.undescribed).slice(0, 1000),+ });+ return {+ pause: true,+ reason: `${report.undescribed.length} canon noun(s) referenced in panels/scenes are undescribed — describe them before visual production`,+ residual,+ };+}+async function dispatchStep(sId, step, record) {switch (step.kind) {case 'generateArc': {@@ -640,6 +687,8 @@ async function dispatchStep(sId, step, record) {return runScriptVerify(sId, step.issueId, record);case 'editorialReview':return runEditorial(sId, record);+ case 'canonVerify':+ return runCanonVerify(sId, record);case 'visualDraft':return runVisualDraft(sId, step.issueId, record);default:@@ -671,6 +720,7 @@ function buildDryRunPlan(series, issues, options) {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: 'canonVerify', count: 1, note: 'descriptive integrity of drawn nouns' });const visualNeeded = ordered.filter((i) => !visualReady(i)).length;if (visualNeeded) plan.push({ kind: 'visualDraft', count: visualNeeded, note: 'cover + back + all pages (draft)' });}@@ -719,6 +769,7 @@ export async function startSeriesAutopilot(sId, options = {}) {runState: {arcVerified: false,editorialReviewed: false,+ canonVerified: false,beatsAttempted: new Set(),textAttempted: new Set(),scriptChecked: new Set(),diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.jsindex 1aeaf76089..9ada88648f 100644--- a/server/services/pipeline/seriesAutopilot.test.js+++ b/server/services/pipeline/seriesAutopilot.test.js@@ -90,6 +90,13 @@ let scriptVerifyFindings = [];const verifyComicScript = vi.fn(async () => ({ issues: scriptVerifyFindings }));vi.mock('./scriptVerify.js', () => ({ verifyComicScript }));+let canonReady = true;+let canonUndescribed = [];+const checkSeriesCanonReadiness = vi.fn(async (seriesId) => ({+ seriesId, ready: canonReady, issues: [], blockingIssues: [], undescribed: canonUndescribed,+}));+vi.mock('./canonReadiness.js', () => ({ checkSeriesCanonReadiness }));+// Real services + the unit under test (imported AFTER the mocks above).const seriesSvc = await import('./series.js');const seasonsSvc = await import('./seasons.js');@@ -121,6 +128,8 @@ beforeEach(() => {verifyFindings = [];editorialFindings = [];scriptVerifyFindings = [];+ canonReady = true;+ canonUndescribed = [];nextTaskId = 0;autopilot.__testing.runs.clear();vi.clearAllMocks();@@ -195,13 +204,23 @@ describe('resolveNextStep (pure)', () => {expect(step.kind).toBe('done');});- it('asks for visual draft when includeVisual and pages are not rendered', () => {+ it('asks for canon verify before visuals when includeVisual', () => {const step = resolveNextStep(comic,[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],{ arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true },{ includeVisual: true },);+ expect(step.kind).toBe('canonVerify');+ });++ it('asks for visual draft once canon is verified and pages are not rendered', () => {+ const step = resolveNextStep(+ comic,+ [issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],+ { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, canonVerified: true },+ { includeVisual: true },+ );expect(step).toMatchObject({ kind: 'visualDraft', issueId: 'iss1' });});@@ -217,7 +236,7 @@ describe('resolveNextStep (pure)', () => {const step = resolveNextStep(comic,[issue({ stages: renderedStages })],- { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true },+ { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, canonVerified: true },{ includeVisual: true },);expect(step.kind).toBe('done');@@ -376,6 +395,32 @@ describe('autopilot conductor', () => {expect(series.autopilot?.status).toBe('done');});+ it('pauses before visuals when a drawn canon noun is undescribed', async () => {+ canonReady = false;+ canonUndescribed = [{ id: 'c1', name: 'Kai', kind: 'character' }];+ const { seriesId } = await seedComplete();+ await autopilot.startSeriesAutopilot(seriesId, { includeVisual: true });+ await waitFor(runFinished(seriesId));+ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;+ expect(last?.type).toBe('paused');+ expect(last?.scope).toBe('canonVerify');+ expect(last?.residualFindings?.[0]?.location).toMatch(/Kai/);+ // gate is BEFORE visual production — no renders kicked off+ expect(visualSpies.enqueueComicCover).not.toHaveBeenCalled();+ const series = await seriesSvc.getSeries(seriesId);+ expect(series.autopilot?.status).toBe('paused');+ });++ it('proceeds to visuals once canon is ready', async () => {+ canonReady = true;+ const { seriesId } = await seedComplete();+ await autopilot.startSeriesAutopilot(seriesId, { includeVisual: true });+ await waitFor(runFinished(seriesId));+ expect(checkSeriesCanonReadiness).toHaveBeenCalled();+ expect(visualSpies.enqueueComicCover).toHaveBeenCalled();+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('complete');+ });+it('does not render visuals when includeVisual is false', async () => {const { seriesId } = await seedComplete();await autopilot.startSeriesAutopilot(seriesId, { includeVisual: false });