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([issue-1314]): editorial checks for comic pacing — splash usage, panel rhythm, page-turn beats

Adam Eivy26e055e05486
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 787d916b0f..f74babffe0 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **[issue-1314] Editorial checks for comic pacing — splash usage, panel rhythm, and page-turn beat placement.** Two new checks (Create → Editorial Checks) read each issue's parsed comic script (page → panel breakdown), not the prose manuscript. **Comic panel rhythm & splash usage** is deterministic: it flags **splash overuse** (too high a share of full-page splashes), **back-to-back splash runs** (consecutive full-page splashes that read as a slideshow and burn the page budget), **overcrowded pages** (too many panels cramped onto one page), and **grid monotony** (the same multi-panel count repeated page after page) — all threshold-configurable (max panels/page, splash-overuse ratio, monotony run length). **Comic page-turn beat placement** is LLM-judged: because a printed comic is read in two-page spreads, a reveal or cliffhanger on a page the reader has already been looking at across the open spread is spoiled before they reach it — a big reveal should land on the *first page after a page turn*. It reads each issue's recto/verso spread layout and flags reveals exposed early, reconciling against the authored reader-map reveals/cliffhangers and suggesting which panel to move. The runner parses each issue's stored comic script into pages only when a comic-pacing check is enabled (no extra I/O otherwise), and fingerprints the parsed layout for finding staleness so a comic-script edit re-stales the findings while a prose-only edit doesn't. The pure scanners live in `server/lib/editorial/comicPacing.js` (no new deps); the page-turn stage prompt (`pipeline-editorial-comic-page-turn`) migrates for existing installs (114). (`server/lib/editorial/{comicPacing,checkRegistry}.js`, `server/services/pipeline/editorial/checkRunner.js`, `scripts/migrations/114-editorial-comic-page-turn-stage.js`, #1314)
+
- **[issue-1310] Editorial check flags plot-structure & momentum problems — passive protagonist, deus ex machina, idiot plot, flat stakes, sagging middle, dropped subplots.** A new **Plot structure & momentum** check (Create → Editorial Checks) reads your drafted manuscript and surfaces the macro pathologies a developmental editor flags at the arc level: a **passive protagonist** (events happen *to* them instead of being driven by their choices), a **deus ex machina / convenient coincidence** that resolves a problem by luck rather than setup, an **idiot plot** that only holds together because someone won't say the obvious, **flat or unclear stakes** that never escalate, a **sagging middle** with no try-fail rhythm, and **dropped subplots** — threads that open and then fizzle. It reconciles dropped threads against your reverse-outline plotline tags and your authored reader-map hooks/payoffs, and defers whole-arc judgments (a sagging middle, a never-resolved thread) until it has seen the whole manuscript so a long book reviewed in chunks isn't false-flagged. Findings render as `Plot structure` notes in the manuscript editor, anchored to the issue and (where one exists) a verbatim quote. Ships a new stage prompt (`pipeline-editorial-plot-structure`) that migrates for existing installs (111). (#1310)
- **[issue-1311] Editorial check flags head-hopping / POV-discipline breaks within a scene.** A new **Head-hopping / POV discipline** LLM check (Create → Editorial Checks) polices viewpoint discipline in limited-POV prose — distinct from the existing **POV justification** check (#1295, which asks whether each viewpoint *character* earns an arc). For each limited-POV scene it flags narration that enters another character's head (reports interior thoughts/feelings the POV character can't know), reports knowledge or perception the POV character couldn't have (offstage events, things behind them), or switches POV mid-scene with no break — and suggests re-anchoring to the POV character's perception or inserting a proper scene break. It reads your reverse-outline scene segmentation as context (each scene's anchored POV character + the other characters on-stage, the candidate heads a hop slips into) and **degrades gracefully** to a whole-issue manuscript scan when no outline exists yet. It **no-ops when the series style guide sets third-person omniscient** — there the roaming viewpoint is intentional — and surfaces the configured POV person (first / third-limited / second) to the model so it judges against the discipline actually in force. Each finding anchors a verbatim quote + issue number and names whose head was entered. Ships a new stage prompt (`pipeline-editorial-head-hopping`) that migrates for existing installs (112). (`server/lib/editorial/checkRegistry.js`, `scripts/migrations/112-editorial-head-hopping-stage.js`, #1311)
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index 11f727e78d..31ed14633d 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -499,6 +499,13 @@
"returnsJson": true,
"variables": []
},
+ "pipeline-editorial-comic-page-turn": {
+ "name": "Pipeline — Editorial Check: Comic page-turn beats",
+ "description": "Editorial check (#1314): flags comic reveals/cliffhangers placed where the reader sees them early — on a page that shares its two-page spread with earlier pages rather than the first page after a page turn. Reads each issue's parsed comic-page layout and reconciles placement against the authored reader-map reveals/cliffhangers. Returns issue-anchored findings.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
+ },
"pipeline-editorial-dead-metaphor": {
"name": "Pipeline — Editorial Check: Dead / mixed metaphor & overwriting",
"description": "Editorial check (#1308): the judgment layer for tired language the deterministic cliché scan can't catch — dead or mixed metaphors, lightly-reworded novel clichés, and overwrought / purple prose. Reads the stitched manuscript; severity is advisory; skips knowing in-voice clichés. Returns issue-anchored findings.",
diff --git a/data.reference/prompts/stages/pipeline-editorial-comic-page-turn.md b/data.reference/prompts/stages/pipeline-editorial-comic-page-turn.md
new file mode 100644
index 0000000000..02c6bcbe8c
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-editorial-comic-page-turn.md
@@ -0,0 +1,89 @@
+# Pipeline — Editorial Check: Comic page-turn beats
+
+You are a comics editor doing a single focused pass for ONE problem:
+**page-turn beat placement** in a comic issue.
+
+## The rule
+
+A printed comic is read in two-page **spreads**: when the book is open the reader
+sees a left-hand (verso, even) page and a right-hand (recto, odd) page *at the same
+time*. Turning the page reveals the **next** spread all at once — so the first page
+of a spread is the only page the reader has NOT already seen across the open book.
+
+Because of this, a big **reveal** or **cliffhanger** should land on the **first page
+after a page turn** (the start of the next spread), where the surprise stays hidden
+until the reader commits to the turn. A reveal placed on a page that shares its
+spread with earlier pages is **spoiled early** — the reader's eye catches it before
+they finish the prior page.
+
+## What to flag
+
+For each page layout below, judge whether a reveal/surprise/cliffhanger beat is
+placed where the reader can see it too early:
+
+- **Spoiled reveal** — a panel that reads as a reveal, twist, shock, or cliffhanger
+ sits on a page that is NOT the first page after a turn (i.e. `beginsSpread` is
+ false), so it's visible across the open spread before the reader reaches it.
+- **Wasted page turn** — the first page after a turn (a reveal-safe slot) is spent on
+ a low-impact, no-surprise beat while a reveal elsewhere in the same stretch is
+ exposed early.
+
+Flag the beat, name the page it's on, and suggest moving the reveal panel to the next
+reveal-safe page (the start of the following spread) — or restructuring the pages so
+the reveal lands after a turn.
+
+Severity: a minor beat exposed a beat early is **low**; a central twist or
+end-of-issue cliffhanger the reader can see across the spread before reaching it is
+**medium**.
+
+Do NOT flag:
+
+- A reveal that already lands on a `first page after a turn (reveal-safe)` page.
+- An ordinary story beat with no surprise/reveal/cliffhanger to protect — page-turn
+ placement only matters for beats whose impact depends on being hidden.
+- Page 1 — it opens the issue and has no prior spread to be spoiled against.
+
+{{#authoredReveals}}
+## Reveals & cliffhangers the writer has already planned
+
+The writer logged these in the series reader-map. Use them to recognize WHICH beats
+are the big reveals/cliffhangers that need a protected page turn — reconcile the
+layout against them. Judge from the layout, not the list alone; do not invent
+findings just to match it.
+
+```
+{{authoredReveals}}
+```
+{{/authoredReveals}}
+
+## Page layout
+
+Each page is listed with its side (recto/verso), spread number, whether it is the
+first page after a turn (reveal-safe), its panel breakdown, and a short digest of
+each panel. Use the page number to attribute every finding.
+
+```
+{{pageLayout}}
+```
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no
+commentary:
+
+```json
+{
+ "findings": [
+ {
+ "severity": "high|medium|low",
+ "location": "string — where (e.g. 'Page 4')",
+ "problem": "1–3 sentences naming the reveal/cliffhanger beat and how its page placement exposes it early",
+ "suggestion": "1–3 sentences on which page (the next reveal-safe page after a turn) to move the beat to, or how to restructure",
+ "anchorQuote": "short verbatim fragment of the panel description for the exposed beat (≤ 200 chars)"
+ }
+ ]
+}
+```
+
+If every reveal already lands on a reveal-safe page, return an empty `findings`
+array — do not invent issues.
diff --git a/scripts/migrations/114-editorial-comic-page-turn-stage.js b/scripts/migrations/114-editorial-comic-page-turn-stage.js
new file mode 100644
index 0000000000..d732a39b7d
--- /dev/null
+++ b/scripts/migrations/114-editorial-comic-page-turn-stage.js
@@ -0,0 +1,79 @@
+/**
+ * Seed the `pipeline-editorial-comic-page-turn` stage into existing installs (#1314).
+ *
+ * Mirrors `113-editorial-voice-distinctiveness-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-page-turn stage unseeded and the
+ * `comic.page-turn-beats` editorial check would throw "Stage not found" the first
+ * time it runs.
+ *
+ * First-shipment seed (no MD5 bookkeeping). Any FUTURE edit to this `.md` MUST add
+ * an `ACCEPTED_OLD_MD5`/`NEW_SHIPPED_MD5` pair (migration 003 pattern) so
+ * `setup-data.js#buildPromptDriftTables` can auto-upgrade other installs.
+ */
+
+import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';
+import { dirname, join } from 'path';
+
+const FILENAME = 'pipeline-editorial-comic-page-turn.md';
+const STAGE_KEY = 'pipeline-editorial-comic-page-turn';
+
+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-page-turn prompt: already present`);
+ } else {
+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
+ if (!sampleExists) {
+ console.warn(`⚠️ pipeline-editorial-comic-page-turn: sample missing for ${FILENAME} — skipping copy`);
+ } else {
+ try {
+ await copyFile(samplePath, dataPath);
+ console.log(`✅ seeded ${FILENAME}`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-editorial-comic-page-turn: 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-page-turn: 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-page-turn stage-config: already present`);
+ return;
+ }
+ if (!sample?.stages?.[STAGE_KEY]) {
+ console.warn(`⚠️ pipeline-editorial-comic-page-turn: 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-page-turn stage-config (${action}): 1 added`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-editorial-comic-page-turn: stage-config merge failed: ${err.message}`);
+ }
+ },
+};
diff --git a/scripts/migrations/114-editorial-comic-page-turn-stage.test.js b/scripts/migrations/114-editorial-comic-page-turn-stage.test.js
new file mode 100644
index 0000000000..50c94686c4
--- /dev/null
+++ b/scripts/migrations/114-editorial-comic-page-turn-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 './114-editorial-comic-page-turn-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 110–113) — no MD5 bookkeeping, so the
+// seed / no-clobber behavior is asserted directly.
+
+const FILENAME = 'pipeline-editorial-comic-page-turn.md';
+const STAGE_KEY = 'pipeline-editorial-comic-page-turn';
+const BODY = '# Comic page-turn beats\n\nshipped body\n';
+
+describe('migration 114 — seed editorial-comic-page-turn 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-114-'));
+ 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 a18c11ee75..d9ec388c0b 100644
--- a/server/lib/editorial/README.md
+++ b/server/lib/editorial/README.md
@@ -103,5 +103,6 @@ runner-injected `ctx.callInlineLLM` (an inline-prompt sibling of
| `italicThoughts.js` | Pure, dependency-free italic-thought primitive for `prose.italic-thoughts` (#1300): `findItalicThoughts` (multi-word markdown `*…*` / `_…_` italic runs, dedup + word-count threshold so single-word emphasis, bold, and `snake_case` are skipped). The LLM siblings (`opening.wrong-start`, `prose.mirror-description`, `dialogue.pleasantries`, `prose.kill-your-darlings`) handle the judgment cases in the #1300 anti-pattern bundle. |
| `proseTics.js` | Pure, dependency-free copy-edit prose-tic primitives for the #1306 line-edit group: `tokenizeWords` / `splitSentences` (shared tokenization), `findFilterWords` (`prose.filter-words`), `findCrutchWords` (`prose.crutch-words`), `findAdverbs` (`prose.adverbs` — `-ly` adverbs + dialogue-tag adverbs), `findPassiveVoice` (`prose.passive-voice` — be-verb + past-participle heuristic), `findGestures` (`prose.repeated-gestures` — gesture tally + body-part autonomy), plus the seed `FILTER_WORDS` / `CRUTCH_WORDS` / `GESTURE_WORDS` lists. The LLM sibling `prose.telling-emotion` handles the named-emotion judgment case. |
| `repetition.js` | Pure, dependency-free word-echo & rhythm primitives for #1306: `findWordEchoes` (`prose.word-echoes` — distinctive word repeated within a window), `findRepeatedOpeners` (runs of sentences sharing an opener, "He… He… He…"), and `measureSentenceRhythm` (`prose.sentence-rhythm` — sentence-length variation). Reuses `tokenizeWords` / `splitSentences` from `proseTics.js`. |
+| `comicPacing.js` | Pure, dependency-free comic-pacing primitives for the #1314 comic-pacing group: `isSplashPage`, `comicSpreadLayout` (recto/verso + spread + `beginsSpread` page-turn map), `summarizeComicPages`, `analyzePanelRhythm` (`comic.panel-rhythm` — splash overuse / back-to-back splashes / overcrowded pages / grid monotony), `comicPageTurnSummary` + `authoredRevealSummary` (LLM-context renderers for `comic.page-turn-beats`). Operates on already-parsed comic pages (the runner parses each issue's stored comic script and injects them as the `comicScript` source) so the editorial dir stays import-pure. |
| `dialogue.js` | Pure, dependency-free dialogue-tag primitives for the #1307 dialogue-craft group: `findSaidBookisms` (`dialogue.said-bookisms` — ornate speech tags like *expostulated*/*opined* and non-speech tags like "she smiled", matched only when adjacent to a double-quote span) and `findUnattributedDialogueRuns` (`dialogue.attribution-clarity` — runs of consecutive untagged/unbeated dialogue lines where the speaker can't be tracked), plus the seed `SAID_BOOKISMS` / `NON_SPEECH_TAGS` lists. The LLM siblings `dialogue.on-the-nose` (subtext-free / "as you know, Bob" dialogue) and `dialogue.voice-distinctiveness` (per-character voice against canon `speechPattern`/`speechAccent`) handle the judgment cases. |
| `index.js` | Barrel re-export of the above. |
diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.js
index 7fe547f60e..e64e846522 100644
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@ -43,6 +43,11 @@ import {
findRepeatedOpeners,
measureSentenceRhythm,
} from './repetition.js';
+import {
+ analyzePanelRhythm,
+ comicPageTurnSummary,
+ authoredRevealSummary,
+} from './comicPacing.js';
export const CHECK_SCOPES = Object.freeze(['series', 'issue', 'scene', 'noun']);
export const CHECK_KINDS = Object.freeze(['deterministic', 'llm']);
@@ -86,6 +91,12 @@ const SEVERITIES = CHECK_SEVERITIES;
// want, need, startState, endState, transitions[] }`). The
// arc.transitions check reconciles detected change moments
// against these authored transitions + flat-arc warnings.
+// - 'comicScript' — the per-issue PARSED comic script (#1314): the runner parses
+// each issue's `stages.comicScript.output` with the (impure)
+// comicScriptParser and injects `ctx.comicScripts`
+// (`[{ issueNumber, pages }]`, only issues that parsed to ≥1
+// page). The comic-pacing checks read page/panel structure —
+// splash usage, panel rhythm, page-turn beat placement.
export const EDITORIAL_SOURCES = Object.freeze([
'manuscript',
'canon',
@@ -96,6 +107,7 @@ export const EDITORIAL_SOURCES = Object.freeze([
'reverseOutline.plotlines',
'editorialArcs',
'series.characterArcs',
+ 'comicScript',
]);
// Default per-run finding cap for user-defined checks (#1346) — mirrors the
@@ -283,6 +295,17 @@ export const PLOT_STRUCTURE_STAGE = 'pipeline-editorial-plot-structure';
// character's head or reports what the POV character can't perceive.
export const HEAD_HOPPING_STAGE = 'pipeline-editorial-head-hopping';
+// Stage name for the comic page-turn-beats LLM check (#1314). Ships in
+// data.reference/prompts/stages/ + stage-config.json (fresh installs via
+// setup-data.js) and migrates to existing installs via migration 114 (boot runs
+// migrations but NOT setup-data, so the migration is required). Reads each issue's
+// parsed comic-page layout (`comicPageTurnSummary`) plus the authored reveals /
+// cliffhangers (`authoredRevealSummary`) and flags big reveals placed where the
+// reader sees them early (a page the reader has already been looking at across the
+// spread, rather than the first page after a turn). The deterministic sibling
+// (comic.panel-rhythm) needs no stage.
+export const COMIC_PAGE_TURN_STAGE = 'pipeline-editorial-comic-page-turn';
+
// Render the authored reader-map cliffhangers (#1298) into a compact text block
// the chapter-ending check passes alongside the manuscript so the model
// reconciles its DETECTED endings against the issue-boundary tugs the writer
@@ -3668,6 +3691,133 @@ export const EDITORIAL_CHECKS = [
return findings;
},
},
+ {
+ id: 'comic.panel-rhythm',
+ sources: ['comicScript'],
+ label: 'Comic panel rhythm & splash usage',
+ description:
+ 'Deterministic scan of each issue\'s parsed comic-page layout for reading-rhythm problems: splash-page overuse (too high a share of full-page splashes), back-to-back splashes that blow the page budget, overcrowded pages that cram too many beats, and monotonous grids (the same multi-panel count repeated page after page). Reads the parsed comic script (page → panel breakdown), not the prose manuscript.',
+ scope: 'issue',
+ kind: 'deterministic',
+ category: 'pacing',
+ severityDefault: 'low',
+ defaultEnabled: true,
+ configSchema: z.object({
+ // Panels above this on one page reads as overcrowded / decompression-killing.
+ maxPanelsPerPage: z.number().int().min(2).max(20).default(9),
+ // Share of full-page splashes at/above which (with >1 splash) splash overuse fires.
+ splashRatioWarn: z.number().min(0.05).max(1).default(0.25),
+ // Identical multi-panel count repeated for this many pages reads as grid monotony.
+ monotonyRunLength: z.number().int().min(2).max(12).default(4),
+ // Cap findings per run so a long run of issues can't flood the review.
+ maxFindings: z.number().int().min(1).max(50).default(20),
+ }),
+ configFields: [
+ { key: 'maxPanelsPerPage', label: 'Max panels per page', type: 'number', min: 2, max: 20, step: 1, help: 'Panels above this on one page reads as overcrowded — too many beats compressed onto a single page.' },
+ { key: 'splashRatioWarn', label: 'Splash overuse ratio', type: 'number', min: 0.05, max: 1, step: 0.05, help: 'Share of full-page splashes (with more than one splash) at/above which the issue is flagged for splash overuse.' },
+ { key: 'monotonyRunLength', label: 'Grid monotony run length', type: 'number', min: 2, max: 12, step: 1, help: 'The same multi-panel page count repeated for this many pages in a row reads as a monotonous grid.' },
+ { key: 'maxFindings', label: 'Max findings per run', type: 'number', min: 1, max: 50, step: 1, help: 'Cap findings so a long run of comic issues can not flood the review.' },
+ ],
+ // Needs at least one issue that parsed to comic pages — the runner only
+ // populates ctx.comicScripts when a comic-pacing check is enabled.
+ gate: (ctx) => Array.isArray(ctx.comicScripts) && ctx.comicScripts.length > 0,
+ run: (ctx) => {
+ const cfg = ctx.config || {};
+ const max = cfg.maxFindings ?? 20;
+ const rows = Array.isArray(ctx.comicScripts) ? ctx.comicScripts : [];
+ const findings = [];
+ for (const { issueNumber, pages } of rows) {
+ if (findings.length >= max) break;
+ const r = analyzePanelRhythm(pages, cfg);
+ const location = Number.isInteger(issueNumber) ? `Issue ${issueNumber}` : 'Comic script';
+ const issueNum = Number.isInteger(issueNumber) ? issueNumber : null;
+ const push = (severity, problem, suggestion) => {
+ if (findings.length >= max) return;
+ findings.push({ severity, category: 'pacing', location, problem, suggestion, anchorQuote: '', issueNumber: issueNum });
+ };
+ if (r.splashOveruse) {
+ push(
+ ctx.severityDefault,
+ `${r.splashPages.length} of ${r.totalPages} pages are full-page splashes (${Math.round(r.splashRatio * 100)}%, pages ${r.splashPages.join(', ')}) — splashes spent this freely lose their impact and burn the page budget on low-movement beats.`,
+ 'Reserve splash pages for the issue\'s biggest reveals or establishing shots; break the rest into multi-panel pages so each splash lands.',
+ );
+ }
+ for (const run of r.backToBackSplashes) {
+ push(
+ ctx.severityDefault,
+ `Pages ${run.startPage}–${run.endPage} are ${run.length} splash pages in a row — consecutive full-page splashes read as a slideshow and spend the page count fast.`,
+ 'Intercut multi-panel pages between the splashes, or collapse the run to the single strongest splash.',
+ );
+ }
+ for (const page of r.overcrowded) {
+ push(
+ ctx.severityDefault,
+ `Page ${page.pageNumber} has ${page.panelCount} panels — past roughly ${cfg.maxPanelsPerPage ?? 9} panels a page cramps each beat and the art has no room to breathe.`,
+ 'Split the page in two or cut the lowest-value panels so the key beats get space.',
+ );
+ }
+ for (const run of r.monotonyRuns) {
+ push(
+ ctx.severityDefault,
+ `Pages ${run.startPage}–${run.endPage} all use the same ${run.panelCount}-panel grid (${run.length} pages running) — an unvarying grid flattens the reading rhythm.`,
+ 'Vary the panel count — open up a beat with fewer, larger panels or compress a fast exchange — so the page rhythm tracks the story\'s.',
+ );
+ }
+ }
+ return findings;
+ },
+ },
+ {
+ id: 'comic.page-turn-beats',
+ sources: ['comicScript', 'series.arc.readerMap'],
+ label: 'Comic page-turn beat placement (LLM)',
+ description:
+ 'LLM scan of each issue\'s comic-page layout for reveals and cliffhangers placed where the reader can see them early. On a two-page spread both pages are visible at once, so a surprise on a page the reader has already been looking at is spoiled before they reach it — a big reveal should land on the first page after a page turn (the start of the next spread). Reconciles the placement against the authored reader-map reveals/cliffhangers and suggests which panel to move.',
+ scope: 'issue',
+ kind: 'llm',
+ category: 'pacing',
+ severityDefault: 'low',
+ defaultEnabled: true,
+ configSchema: z.object({
+ // Cap findings per run so a long run of issues can't flood the review.
+ maxFindings: z.number().int().min(1).max(50).default(12),
+ }),
+ configFields: [
+ { key: 'maxFindings', label: 'Max findings per run', type: 'number', min: 1, max: 50, step: 1, help: 'Cap findings so a long run of comic issues can not flood the review.' },
+ ],
+ // Needs at least one issue that parsed to comic pages.
+ gate: (ctx) => Array.isArray(ctx.comicScripts) && ctx.comicScripts.length > 0,
+ run: async (ctx) => {
+ const max = ctx.config?.maxFindings ?? 12;
+ // Authored reveals/cliffhangers are pure series-level context the model
+ // reconciles each issue's placement against; '' when nothing is authored.
+ const authoredReveals = authoredRevealSummary(ctx.series?.arc?.readerMap);
+ const rows = Array.isArray(ctx.comicScripts) ? ctx.comicScripts : [];
+ const findings = [];
+ for (const { issueNumber, pages } of rows) {
+ if (ctx.signal?.aborted || findings.length >= max) break;
+ const pageLayout = comicPageTurnSummary(pages, issueNumber);
+ if (!pageLayout) continue;
+ const { content } = await ctx.callStagedLLM(
+ COMIC_PAGE_TURN_STAGE,
+ { pageLayout, authoredReveals },
+ { returnsJson: true, source: COMIC_PAGE_TURN_STAGE },
+ );
+ const issueNum = Number.isInteger(issueNumber) ? issueNumber : null;
+ const mapped = mapLlmFindings(content?.findings, {
+ severityDefault: ctx.severityDefault,
+ category: 'pacing',
+ max: max - findings.length,
+ withIssueNumber: false,
+ });
+ // The page-turn check runs per-issue, so attribute every finding to the
+ // issue whose layout the model just read (the prompt has no issue header
+ // for the model to echo back like the manuscript checks do).
+ for (const f of mapped) findings.push({ ...f, issueNumber: issueNum });
+ }
+ return findings;
+ },
+ },
];
// ---------------------------------------------------------------------------
diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.js
index 1686d887ea..47466b2f07 100644
--- a/server/lib/editorial/checkRegistry.test.js
+++ b/server/lib/editorial/checkRegistry.test.js
@@ -2978,3 +2978,111 @@ describe('dialogue-craft bundle (#1307)', () => {
});
});
});
+
+describe('comic-pacing bundle (#1314)', () => {
+ const PANEL_RHYTHM = 'comic.panel-rhythm';
+ const PAGE_TURN = 'comic.page-turn-beats';
+ // A parsed comic page is `{ panels: [...] }`; build pages by panel count.
+ const page = (n) => ({ panels: Array.from({ length: n }, (_, i) => ({ description: `p${i}`, caption: '', dialogue: [], sfx: '' })) });
+ const issue = (number, counts) => ({ issueNumber: number, pages: counts.map(page) });
+
+ describe('comic.panel-rhythm — deterministic', () => {
+ it('is registered as an issue-scoped deterministic pacing check over comicScript', () => {
+ const check = getCheck(PANEL_RHYTHM);
+ expect(check.kind).toBe('deterministic');
+ expect(check.scope).toBe('issue');
+ expect(check.category).toBe('pacing');
+ expect(check.sources).toEqual(['comicScript']);
+ });
+
+ it('only runs when at least one issue parsed to comic pages', () => {
+ const check = getCheck(PANEL_RHYTHM);
+ expect(check.gate({ comicScripts: [] })).toBe(false);
+ expect(check.gate({ comicScripts: undefined })).toBe(false);
+ expect(check.gate({ comicScripts: [issue(1, [3])] })).toBe(true);
+ });
+
+ it('flags splash overuse, overcrowding, and grid monotony, attributing each to its issue', () => {
+ const ctx = {
+ config: {},
+ severityDefault: 'low',
+ comicScripts: [issue(3, [1, 1, 3, 12, 4, 4, 4, 4])],
+ };
+ const findings = getCheck(PANEL_RHYTHM).run(ctx);
+ expect(findings.length).toBeGreaterThan(0);
+ expect(findings.every((f) => f.category === 'pacing')).toBe(true);
+ expect(findings.every((f) => f.issueNumber === 3)).toBe(true);
+ const problems = findings.map((f) => f.problem).join('\n');
+ expect(problems).toContain('full-page splashes');
+ expect(problems).toContain('12 panels');
+ expect(problems).toMatch(/same 4-panel grid/);
+ });
+
+ it('honors maxFindings as a hard cap across issues', () => {
+ const ctx = {
+ config: { maxFindings: 1 },
+ severityDefault: 'low',
+ comicScripts: [issue(1, [1, 1, 1]), issue(2, [12, 12])],
+ };
+ const findings = getCheck(PANEL_RHYTHM).run(ctx);
+ expect(findings).toHaveLength(1);
+ });
+ });
+
+ describe('comic.page-turn-beats — LLM', () => {
+ it('is registered as an issue-scoped LLM pacing check reading comicScript + reader-map', () => {
+ const check = getCheck(PAGE_TURN);
+ expect(check.kind).toBe('llm');
+ expect(check.scope).toBe('issue');
+ expect(check.category).toBe('pacing');
+ expect(check.sources).toEqual(['comicScript', 'series.arc.readerMap']);
+ });
+
+ it('passes each issue page layout + authored reveals to the model and attributes findings to the issue', async () => {
+ const seenVars = [];
+ const ctx = {
+ config: {},
+ severityDefault: 'low',
+ series: { arc: { readerMap: { beats: [{ kind: 'reveal', note: 'The mentor is the villain' }], cliffhangers: [] } } },
+ comicScripts: [issue(7, [1, 3, 2])],
+ callStagedLLM: async (_stage, vars) => {
+ seenVars.push(vars);
+ return { content: { findings: [{ severity: 'medium', location: 'Page 2', problem: 'Reveal exposed early' }] } };
+ },
+ };
+ const findings = await getCheck(PAGE_TURN).run(ctx);
+ expect(seenVars[0].pageLayout).toContain('Issue 7 page layout:');
+ expect(seenVars[0].authoredReveals).toContain('The mentor is the villain');
+ expect(findings).toHaveLength(1);
+ expect(findings[0].category).toBe('pacing');
+ expect(findings[0].issueNumber).toBe(7);
+ });
+
+ it('passes an empty authoredReveals var when the series has no reader-map', async () => {
+ let seen = null;
+ const ctx = {
+ config: {},
+ severityDefault: 'low',
+ series: {},
+ comicScripts: [issue(1, [2, 2])],
+ callStagedLLM: async (_stage, vars) => { seen = vars; return { content: { findings: [] } }; },
+ };
+ await getCheck(PAGE_TURN).run(ctx);
+ expect(seen.authoredReveals).toBe('');
+ });
+
+ it('stops launching further issue calls once maxFindings is reached', async () => {
+ let calls = 0;
+ const ctx = {
+ config: { maxFindings: 1 },
+ severityDefault: 'low',
+ series: {},
+ comicScripts: [issue(1, [2, 2]), issue(2, [3, 3])],
+ callStagedLLM: async () => { calls += 1; return { content: { findings: [{ problem: 'x' }] } }; },
+ };
+ const findings = await getCheck(PAGE_TURN).run(ctx);
+ expect(findings).toHaveLength(1);
+ expect(calls).toBe(1);
+ });
+ });
+});
diff --git a/server/lib/editorial/comicPacing.js b/server/lib/editorial/comicPacing.js
new file mode 100644
index 0000000000..6ac3087ec7
--- /dev/null
+++ b/server/lib/editorial/comicPacing.js
@@ -0,0 +1,211 @@
+/**
+ * Pure comic-pacing primitives for the comic editorial checks (#1314) —
+ * splash-page usage, panel rhythm, and page-turn beat placement. Operates on the
+ * ALREADY-PARSED comic pages the runner produces from each issue's stored comic
+ * script (`comicScriptParser.parseComicScript().pages`), so this module stays
+ * dependency-free (the parser imports out to fileUtils, which the pure editorial
+ * registry can't), matching nameSimilarity.js / proseTics.js.
+ *
+ * A parsed page is `{ rawText, panels: [{ description, caption, dialogue, sfx }] }`.
+ * These helpers never read ctx, never throw on a malformed page, and return plain
+ * data the registry's `run(ctx)` shapes into findings (with `ctx.severityDefault`).
+ */
+
+// A page with exactly one panel is a splash — a single full-page image. Zero
+// panels can't happen for a kept page (the parser drops contentless panels and
+// filters empty pages), but guard anyway so a hand-built page array is inert.
+export const isSplashPage = (page) => Array.isArray(page?.panels) && page.panels.length === 1;
+
+// The recto/verso layout of a comic interior, 1-indexed by page number.
+//
+// Print convention: page 1 is a RECTO (the right-hand page, paired with the
+// inside front cover). From page 2 on, the reader sees two-page SPREADS —
+// verso (even, left) + recto (odd, right). A page turn flips the recto and
+// reveals the NEXT spread's pages all at once, so a beat on a page is "visible
+// early" (pre-turn) once any page of its spread is on-screen. `beginsSpread`
+// marks the first page of each spread — the page that only appears after a turn,
+// where a reveal stays hidden until the reader commits to it.
+export function comicSpreadLayout(pageCount) {
+ const n = Number.isInteger(pageCount) && pageCount > 0 ? pageCount : 0;
+ const layout = [];
+ for (let p = 1; p <= n; p += 1) {
+ if (p === 1) {
+ layout.push({ pageNumber: 1, side: 'recto', spread: 1, beginsSpread: true });
+ continue;
+ }
+ const side = p % 2 === 0 ? 'verso' : 'recto';
+ const spread = Math.floor(p / 2) + 1;
+ // A verso (even page) opens each spread after page 1; its recto partner
+ // completes the same spread. Page 1's spread is opened by page 1 itself.
+ layout.push({ pageNumber: p, side, spread, beginsSpread: side === 'verso' });
+ }
+ return layout;
+}
+
+// A compact, type-guarded one-line digest of a panel's content for the page-turn
+// LLM context — its description (truncated), plus a hint of caption/dialogue/SFX
+// load so the model can reason about where a beat actually lands on the page.
+function panelDigest(panel) {
+ if (!panel || typeof panel !== 'object') return '';
+ const desc = typeof panel.description === 'string' ? panel.description.trim().replace(/\s+/g, ' ') : '';
+ const head = desc ? desc.slice(0, 160) : '(no description)';
+ const extras = [];
+ const caption = typeof panel.caption === 'string' ? panel.caption.trim() : '';
+ if (caption) extras.push('caption');
+ const dialogue = Array.isArray(panel.dialogue) ? panel.dialogue : [];
+ if (dialogue.length) extras.push(`${dialogue.length} dialogue`);
+ const sfx = typeof panel.sfx === 'string' ? panel.sfx.trim() : '';
+ if (sfx) extras.push('sfx');
+ return extras.length ? `${head} [${extras.join(', ')}]` : head;
+}
+
+// Per-page summary used by both the deterministic rhythm analysis and the
+// page-turn LLM context: panel count, splash flag, recto/verso side + spread,
+// and a short content digest. `pages` is one issue's parsed comic pages.
+export function summarizeComicPages(pages) {
+ const list = Array.isArray(pages) ? pages : [];
+ const layout = comicSpreadLayout(list.length);
+ return list.map((page, i) => {
+ const panels = Array.isArray(page?.panels) ? page.panels : [];
+ const pos = layout[i] || { pageNumber: i + 1, side: 'recto', spread: 1, beginsSpread: true };
+ return {
+ pageNumber: pos.pageNumber,
+ panelCount: panels.length,
+ isSplash: panels.length === 1,
+ side: pos.side,
+ spread: pos.spread,
+ beginsSpread: pos.beginsSpread,
+ panels: panels.map(panelDigest),
+ };
+ });
+}
+
+// Deterministic panel-rhythm + splash analysis over one issue's parsed pages.
+// Returns plain signals (no severity / finding text — the registry's run() shapes
+// those) so the heuristics stay unit-testable in isolation:
+//
+// - splashPages — page numbers that are full-page splashes.
+// - splashRatio — splashes / total pages (0 when no pages).
+// - splashOveruse — true when splashRatio is at/above `splashRatioWarn`
+// AND there is more than one splash (a lone splash on a
+// short script isn't overuse).
+// - backToBackSplashes — runs of >= 2 consecutive splash pages, as
+// { startPage, endPage, length }.
+// - overcrowded — pages with more than `maxPanelsPerPage` panels, as
+// { pageNumber, panelCount }.
+// - monotonyRuns — runs of >= `monotonyRunLength` consecutive pages that
+// all carry the SAME (multi-panel) panel count, as
+// { startPage, endPage, panelCount, length }. Splash
+// runs are reported separately, so a monotony run needs
+// panelCount >= 2.
+export function analyzePanelRhythm(pages, cfg = {}) {
+ const list = Array.isArray(pages) ? pages : [];
+ const totalPages = list.length;
+ const maxPanelsPerPage = Number.isFinite(cfg.maxPanelsPerPage) ? cfg.maxPanelsPerPage : 9;
+ const splashRatioWarn = Number.isFinite(cfg.splashRatioWarn) ? cfg.splashRatioWarn : 0.25;
+ const monotonyRunLength = Number.isInteger(cfg.monotonyRunLength) ? cfg.monotonyRunLength : 4;
+
+ const counts = list.map((p) => (Array.isArray(p?.panels) ? p.panels.length : 0));
+ const splashPages = [];
+ const overcrowded = [];
+ counts.forEach((c, i) => {
+ const pageNumber = i + 1;
+ if (c === 1) splashPages.push(pageNumber);
+ if (c > maxPanelsPerPage) overcrowded.push({ pageNumber, panelCount: c });
+ });
+
+ const splashRatio = totalPages > 0 ? splashPages.length / totalPages : 0;
+ const splashOveruse = splashPages.length > 1 && splashRatio >= splashRatioWarn;
+
+ // Consecutive-splash runs (length >= 2).
+ const backToBackSplashes = collectRuns(counts, (c) => c === 1, 2)
+ .map((r) => ({ startPage: r.start + 1, endPage: r.end + 1, length: r.length }));
+
+ // Monotony runs: same multi-panel count repeated for >= monotonyRunLength pages.
+ // A run of identical splashes is a back-to-back-splash signal, not grid monotony,
+ // so monotony is gated to panelCount >= 2.
+ const monotonyRuns = [];
+ if (monotonyRunLength >= 2) {
+ let start = 0;
+ for (let i = 1; i <= counts.length; i += 1) {
+ if (i < counts.length && counts[i] === counts[start]) continue;
+ const length = i - start;
+ const panelCount = counts[start];
+ if (panelCount >= 2 && length >= monotonyRunLength) {
+ monotonyRuns.push({ startPage: start + 1, endPage: i, panelCount, length });
+ }
+ start = i;
+ }
+ }
+
+ return { totalPages, splashPages, splashRatio, splashOveruse, backToBackSplashes, overcrowded, monotonyRuns };
+}
+
+// Collect runs of >= minLength consecutive entries satisfying `pred`, as
+// { start, end, length } (0-indexed, inclusive). Shared by the splash-run scan.
+function collectRuns(arr, pred, minLength) {
+ const runs = [];
+ let start = -1;
+ for (let i = 0; i <= arr.length; i += 1) {
+ const ok = i < arr.length && pred(arr[i]);
+ if (ok && start === -1) start = i;
+ if (!ok && start !== -1) {
+ const length = i - start;
+ if (length >= minLength) runs.push({ start, end: i - 1, length });
+ start = -1;
+ }
+ }
+ return runs;
+}
+
+// Render one issue's page layout into a compact text block the page-turn-beats
+// LLM check passes alongside the manuscript/script so the model knows each page's
+// recto/verso side, spread, panel breakdown, and which pages are first-seen only
+// after a page turn (`beginsSpread`). Pure + deterministic so it's unit-testable
+// and its token cost can be counted into the per-chunk overhead. Returns '' for an
+// empty page list. `issueNumber` (when an integer) prefixes the block.
+export function comicPageTurnSummary(pages, issueNumber = null) {
+ const summary = summarizeComicPages(pages);
+ if (!summary.length) return '';
+ const lines = summary.map((pg) => {
+ const turn = pg.beginsSpread ? ', first page after a turn (reveal-safe)' : '';
+ const kind = pg.isSplash ? 'splash' : `${pg.panelCount} panels`;
+ const panels = pg.panels.length ? `\n ${pg.panels.map((p, i) => `panel ${i + 1}: ${p}`).join('\n ')}` : '';
+ return `- Page ${pg.pageNumber} (${pg.side}, spread ${pg.spread}${turn}) — ${kind}${panels}`;
+ });
+ const header = Number.isInteger(issueNumber) ? `Issue ${issueNumber} page layout:` : 'Page layout:';
+ return `${header}\n${lines.join('\n')}`;
+}
+
+// Render the authored reader-map REVEALS (beats with kind 'reveal') and
+// CLIFFHANGERS into a compact text block the page-turn-beats check passes
+// alongside the script, so the model reconciles WHICH beats are big reveals that
+// need a protected page-turn against what the writer logged. Pure + deterministic
+// (mirrors authoredCliffhangerSummary / authoredSetupPayoffSummary in the
+// registry). Returns '' when nothing reveal-like is authored.
+export function authoredRevealSummary(readerMap) {
+ const beats = Array.isArray(readerMap?.beats) ? readerMap.beats : [];
+ const cliffs = Array.isArray(readerMap?.cliffhangers) ? readerMap.cliffhangers : [];
+ const revealLines = beats
+ .filter((b) => b?.kind === 'reveal')
+ .map((b) => {
+ const note = typeof b?.note === 'string' ? b.note.trim() : '';
+ if (!note) return '';
+ const pos = Number.isFinite(b?.atArcPosition) ? ` (arc position ${b.atArcPosition})` : '';
+ return `- ${note}${pos}`;
+ })
+ .filter(Boolean);
+ const cliffLines = cliffs
+ .map((c) => {
+ const note = typeof c?.note === 'string' ? c.note.trim() : '';
+ if (!note) return '';
+ const at = Number.isInteger(c?.atIssueBoundary) ? ` (ending issue ${c.atIssueBoundary})` : '';
+ return `- ${note}${at}`;
+ })
+ .filter(Boolean);
+ if (!revealLines.length && !cliffLines.length) return '';
+ const parts = [];
+ if (revealLines.length) parts.push(`Authored reveals (beats the writer planted):\n${revealLines.join('\n')}`);
+ if (cliffLines.length) parts.push(`Authored cliffhangers (issue-boundary tugs):\n${cliffLines.join('\n')}`);
+ return parts.join('\n\n');
+}
diff --git a/server/lib/editorial/comicPacing.test.js b/server/lib/editorial/comicPacing.test.js
new file mode 100644
index 0000000000..eb477f1e8e
--- /dev/null
+++ b/server/lib/editorial/comicPacing.test.js
@@ -0,0 +1,147 @@
+import { describe, it, expect } from 'vitest';
+import {
+ isSplashPage,
+ comicSpreadLayout,
+ summarizeComicPages,
+ analyzePanelRhythm,
+ comicPageTurnSummary,
+ authoredRevealSummary,
+} from './comicPacing.js';
+
+// A parsed page is `{ rawText, panels: [...] }`; build pages by panel count.
+const page = (n) => ({ rawText: '', panels: Array.from({ length: n }, (_, i) => ({ description: `p${i}`, caption: '', dialogue: [], sfx: '' })) });
+const pagesByCounts = (counts) => counts.map(page);
+
+describe('isSplashPage', () => {
+ it('is true only for a single-panel page', () => {
+ expect(isSplashPage(page(1))).toBe(true);
+ expect(isSplashPage(page(2))).toBe(false);
+ expect(isSplashPage(page(0))).toBe(false);
+ expect(isSplashPage(null)).toBe(false);
+ expect(isSplashPage({})).toBe(false);
+ });
+});
+
+describe('comicSpreadLayout', () => {
+ it('places page 1 as a lone recto, then verso/recto spreads', () => {
+ const layout = comicSpreadLayout(5);
+ expect(layout).toEqual([
+ { pageNumber: 1, side: 'recto', spread: 1, beginsSpread: true },
+ { pageNumber: 2, side: 'verso', spread: 2, beginsSpread: true },
+ { pageNumber: 3, side: 'recto', spread: 2, beginsSpread: false },
+ { pageNumber: 4, side: 'verso', spread: 3, beginsSpread: true },
+ { pageNumber: 5, side: 'recto', spread: 3, beginsSpread: false },
+ ]);
+ });
+
+ it('returns [] for non-positive / non-integer counts', () => {
+ expect(comicSpreadLayout(0)).toEqual([]);
+ expect(comicSpreadLayout(-3)).toEqual([]);
+ expect(comicSpreadLayout(2.5)).toEqual([]);
+ });
+});
+
+describe('summarizeComicPages', () => {
+ it('summarizes panel count, splash, side, and digests', () => {
+ const summary = summarizeComicPages([page(1), page(3)]);
+ expect(summary[0]).toMatchObject({ pageNumber: 1, panelCount: 1, isSplash: true, side: 'recto', beginsSpread: true });
+ expect(summary[1]).toMatchObject({ pageNumber: 2, panelCount: 3, isSplash: false, side: 'verso' });
+ expect(summary[1].panels).toHaveLength(3);
+ });
+
+ it('folds caption/dialogue/sfx hints into the panel digest', () => {
+ const pages = [{ panels: [{ description: 'A long beat', caption: 'cap', dialogue: [{ character: 'X', line: 'hi' }], sfx: 'BOOM' }] }];
+ const [pg] = summarizeComicPages(pages);
+ expect(pg.panels[0]).toContain('A long beat');
+ expect(pg.panels[0]).toContain('caption');
+ expect(pg.panels[0]).toContain('1 dialogue');
+ expect(pg.panels[0]).toContain('sfx');
+ });
+
+ it('tolerates a non-array input', () => {
+ expect(summarizeComicPages(null)).toEqual([]);
+ });
+});
+
+describe('analyzePanelRhythm — splashes', () => {
+ it('flags splash overuse above the ratio when more than one splash', () => {
+ const r = analyzePanelRhythm(pagesByCounts([1, 1, 3, 4]), { splashRatioWarn: 0.25 });
+ expect(r.splashPages).toEqual([1, 2]);
+ expect(r.splashRatio).toBe(0.5);
+ expect(r.splashOveruse).toBe(true);
+ });
+
+ it('does not flag a lone splash as overuse', () => {
+ const r = analyzePanelRhythm(pagesByCounts([1, 3, 4, 5]), { splashRatioWarn: 0.2 });
+ expect(r.splashPages).toEqual([1]);
+ expect(r.splashOveruse).toBe(false);
+ });
+
+ it('collects back-to-back splash runs of length >= 2', () => {
+ const r = analyzePanelRhythm(pagesByCounts([1, 1, 1, 4, 1]));
+ expect(r.backToBackSplashes).toEqual([{ startPage: 1, endPage: 3, length: 3 }]);
+ });
+});
+
+describe('analyzePanelRhythm — crowding & monotony', () => {
+ it('flags overcrowded pages above the max', () => {
+ const r = analyzePanelRhythm(pagesByCounts([3, 11, 4, 12]), { maxPanelsPerPage: 9 });
+ expect(r.overcrowded).toEqual([
+ { pageNumber: 2, panelCount: 11 },
+ { pageNumber: 4, panelCount: 12 },
+ ]);
+ });
+
+ it('flags a monotony run of identical multi-panel counts', () => {
+ const r = analyzePanelRhythm(pagesByCounts([4, 4, 4, 4, 6]), { monotonyRunLength: 4 });
+ expect(r.monotonyRuns).toEqual([{ startPage: 1, endPage: 4, panelCount: 4, length: 4 }]);
+ });
+
+ it('does not treat a splash run as grid monotony', () => {
+ const r = analyzePanelRhythm(pagesByCounts([1, 1, 1, 1]), { monotonyRunLength: 4 });
+ expect(r.monotonyRuns).toEqual([]);
+ expect(r.backToBackSplashes).toEqual([{ startPage: 1, endPage: 4, length: 4 }]);
+ });
+
+ it('monotonyRunLength below 2 disables the monotony scan', () => {
+ const r = analyzePanelRhythm(pagesByCounts([4, 4, 4, 4]), { monotonyRunLength: 1 });
+ expect(r.monotonyRuns).toEqual([]);
+ });
+});
+
+describe('comicPageTurnSummary', () => {
+ it('renders a per-page layout block with reveal-safe markers', () => {
+ const out = comicPageTurnSummary([page(1), page(3), page(2)], 4);
+ expect(out).toContain('Issue 4 page layout:');
+ expect(out).toContain('Page 1 (recto, spread 1, first page after a turn (reveal-safe)) — splash');
+ expect(out).toContain('Page 2 (verso, spread 2, first page after a turn (reveal-safe)) — 3 panels');
+ expect(out).toContain('Page 3 (recto, spread 2) — 2 panels');
+ });
+
+ it('returns empty string for no pages', () => {
+ expect(comicPageTurnSummary([])).toBe('');
+ });
+});
+
+describe('authoredRevealSummary', () => {
+ it('renders reveals (beats kind=reveal) and cliffhangers', () => {
+ const readerMap = {
+ beats: [
+ { kind: 'reveal', note: 'The mentor is the villain', atArcPosition: 6 },
+ { kind: 'hook', note: 'who sent the letter' },
+ ],
+ cliffhangers: [{ note: 'The door opens', atIssueBoundary: 2 }],
+ };
+ const out = authoredRevealSummary(readerMap);
+ expect(out).toContain('Authored reveals');
+ expect(out).toContain('The mentor is the villain (arc position 6)');
+ expect(out).not.toContain('who sent the letter');
+ expect(out).toContain('Authored cliffhangers');
+ expect(out).toContain('The door opens (ending issue 2)');
+ });
+
+ it('returns empty string when nothing reveal-like is authored', () => {
+ expect(authoredRevealSummary(null)).toBe('');
+ expect(authoredRevealSummary({ beats: [{ kind: 'hook', note: 'q' }] })).toBe('');
+ });
+});
diff --git a/server/lib/editorial/index.js b/server/lib/editorial/index.js
index 85466f6f37..58709cfb59 100644
--- a/server/lib/editorial/index.js
+++ b/server/lib/editorial/index.js
@@ -2,6 +2,7 @@
// (#1284). See README.md for the catalog. Re-export every public module here.
export * from './checkRegistry.js';
export * from './cliches.js';
+export * from './comicPacing.js';
export * from './dialogue.js';
export * from './italicThoughts.js';
export * from './nameSimilarity.js';
diff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.js
index 731c15feb1..f2b5a16f55 100644
--- a/server/services/pipeline/editorial/checkRunner.js
+++ b/server/services/pipeline/editorial/checkRunner.js
@@ -29,6 +29,7 @@ import { getReverseOutline } from '../reverseOutline.js';
import { getSeriesEditorial } from '../editorialAnalysis.js';
import { seedReviewFromFindings, getReview } from '../manuscriptReview.js';
import { canonicalStringify } from '../../../lib/objects.js';
+import { parseComicScript } from '../../../lib/comicScriptParser.js';
// Source-content fingerprinting for finding staleness (#1345, #1387). Each finding
// is stamped with a hash of the exact content its check analyzed; the manuscript
@@ -81,8 +82,30 @@ const SOURCE_RESOLVERS = {
// against (#1293). Lives on the already-loaded series record, so no extra I/O
// — fingerprint the whole array so any arc/transition edit stales the findings.
'series.characterArcs': ({ series }) => canonicalStringify(series?.characterArcs ?? null),
+ // The per-issue PARSED comic scripts the comic-pacing checks read (#1314).
+ // Fingerprint the parsed page/panel structure so a comic-script edit stales the
+ // findings (and a prose-only edit that leaves the comic script untouched doesn't).
+ comicScript: ({ comicScripts }) => canonicalStringify(comicScripts ?? null),
};
+// Parse each issue's stored comic script into `{ issueNumber, pages }` rows,
+// keeping only issues that parsed to at least one page (an issue without a comic
+// script, or one that parses to zero pages, contributes nothing the comic-pacing
+// checks can read). Lives in the runner (not the pure editorial registry) because
+// `parseComicScript` imports out to fileUtils — the registry stays import-pure and
+// reads the already-parsed rows off `ctx.comicScripts`.
+function parseComicScripts(issues) {
+ const rows = [];
+ for (const issue of Array.isArray(issues) ? issues : []) {
+ const source = (issue?.stages?.comicScript?.output || '').trim();
+ if (!source) continue;
+ const { pages } = parseComicScript(source);
+ if (!Array.isArray(pages) || pages.length === 0) continue;
+ rows.push({ issueNumber: Number.isInteger(issue.number) ? issue.number : null, pages });
+ }
+ return rows;
+}
+
// Stable projection of the series editorial aggregate down to the arc fields a
// POV/arc check reads — drops the volatile `generatedAt` (and the rest) so the
// staleness fingerprint only moves when a character's detected arc actually does.
@@ -197,6 +220,9 @@ export async function runEditorialChecks(seriesId, options = {}) {
// Editorial-arc fetch is gated on the declared source (#1295) so a run with no
// POV/arc check pays no extra snapshot I/O — mirrors the needsReverseOutline gate.
const needsEditorialArcs = enabled.some(({ check }) => checkSources(check).includes('editorialArcs'));
+ // Comic-script parsing is gated on the declared source (#1314) so a run with no
+ // comic-pacing check pays no parse cost — the issues are already fetched below.
+ const needsComicScript = enabled.some(({ check }) => checkSources(check).includes('comicScript'));
const [sections, canon, issues, outline, editorial] = await Promise.all([
needsManuscript ? collectManuscriptSections(seriesId) : Promise.resolve([]),
getSeriesCanon(series),
@@ -214,6 +240,9 @@ export async function runEditorialChecks(seriesId, options = {}) {
// against the author's tagged threads.
const reverseOutlinePlotlines = Array.isArray(outline?.plotlines) ? outline.plotlines : [];
const editorialArcs = projectEditorialArcs(editorial);
+ // Per-issue parsed comic scripts for the comic-pacing checks (#1314) — derived
+ // from the already-fetched issues (no extra I/O), only when a comic check is enabled.
+ const comicScripts = needsComicScript ? parseComicScripts(issues) : [];
// Whether every analyzable issue has been analyzed and is fresh — gates the
// pov.justified "absent from detected arcs" finding so a partially-analyzed
// series (canceled/early-stopped batch) doesn't flag a not-yet-analyzed POV
@@ -222,7 +251,7 @@ export async function runEditorialChecks(seriesId, options = {}) {
// Resolve every source token once — each finding's fingerprint reads from this
// so the editor flags it `stale` when the content that check actually read (its
// declared `sources`) drifts (#1345, #1387).
- const resolvedSources = resolveSources({ manuscript, canon, series, reverseOutline, reverseOutlinePlotlines, editorialArcs, editorialArcsComplete });
+ const resolvedSources = resolveSources({ manuscript, canon, series, reverseOutline, reverseOutlinePlotlines, editorialArcs, editorialArcsComplete, comicScripts });
const baseCtx = {
seriesId,
series,
@@ -233,6 +262,7 @@ export async function runEditorialChecks(seriesId, options = {}) {
reverseOutlinePlotlines,
editorialArcs,
editorialArcsComplete,
+ comicScripts,
canon,
providerOverride,
modelOverride,
@@ -380,19 +410,24 @@ export async function getReviewWithStaleness(seriesId) {
return sources.includes('reverseOutline') || sources.includes('reverseOutline.plotlines');
});
const needsEditorialArcs = evaluable.some((c) => checkSources(checkFor(c.checkId)).includes('editorialArcs'));
+ // Comic-script parsing for staleness — gated like the run path, fetching the
+ // issues only when an evaluable comic-pacing finding needs them (#1314).
+ const needsComicScript = evaluable.some((c) => checkSources(checkFor(c.checkId)).includes('comicScript'));
const series = await getSeries(seriesId);
- const [sections, canon, outline, editorial] = await Promise.all([
+ const [sections, canon, outline, editorial, comicIssues] = await Promise.all([
needsManuscript ? collectManuscriptSections(seriesId) : Promise.resolve([]),
getSeriesCanon(series),
needsReverseOutline ? getReverseOutline(seriesId).catch(() => null) : Promise.resolve(null),
// Reuse the already-loaded series (issues isn't fetched on this path).
needsEditorialArcs ? getSeriesEditorial(seriesId, { series }).catch(() => null) : Promise.resolve(null),
+ needsComicScript ? listIssues({ seriesId }).catch(() => []) : Promise.resolve([]),
]);
const reverseOutline = Array.isArray(outline?.scenes) ? outline.scenes : [];
const reverseOutlinePlotlines = Array.isArray(outline?.plotlines) ? outline.plotlines : [];
const editorialArcs = projectEditorialArcs(editorial);
const editorialArcsComplete = editorialCoverageComplete(editorial);
- const resolvedSources = resolveSources({ manuscript: sectionsCorpus(sections), canon, series, reverseOutline, reverseOutlinePlotlines, editorialArcs, editorialArcsComplete });
+ const comicScripts = needsComicScript ? parseComicScripts(comicIssues) : [];
+ const resolvedSources = resolveSources({ manuscript: sectionsCorpus(sections), canon, series, reverseOutline, reverseOutlinePlotlines, editorialArcs, editorialArcsComplete, comicScripts });
return {
...review,
comments: review.comments.map((c) => {
diff --git a/server/services/pipeline/editorial/checkRunner.test.js b/server/services/pipeline/editorial/checkRunner.test.js
index a7cf4a1ac6..819a5383d8 100644
--- a/server/services/pipeline/editorial/checkRunner.test.js
+++ b/server/services/pipeline/editorial/checkRunner.test.js
@@ -76,6 +76,7 @@ const { getSeriesCanon } = await import('../seriesCanon.js');
const { getSeries } = await import('../series.js');
const { getSettings } = await import('../../settings.js');
const { listChecks, getCheck } = await import('../../../lib/editorial/index.js');
+const { listIssues } = await import('../issues.js');
// Build a `pipelineEditorialChecks.checks` map that disables every check
// matching `predicate` — keeps these fixtures robust as the registry grows
@@ -96,6 +97,8 @@ beforeEach(() => {
resolveStageContext.mockClear();
collectManuscriptSections.mockClear();
getSeriesCanon.mockClear();
+ listIssues.mockClear();
+ listIssues.mockResolvedValue([]);
});
describe('runEditorialChecks', () => {
@@ -143,6 +146,31 @@ describe('runEditorialChecks', () => {
expect(collectManuscriptSections).toHaveBeenCalled();
});
+ it('parses each issue comic script and feeds comic-pacing checks (#1314)', async () => {
+ // Two issues with comic scripts: issue 1 has a back-to-back splash run the
+ // deterministic comic.panel-rhythm check flags; issue 2 has none. The runner
+ // parses the stored scripts into pages and injects ctx.comicScripts.
+ listIssues.mockResolvedValueOnce([
+ { number: 1, stages: { comicScript: { output: 'PAGE 1\nPANEL 1\nSplash.\nPAGE 2\nPANEL 1\nSplash again.' } } },
+ { number: 2, stages: { comicScript: { output: 'PAGE 1\nPANEL 1\nA.\nPANEL 2\nB.\nPANEL 3\nC.' } } },
+ ]);
+ const result = await runEditorialChecks('s1', { checkIds: ['comic.panel-rhythm'] });
+ const comic = result.findings.filter((f) => f.checkId === 'comic.panel-rhythm');
+ expect(comic.length).toBeGreaterThan(0);
+ expect(comic.some((f) => f.issueNumber === 1)).toBe(true);
+ expect(comic.every((f) => f.category === 'pacing')).toBe(true);
+ });
+
+ it('skips comic-script parsing when no comic-pacing check is enabled', async () => {
+ listIssues.mockResolvedValueOnce([
+ { number: 1, stages: { comicScript: { output: 'PAGE 1\nPANEL 1\nSplash.' } } },
+ ]);
+ // Only the naming check runs — it never declares the comicScript source, so the
+ // parsed-pages gate keeps comic checks inert (no comic findings produced).
+ const result = await runEditorialChecks('s1', { checkIds: ['naming.dissimilar-names'] });
+ expect(result.findings.some((f) => f.checkId === 'comic.panel-rhythm')).toBe(false);
+ });
+
it('skips disabled checks', async () => {
// Disable every LLM check → no provider call, only deterministic findings.
// The mock canon has no objects/links, so naming is the only producer.