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

feat: editorial check for comic↔prose synchronization in hybrid issues (#1589)

Adam Eivyda9906d57685
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f2a1a6b269..36703693e6 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -65,6 +65,8 @@
- **[issue-1588] A new opt-in editorial check catches contradictions to real-world facts — Paris placed in Germany, an anachronistic technology, a physiologically impossible feat.** Distinct from the internal timeline/canon check (#1581), nothing reconciled grounded fiction against *external* truth, so a checkable howler in a historical or hard-SF series — a city in the wrong country, an event dated before the war it belongs to, a survivable injury that isn't — could ship and quietly torch the story's credibility. The new **Research / fact accuracy** check (`research.fact-accuracy`) scans the stitched manuscript against an **author-supplied fact reference** and flags geography, history/chronology, and science/physiology claims that contradict it. It is deliberately **opt-in and gated**: it runs only when a series is marked **fact-critical** *and* a non-empty fact reference is supplied, so it never second-guesses deliberate invention in pure fantasy. A new **Fact accuracy** section in the series bible (Pipeline → series) carries the toggle + reference textarea; the reference is a fingerprinted editorial source (`series.factReference`), so editing it re-runs the check, and findings surface in the existing editorial-review UI and Series Autopilot under a new **Fact accuracy** category. Both new series fields (`factCritical`, `factReference`) are wire-gated (pipelineSeries schema v7) so an older federated peer can't strip-then-LWW the loss. (`server/lib/editorial/checkRegistry.js`, `server/services/pipeline/series.js`, `client/src/pages/PipelineSeries.jsx`, `data.reference/prompts/stages/pipeline-editorial-fact-accuracy.md`, `scripts/migrations/135-editorial-fact-accuracy-stage.js`)
+- **[issue-1589] A new editorial check catches comic↔prose drift in hybrid issues — a plot beat the prose narrates that no panel shows, panel dialogue that contradicts the prose, or events ordered differently across the two media.** The existing `comic.*` checks validate comic content *in isolation* (lettering load, balloon attribution, panel rhythm), but for an issue told as **both prose and comic** nothing checked that the two media tell the *same* story — so a character the prose stabs could stand unharmed in the panels, a line could be put in a different character's mouth on the page, or the comic could reorder events the prose places in a fixed sequence, all unflagged. The new **Comic ↔ prose synchronization** check (`comic.prose-sync`) pairs each hybrid issue's prose narration with its authoritative comic pages (each panel's visual description, dialogue, captions, and SFX) and flags three substantive divergences: an **unshown beat** (a consequential event the prose narrates that no panel depicts), **contradicted dialogue** (a line said with materially different meaning or attributed to a different speaker), and a **chronology disagreement** (the two media ordering the same events incompatibly). It is deliberately tuned to *ignore* ordinary medium translation — comics legitimately compress, cut, reorder for page rhythm, and externalize interior narration into image — so a faithful adaptation that simply differs in density isn't flagged. It runs one model call per issue that has both prose and comic content (capped per run), reads the per-issue manuscript prose plus the `comicScript.pacing` comic content, and anchors every finding to its issue; its findings go stale and re-run when either the prose or the comic for that issue drifts. It's a default-on, issue-scope check that surfaces in the existing editorial-review UI and Series Autopilot like every other check, marking a flat contradiction or a dropped consequential beat medium-severity. (`server/lib/editorial/checkRegistry.js`, `data.reference/prompts/stages/pipeline-editorial-comic-prose-sync.md`, `scripts/migrations/135-editorial-comic-prose-sync-stage.js`)
+
## Series Autopilot
- **[issue-1510] Series Autopilot now catches whole-book continuity problems at the cheap beat stage, before it generates full scripts.** The autopilot reviewed continuity at two altitudes — the cross-volume synopsis pass (before beats exist) and the full-text editorial pass (after every issue's script is written, the most expensive stage) — leaving a gap in between. So structural defects spanning the whole book (a cliffhanger raised in one issue and never resolved, a finale that drifts onto a new subplot instead of landing the arc's intended ending, a promised through-line that never pays off, an event staged as the "first" in two different issues, a broken volume-to-volume hand-off) were only caught *after* all the scripts already existed — or not until a human read it. The autopilot now runs a **whole-manuscript beat-continuity pass over every issue's beat sheet, between beat generation and script generation**. Blocking findings are auto-resolved by rewriting just the affected issues' beats and re-checking (bounded, then it pauses for review with the residual findings), so the fix lands before any script is generated. The full-text editorial pass is unchanged and still catches what only the verbatim script can show (pacing, repeated/looping passages, dialogue craft). A new **Beat continuity rounds** control in the autopilot Options tunes how many auto-resolve rounds it attempts (0 skips the pass), saved as a per-install default like the existing Arc-verify and Editorial round knobs.
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index 9864935755..7a30429dd8 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -736,6 +736,13 @@
"model": "default",
"returnsJson": true,
"variables": []
+ },
+ "pipeline-editorial-comic-prose-sync": {
+ "name": "Pipeline — Editorial Check: Comic ↔ prose synchronization (hybrid issues)",
+ "description": "Editorial check (#1589): cross-media consistency for hybrid comic+prose issues. Pairs each issue's prose narration with its authoritative comic pages (description + dialogue + caption + SFX) and flags SUBSTANTIVE divergences — a plot beat the prose narrates that no panel shows, panel dialogue that contradicts the prose (different words or a different speaker), or a chronology disagreement across the two media. Tuned to ignore ordinary medium-translation compression/reordering; reads the per-issue manuscript prose + comicScript.pacing. Runs one model call per hybrid issue. Returns issue-anchored findings.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
}
}
}
diff --git a/data.reference/prompts/stages/pipeline-editorial-comic-prose-sync.md b/data.reference/prompts/stages/pipeline-editorial-comic-prose-sync.md
new file mode 100644
index 0000000000..0624b0defe
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-editorial-comic-prose-sync.md
@@ -0,0 +1,106 @@
+# Pipeline — Editorial Check: Comic ↔ prose synchronization
+
+You are a developmental editor doing a single focused pass for ONE concern on a
+**hybrid comic + prose issue**: whether the **comic visually shows and says what
+the prose narrates** for the SAME issue. The story is told in two media at once —
+a prose manuscript and a comic-script breakdown of the same events. Your job is to
+catch places where the two media **disagree on substance**, so a reader following
+both isn't whiplashed by a contradiction.
+
+You are judging ONE issue at a time. Below you are given that issue's prose and its
+comic content (page-by-page, panel-by-panel: what each panel SHOWS, who SPEAKS and
+what they say, plus captions and SFX).
+
+Flag three kinds of divergence:
+
+- **Unshown beat.** The prose narrates a concrete, consequential event, action, or
+ reveal that NO panel depicts — a plot beat that happens in the prose but is
+ invisible in the comic (e.g. the prose says a character is stabbed, but no panel
+ shows the wound, the attack, or its aftermath). Flag the missing beat, not every
+ descriptive detail the comic compresses.
+- **Contradicted dialogue.** A line the prose puts in one character's mouth is, in
+ the comic, said with **materially different meaning**, or attributed to a
+ **different speaker**. A reworded-but-equivalent line is NOT a finding; a line
+ that changes who said it, or what they decided/promised/revealed, IS.
+- **Chronology disagreement.** The two media order the same events differently — a
+ panel shows an event the prose places later, or the comic's sequence contradicts
+ the prose's "before/after." Flag only an actual ordering conflict, not a comic
+ that simply opens on a different beat.
+
+A comic is NOT a panel-for-paragraph transcription of the prose. **Comics
+legitimately compress, cut, reorder for page rhythm, and externalize interior
+prose into image.** Do NOT flag:
+
+- ordinary compression — the comic covering in three panels what the prose covers
+ in three pages;
+- interior narration (a character's unspoken thoughts/feelings) that the comic
+ conveys through image and expression instead of a caption — that is craft, not a
+ gap;
+- a faithfully reworded line that keeps the same speaker and meaning;
+- a missing minor sensory or descriptive detail that doesn't change the story.
+
+Flag only divergences a reader would experience as the two media **telling a
+different story** — a contradiction or a dropped beat that matters, not a stylistic
+translation choice.
+
+## Issue under review
+
+This is **Issue {{issueNumber}}**. Attribute every finding's `issueNumber` to
+**{{issueNumber}}**.
+
+## Prose
+
+The prose narration for this issue. It may be truncated to a length cap — if it
+ends abruptly, judge only the events visible here and do not flag a "missing beat"
+for a panel that depicts something past where the prose text stops.
+
+```
+{{prose}}
+```
+
+## Comic
+
+The authoritative comic breakdown for this issue — each panel's visual content
+(`Shows:`), spoken dialogue (`Speaker: line`), captions, and SFX.
+
+```
+{{comic}}
+```
+
+## Task
+
+1. Read the prose and the comic as two tellings of the SAME issue.
+2. Identify SUBSTANTIVE divergences of the three kinds above (unshown beat,
+ contradicted dialogue, chronology disagreement). Set `location` to the concern
+ plus where it lands (e.g. `Issue {{issueNumber}} — unshown beat (Page 3)` or
+ `Issue {{issueNumber}} — dialogue mismatch`). Quote the offending PROSE line (or
+ a short panel line) as the `anchorQuote`.
+3. If the comic faithfully tells the same story as the prose — compressing and
+ reordering for the medium without contradicting it — return an empty `findings`
+ array. Do NOT invent a mismatch where the two media simply differ in density or
+ pacing.
+
+Severity: a flat contradiction (a line attributed to the wrong character, an event
+the two media order incompatibly) or a consequential plot beat shown in one medium
+and absent from the other is medium; a softer divergence the reader would likely
+shrug off is low.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no
+commentary:
+
+```json
+{
+ "findings": [
+ {
+ "severity": "high|medium|low",
+ "issueNumber": {{issueNumber}},
+ "location": "string — concern + where (e.g. 'Issue {{issueNumber}} — unshown beat (Page 3)' or 'Issue {{issueNumber}} — dialogue mismatch')",
+ "problem": "1–3 sentences naming the divergence: what the prose says vs what the comic shows/says, and why it reads as a contradiction or dropped beat rather than ordinary compression",
+ "suggestion": "1–3 sentences proposing how to reconcile the two media (add a panel for the unshown beat, fix the speaker/line, or align the ordering)",
+ "anchorQuote": "short verbatim quote of the offending PROSE line or panel line (≤ 200 chars)"
+ }
+ ]
+}
+```
diff --git a/scripts/migrations/135-editorial-comic-prose-sync-stage.js b/scripts/migrations/135-editorial-comic-prose-sync-stage.js
new file mode 100644
index 0000000000..93648e0a29
--- /dev/null
+++ b/scripts/migrations/135-editorial-comic-prose-sync-stage.js
@@ -0,0 +1,75 @@
+/**
+ * Seed the `pipeline-editorial-comic-prose-sync` stage into existing installs (#1589).
+ *
+ * Mirrors `134-editorial-voice-consistency-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-prose-sync stage unseeded and the
+ * `comic.prose-sync` editorial check would throw "Stage not found" the first time it
+ * runs.
+ */
+
+import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';
+import { dirname, join } from 'path';
+
+const FILENAME = 'pipeline-editorial-comic-prose-sync.md';
+const STAGE_KEY = 'pipeline-editorial-comic-prose-sync';
+
+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-editorial-comic-prose-sync prompt: already present`);
+ } else {
+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
+ if (!sampleExists) {
+ console.warn(`⚠️ pipeline-editorial-comic-prose-sync: sample missing for ${FILENAME} — skipping copy`);
+ } else {
+ try {
+ await copyFile(samplePath, dataPath);
+ console.log(`✅ seeded ${FILENAME}`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-editorial-comic-prose-sync: 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-editorial-comic-prose-sync: 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-editorial-comic-prose-sync stage-config: already present`);
+ return;
+ }
+ if (!sample?.stages?.[STAGE_KEY]) {
+ console.warn(`⚠️ pipeline-editorial-comic-prose-sync: 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-editorial-comic-prose-sync stage-config (${action}): 1 added`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-editorial-comic-prose-sync: stage-config merge failed: ${err.message}`);
+ }
+ },
+};
diff --git a/scripts/migrations/135-editorial-comic-prose-sync-stage.test.js b/scripts/migrations/135-editorial-comic-prose-sync-stage.test.js
new file mode 100644
index 0000000000..197d63e196
--- /dev/null
+++ b/scripts/migrations/135-editorial-comic-prose-sync-stage.test.js
@@ -0,0 +1,86 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+
+import migration from './135-editorial-comic-prose-sync-stage.js';
+
+// scripts/migrations/<this> → ../.. is the repo root (matches _testHelpers.js).
+const repoRoot = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
+
+// First-shipment seed migration (mirrors 134) — no MD5 bookkeeping, so the
+// seed / no-clobber behavior is asserted directly.
+
+const FILENAME = 'pipeline-editorial-comic-prose-sync.md';
+const STAGE_KEY = 'pipeline-editorial-comic-prose-sync';
+const BODY = '# Comic ↔ prose synchronization\n\nshipped body\n';
+
+describe('migration 135 — seed editorial-comic-prose-sync stage', () => {
+ let rootDir;
+ let stagesDir;
+ let refStagesDir;
+ let installedConfigPath;
+
+ const seedReference = ({ withConfig = true } = {}) => {
+ writeFileSync(join(refStagesDir, FILENAME), BODY);
+ if (withConfig) {
+ const refConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ writeFileSync(
+ refConfigPath,
+ JSON.stringify({ stages: { [STAGE_KEY]: { name: STAGE_KEY, description: 'desc', model: 'default', returnsJson: true, variables: [] } } }, null, 2) + '\n',
+ );
+ }
+ };
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-135-'));
+ stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ refStagesDir = join(rootDir, 'data.reference', 'prompts', 'stages');
+ installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ mkdirSync(stagesDir, { recursive: true });
+ mkdirSync(refStagesDir, { recursive: true });
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ });
+
+ it('seeds the .md template and merges the stage-config entry on a fresh install', async () => {
+ seedReference();
+ await expect(migration.up({ rootDir })).resolves.not.toThrow();
+ expect(readFileSync(join(stagesDir, FILENAME), 'utf8')).toBe(BODY);
+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));
+ expect(installed.stages[STAGE_KEY]).toMatchObject({ returnsJson: true });
+ });
+
+ it('is idempotent and never clobbers a customized .md or an existing stage-config entry', async () => {
+ seedReference();
+ const customBody = '# CUSTOMIZED — do not overwrite\n';
+ writeFileSync(join(stagesDir, FILENAME), customBody);
+ writeFileSync(
+ installedConfigPath,
+ JSON.stringify({ stages: { [STAGE_KEY]: { name: 'user-tuned', model: 'custom' } } }, null, 2) + '\n',
+ );
+
+ await migration.up({ rootDir });
+
+ expect(readFileSync(join(stagesDir, FILENAME), 'utf8')).toBe(customBody);
+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));
+ expect(installed.stages[STAGE_KEY]).toEqual({ name: 'user-tuned', model: 'custom' });
+ });
+
+ it('does not throw when the data.reference samples are missing', async () => {
+ await expect(migration.up({ rootDir })).resolves.not.toThrow();
+ expect(existsSync(join(stagesDir, FILENAME))).toBe(false);
+ });
+
+ it('matches the live shipped stage-config key + prompt file (drift catch)', () => {
+ const refConfig = JSON.parse(
+ readFileSync(join(repoRoot, 'data.reference', 'prompts', 'stage-config.json'), 'utf8'),
+ );
+ expect(refConfig.stages[STAGE_KEY], `stage-config missing ${STAGE_KEY}`).toBeTruthy();
+ expect(refConfig.stages[STAGE_KEY].returnsJson).toBe(true);
+ expect(existsSync(join(repoRoot, 'data.reference', 'prompts', 'stages', FILENAME))).toBe(true);
+ });
+});
diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.md
index e8fe81027d..d8786a721f 100644
--- a/server/lib/editorial/README.md
+++ b/server/lib/editorial/README.md
@@ -120,7 +120,13 @@ when present, else the generated `stages.comicScript.output` (derived from the
already-loaded `ctx.issues`, no extra fetch). The `comic.lettering-density` check
reads the same content (via the shared `comicLetteringIssues`) to count
balloon/panel/page word load, so a finding stales exactly when the comic text the
-check read changes — not when an unrelated image renders. When a new check reads a
+check read changes — not when an unrelated image renders. The LLM check
+`comic.prose-sync` (#1589) is the CROSS-MEDIA sibling: for a hybrid comic+prose
+issue it pairs that issue's prose (a `manuscript` section, via `needsManuscript`)
+with its comic content (`comicScript.pacing`) and flags substantive divergences —
+an unshown beat, contradicted dialogue, or a chronology disagreement — making one
+model call per hybrid issue and fingerprinting both the prose and the comic so a
+finding stales when either drifts. When a new check reads a
`ctx.series` field (or another artifact) that isn't yet a token, add the token to
`EDITORIAL_SOURCES` and a matching resolver in the runner's `SOURCE_RESOLVERS`.
diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.js
index 72c11d93b6..4eec0a0004 100644
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@ -707,6 +707,19 @@ export const EYELINE_MATCH_STAGE = 'pipeline-editorial-eyeline-match';
// matches characters by name but never diffs their free-text descriptions).
export const APPEARANCE_CONTINUITY_STAGE = 'pipeline-editorial-appearance-continuity';
+// Stage name for the comic ↔ prose synchronization LLM check (#1589). Ships in
+// data.reference/prompts/stages/ + stage-config.json (fresh installs via
+// setup-data.js) and migrates to existing installs via migration 135 (boot runs
+// migrations but NOT setup-data, so the migration is required). For a hybrid
+// comic+prose issue it pairs the issue's PROSE (a manuscript section) with its
+// authoritative COMIC content (description + dialogue + caption + SFX — the same
+// fields the `comicScript.pacing` source carries) and asks the model to flag
+// SUBSTANTIVE cross-media divergences: a plot beat the prose narrates that no
+// panel shows, panel dialogue that contradicts the prose, or a chronology
+// disagreement across the two media. Comics legitimately compress and cut, so the
+// prompt is tuned to ignore ordinary medium-translation trims.
+export const COMIC_PROSE_SYNC_STAGE = 'pipeline-editorial-comic-prose-sync';
+
// Render the canon roster's names + aliases (#1412) into a compact text block the
// unmodeled-names check passes alongside the manuscript, so the model knows which
// proper nouns are ALREADY modeled (and therefore must NOT be flagged) and only
@@ -1965,6 +1978,88 @@ function balloonAttributionFinding(v, number) {
};
}
+// ---------------------------------------------------------------------------
+// Comic ↔ prose synchronization helpers (#1589). The cross-media check pairs each
+// hybrid issue's PROSE (a manuscript section) with its authoritative COMIC content
+// and feeds the pair to the model. Pure + deterministic so they're unit-testable
+// in isolation (the LLM caller is injected via ctx.callStagedLLM).
+// ---------------------------------------------------------------------------
+
+// Per-issue prose ceiling fed to the comic↔prose check (#1589) — so a long
+// chapter can't blow a small/local provider's window. Unlike the manuscript-
+// corpus checks (which chunk the whole series), this check makes ONE call per
+// hybrid issue with that issue's prose + comic, so the bound is per-issue. The
+// comic content is the smaller, authoritative anchor; the prose is sliced to this
+// ceiling and the prompt warns the model the prose may be truncated. ~24k chars
+// ≈ 6k tokens, which fits alongside the comic block on every supported provider.
+export const PROSE_SYNC_PROSE_CHAR_CAP = 24_000;
+
+// Per-issue prose keyed by issue number, from the collected manuscript sections
+// (`ctx.sections` — `collectManuscriptSections` emits ONE section per issue, see
+// arcPlanner/context.js). Skips sections with no usable number or empty content.
+export function proseByIssueNumber(sections) {
+ const map = new Map();
+ for (const s of (Array.isArray(sections) ? sections : [])) {
+ if (!Number.isInteger(s?.number)) continue;
+ const content = typeof s?.content === 'string' ? s.content : '';
+ if (content.trim()) map.set(s.number, content);
+ }
+ return map;
+}
+
+// Render an issue's parsed comic pages into a compact, model-readable block —
+// page/panel headers plus each panel's visual DESCRIPTION (what the panel SHOWS),
+// DIALOGUE (`speaker: line`), CAPTION, and SFX — so the model can compare what the
+// comic shows and says against the prose. Mirrors the field set in
+// `projectComicPacingContent` (the `comicScript.pacing` source this check
+// fingerprints), so the rendered content matches what staleness tracks. Returns ''
+// when no panel carries any content.
+export function renderComicForProseSync(pages) {
+ const lines = [];
+ (Array.isArray(pages) ? pages : []).forEach((p, pageIdx) => {
+ const panels = Array.isArray(p?.panels) ? p.panels : [];
+ panels.forEach((panel, panelIdx) => {
+ const block = [];
+ const desc = typeof panel?.description === 'string' ? panel.description.trim() : '';
+ if (desc) block.push(` Shows: ${desc}`);
+ for (const d of (Array.isArray(panel?.dialogue) ? panel.dialogue : [])) {
+ const speaker = typeof d?.speaker === 'string' ? d.speaker.trim() : '';
+ const line = typeof d?.line === 'string' ? d.line.trim() : '';
+ if (line) block.push(` ${speaker ? `${speaker}: ` : ''}${line}`);
+ }
+ const caption = typeof panel?.caption === 'string' ? panel.caption.trim() : '';
+ if (caption) block.push(` Caption: ${caption}`);
+ const sfx = typeof panel?.sfx === 'string' ? panel.sfx.trim() : '';
+ if (sfx) block.push(` SFX: ${sfx}`);
+ // Skip an entirely empty panel — no content to cross-check against prose.
+ if (block.length) {
+ lines.push(`Page ${pageIdx + 1} · Panel ${panelIdx + 1}`, ...block);
+ }
+ });
+ });
+ return lines.join('\n');
+}
+
+// The issues that have BOTH drafted prose AND comic content — the comparable set
+// for the comic↔prose sync check. Returns `[{ number, prose, comic }]` sorted by
+// issue number (`comicLetteringIssues` already sorts), prose sliced to
+// PROSE_SYNC_PROSE_CHAR_CAP. An issue with comic but no prose (or prose but no
+// comic) has nothing to cross-check and is skipped. Pure: reads ctx.issues +
+// ctx.sections only.
+export function proseSyncPairs(ctx) {
+ const proseByIssue = proseByIssueNumber(ctx?.sections);
+ const pairs = [];
+ for (const { number, pages } of comicLetteringIssues(ctx?.issues)) {
+ if (!Number.isInteger(number)) continue;
+ const prose = proseByIssue.get(number);
+ if (!prose) continue;
+ const comic = renderComicForProseSync(pages);
+ if (!comic.trim()) continue;
+ pairs.push({ number, prose: prose.slice(0, PROSE_SYNC_PROSE_CHAR_CAP), comic });
+ }
+ return pairs;
+}
+
export const EDITORIAL_CHECKS = [
{
id: 'naming.dissimilar-names',
@@ -2498,6 +2593,85 @@ export const EDITORIAL_CHECKS = [
return findings;
},
},
+ {
+ id: 'comic.prose-sync',
+ // Reads each issue's PROSE (manuscript sections, via needsManuscript) and its
+ // authoritative COMIC content (`comicScript.pacing` — description + dialogue +
+ // caption + SFX). Fingerprints BOTH so a finding stales when either the prose
+ // or the comic for that issue drifts. comicScript.pacing also makes the runner
+ // fetch the per-issue `issues` this check parses for comic pages.
+ sources: ['manuscript', 'comicScript.pacing'],
+ label: 'Comic ↔ prose synchronization (hybrid issues)',
+ description:
+ 'LLM cross-media check for hybrid comic+prose issues: pairs each issue\'s prose narration with its authoritative comic pages and flags SUBSTANTIVE divergences — a plot beat the prose narrates that no panel shows, panel dialogue that contradicts the prose (different words or a different speaker), or a chronology disagreement (events ordered differently across the two media). Comics legitimately compress and cut, so it flags only material mismatches, not ordinary medium-translation trims. Runs one model call per issue that has both prose and comic content, anchoring every finding to its issue.',
+ scope: 'issue',
+ kind: 'llm',
+ category: 'continuity',
+ severityDefault: 'medium',
+ defaultEnabled: true,
+ // Pairs each issue's comic with its prose section, so the manuscript sections
+ // must be collected (the runner only pays that I/O when a needsManuscript check
+ // is enabled).
+ needsManuscript: true,
+ configSchema: z.object({
+ // Cap findings per issue so a long issue can't flood the review.
+ maxFindings: z.number().int().min(1).max(50).default(12),
+ // Cap how many hybrid issues are cross-checked per run (one LLM call each),
+ // so a long series can't fan out into an unbounded number of calls. 0 = no cap.
+ maxIssues: z.number().int().min(0).max(500).default(40),
+ }),
+ configFields: [
+ {
+ key: 'maxFindings',
+ label: 'Max findings per issue',
+ type: 'number',
+ min: 1,
+ max: 50,
+ step: 1,
+ help: 'Cap findings per issue so a long issue can not flood the review.',
+ },
+ {
+ key: 'maxIssues',
+ label: 'Max issues cross-checked per run',
+ type: 'number',
+ min: 0,
+ max: 500,
+ step: 1,
+ help: 'Cap how many hybrid issues are compared per run (one model call each). 0 disables the cap.',
+ },
+ ],
+ // Skip the LLM entirely unless at least one issue has BOTH prose and comic
+ // content to cross-check.
+ gate: (ctx) => proseSyncPairs(ctx).length > 0,
+ run: async (ctx) => {
+ const pairs = proseSyncPairs(ctx);
+ if (!pairs.length) return [];
+ const maxIssues = ctx.config?.maxIssues ?? 40;
+ const scanned = maxIssues > 0 ? pairs.slice(0, maxIssues) : pairs;
+ const maxFindings = ctx.config?.maxFindings ?? 12;
+ const findings = [];
+ for (const { number, prose, comic } of scanned) {
+ // The runner only checks the abort signal before/after each check.run, so a
+ // multi-issue loop honors it between issues to stop launching further calls.
+ if (ctx.signal?.aborted) break;
+ const { content } = await ctx.callStagedLLM(
+ COMIC_PROSE_SYNC_STAGE,
+ { issueNumber: number, prose, comic },
+ { returnsJson: true, source: COMIC_PROSE_SYNC_STAGE },
+ );
+ // We KNOW which issue is under comparison, so force the issue anchor — a
+ // model that omits or garbles issueNumber still attributes correctly.
+ const mapped = mapLlmFindings(content?.findings, {
+ severityDefault: ctx.severityDefault,
+ category: 'continuity',
+ max: maxFindings,
+ withIssueNumber: true,
+ }).map((f) => ({ ...f, issueNumber: number }));
+ findings.push(...mapped);
+ }
+ return findings;
+ },
+ },
{
id: 'cast.representation-balance',
sources: ['manuscript', 'canon', 'reverseOutline'],
diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.js
index 339fcbc72b..2035fba2f6 100644
--- a/server/lib/editorial/checkRegistry.test.js
+++ b/server/lib/editorial/checkRegistry.test.js
@@ -41,6 +41,10 @@ import {
canonCharacterStatesSummary,
canonCharacterTraitsSummary,
continuityLedgerSummary,
+ proseByIssueNumber,
+ renderComicForProseSync,
+ proseSyncPairs,
+ PROSE_SYNC_PROSE_CHAR_CAP,
} from './checkRegistry.js';
const NAMING = 'naming.dissimilar-names';
@@ -3461,6 +3465,148 @@ describe('visual.appearance-continuity — LLM check (#1467)', () => {
});
});
+describe('comic.prose-sync — LLM cross-media check (#1589)', () => {
+ // An issue record whose comic content lives in the populated comicPages split.
+ const comicIssue = (number, panels) => ({
+ number,
+ stages: { comicPages: { pages: [{ panels }] } },
+ });
+ // A manuscript section as collectManuscriptSections emits it (one per issue).
+ const section = (number, content) => ({ id: `i${number}`, number, title: '', stageId: 'manuscript', content });
+
+ describe('pure helpers', () => {
+ it('proseByIssueNumber keys non-empty prose by issue number, skipping bad entries', () => {
+ const map = proseByIssueNumber([
+ section(3, 'Issue three prose.'),
+ section(4, ' '), // blank → skipped
+ { number: null, content: 'no number' }, // no number → skipped
+ section(5, 'Issue five prose.'),
+ ]);
+ expect([...map.keys()].sort()).toEqual([3, 5]);
+ expect(map.get(3)).toBe('Issue three prose.');
+ });
+
+ it('renderComicForProseSync emits page/panel headers + shows/dialogue/caption/sfx, skipping empty panels', () => {
+ const out = renderComicForProseSync([
+ { panels: [
+ { description: 'Anna draws the knife', dialogue: [{ speaker: 'ANNA', line: 'Stay back.' }], caption: 'Later', sfx: 'SHNK' },
+ { description: '', dialogue: [], caption: '', sfx: '' }, // empty → skipped
+ ] },
+ ]);
+ expect(out).toContain('Page 1 · Panel 1');
+ expect(out).toContain('Shows: Anna draws the knife');
+ expect(out).toContain('ANNA: Stay back.');
+ expect(out).toContain('Caption: Later');
+ expect(out).toContain('SFX: SHNK');
+ // The empty second panel produced no header.
+ expect(out).not.toContain('Panel 2');
+ });
+
+ it('proseSyncPairs joins only issues that have BOTH prose and comic, and caps prose length', () => {
+ const longProse = 'x'.repeat(PROSE_SYNC_PROSE_CHAR_CAP + 500);
+ const ctx = {
+ sections: [section(3, longProse), section(9, 'prose but no comic')],
+ issues: [
+ comicIssue(3, [{ description: 'a panel', dialogue: [], caption: '', sfx: '' }]),
+ comicIssue(7, [{ description: 'comic but no prose', dialogue: [], caption: '', sfx: '' }]),
+ ],
+ };
+ const pairs = proseSyncPairs(ctx);
+ expect(pairs.map((p) => p.number)).toEqual([3]); // only issue 3 has both
+ expect(pairs[0].prose).toHaveLength(PROSE_SYNC_PROSE_CHAR_CAP);
+ expect(pairs[0].comic).toContain('Shows: a panel');
+ });
+ });
+
+ it('gates true only when an issue has both prose and comic content', () => {
+ const check = getCheck('comic.prose-sync');
+ expect(check.gate({
+ sections: [section(3, 'prose')],
+ issues: [comicIssue(3, [{ description: 'panel', dialogue: [], caption: '', sfx: '' }])],
+ })).toBe(true);
+ // Comic but no prose → nothing to cross-check.
+ expect(check.gate({
+ sections: [],
+ issues: [comicIssue(3, [{ description: 'panel', dialogue: [], caption: '', sfx: '' }])],
+ })).toBe(false);
+ expect(check.gate({ sections: [], issues: [] })).toBe(false);
+ });
+
+ it('makes one model call per hybrid issue and forces the issue anchor on findings', async () => {
+ const seen = [];
+ const findings = await getCheck('comic.prose-sync').run({
+ sections: [section(3, 'Anna is stabbed and falls.'), section(4, 'A quiet morning.')],
+ issues: [
+ comicIssue(3, [{ description: 'Anna stands, unharmed', dialogue: [], caption: '', sfx: '' }]),
+ comicIssue(4, [{ description: 'morning kitchen', dialogue: [], caption: '', sfx: '' }]),
+ ],
+ config: { maxFindings: 12, maxIssues: 40 },
+ severityDefault: 'medium',
+ callStagedLLM: async (_stage, vars) => {
+ seen.push(vars);
+ // Model reports a mismatch only for the issue whose number it sees as 3,
+ // and deliberately omits issueNumber to prove the check forces it.
+ return vars.issueNumber === 3
+ ? { content: { findings: [{ severity: 'medium', location: 'Issue 3 — unshown beat', problem: 'Prose stabs Anna; no panel shows it.', suggestion: 'Add a panel.', anchorQuote: 'Anna is stabbed' }] } }
+ : { content: { findings: [] } };
+ },
+ });
+ // One call per hybrid issue.
+ expect(seen.map((v) => v.issueNumber).sort()).toEqual([3, 4]);
+ expect(seen[0]).toHaveProperty('prose');
+ expect(seen[0]).toHaveProperty('comic');
+ expect(findings).toHaveLength(1);
+ expect(findings[0].category).toBe('continuity');
+ expect(findings[0].issueNumber).toBe(3); // forced from the pair, not the model
+ });
+
+ it('respects maxIssues (caps the number of model calls)', async () => {
+ let calls = 0;
+ await getCheck('comic.prose-sync').run({
+ sections: [section(3, 'p3'), section(4, 'p4'), section(5, 'p5')],
+ issues: [
+ comicIssue(3, [{ description: 'd3', dialogue: [], caption: '', sfx: '' }]),
+ comicIssue(4, [{ description: 'd4', dialogue: [], caption: '', sfx: '' }]),
+ comicIssue(5, [{ description: 'd5', dialogue: [], caption: '', sfx: '' }]),
+ ],
+ config: { maxIssues: 2 },
+ severityDefault: 'medium',
+ callStagedLLM: async () => { calls += 1; return { content: { findings: [] } }; },
+ });
+ expect(calls).toBe(2);
+ });
+
+ it('stops launching further calls once the abort signal trips', async () => {
+ let calls = 0;
+ const signal = { aborted: false };
+ await getCheck('comic.prose-sync').run({
+ sections: [section(3, 'p3'), section(4, 'p4')],
+ issues: [
+ comicIssue(3, [{ description: 'd3', dialogue: [], caption: '', sfx: '' }]),
+ comicIssue(4, [{ description: 'd4', dialogue: [], caption: '', sfx: '' }]),
+ ],
+ config: {},
+ severityDefault: 'medium',
+ signal,
+ callStagedLLM: async () => { calls += 1; signal.aborted = true; return { content: { findings: [] } }; },
+ });
+ expect(calls).toBe(1); // second issue skipped after the signal tripped
+ });
+
+ it('returns no findings (and never calls the model) when no issue is hybrid', async () => {
+ let called = false;
+ const findings = await getCheck('comic.prose-sync').run({
+ sections: [section(3, 'prose only')],
+ issues: [], // no comic content anywhere
+ config: {},
+ severityDefault: 'medium',
+ callStagedLLM: async () => { called = true; return { content: { findings: [] } }; },
+ });
+ expect(findings).toEqual([]);
+ expect(called).toBe(false);
+ });
+});
+
describe('style.reading-level — deterministic check (#1303)', () => {
const check = getCheck('style.reading-level');
const run = (styleGuide, manuscript, config = {}) =>