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

Merge remote-tracking branch 'origin/main' into claim/issue-1314

Adam Eivy6849cb9c3e12
diff --cc .changelog/NEXT.md
index f74babffe0,214ad004ac..4f30278045
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@@ -2,9 -2,20 +2,21 @@@
## 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-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 (117). (`server/lib/editorial/{comicPacing,checkRegistry}.js`, `server/services/pipeline/editorial/checkRunner.js`, `scripts/migrations/117-editorial-comic-page-turn-stage.js`, #1314)
+ - **[issue-1408] LoRA training quality-of-life: vision-assisted reference-sheet slicing, caption with Claude/Codex CLI providers, and a richer training queue.** Three improvements to building character LoRAs (Create → LoRA Training). **(1) Smarter sheet slicing** — "Slice reference sheet" now offers *Auto-detect figures with a vision model*, which asks a vision model to draw a tight box around each figure on the turnaround and crops those instead of a rigid grid; it falls back to the columns×rows grid automatically when no vision model is installed or detection finds nothing, so you still get crops to prune either way. **(2) Caption with a CLI model** — the caption-model picker now also lists vision-capable CLI providers (Codex / Claude Code), so you can auto-caption a dataset with `codex` or `claude` (vision) rather than only a local LM Studio / Ollama vision model. **(3) Training queue at a glance** — the new Training queue on the LoRA Training page shows each run's loss curve (a sparkline over its checkpoints) and sample thumbnails right in the row, so you can watch a run learn — and spot a divergence — without opening it. (Part of #1227, #1408)
+ - **[issue-1412] Editorial check classifies unmodeled proper nouns used as character names — the LLM-assisted half of roster economy.** A new **Unmodeled proper nouns used as character names** LLM check (Create → Editorial Checks) closes the gap the deterministic **roster economy** check (#1292) deliberately left open: that scan only sees canon names + aliases, so a proper noun used as an *apparent* character name that was never added to the story bible is invisible to it. This check surfaces those — and **classifies** each one, because a keyword scan can't tell a person from a place, organization, brand, or honorific. It reads the stitched manuscript plus your canon roster (names + aliases) as an exclusion list, flags capitalized proper nouns used as character names that are **absent from canon**, and calls out **throwaway one-appearance names** the reader is told to remember but who never recur — suggesting either adding them to canon or recasting them as an unnamed description. Unlike roster economy it runs even on an **empty bible** (then every named proper noun is a candidate). The LLM does only the judgment it alone can — surface a name and confirm it's a *person* — while a **deterministic pass counts each surfaced name's appearances across the whole manuscript and authors the verdict** (one-appearance throwaway vs recurring), so a long book reviewed in chunks never mislabels a name that appears in chapters 1 and 12 as a throwaway (and the same name surfaced from two chunks collapses to one finding). Findings render as `Casting` notes anchored to the issue + a verbatim quote. Ships a new stage prompt (`pipeline-editorial-unmodeled-names`) that migrates for existing installs (116). (`server/lib/editorial/checkRegistry.js`, `data.reference/prompts/stages/pipeline-editorial-unmodeled-names.md`, `scripts/migrations/116-editorial-unmodeled-names-stage.js`, Part of #1283, #1412)
+ - **[issue-1317] Editorial check flags theme-coherence problems — themes stated but never dramatized, dropped after the opening, or unpaid at the climax (plus emergent-theme detection).** A new **Theme coherence / thematic throughline** LLM check (Create → Editorial Checks) asks whether the manuscript actually *delivers* the themes the story arc declares (`series.arc.themes`), not just names them. For each declared theme it builds a setup → complication → payoff coverage map and flags a theme that is **stated but never dramatized** through a character's choices or the central conflict, a theme that is **dropped** after the opening, and a climax that **resolves the plot but never lands the thematic argument** the setup promised. It also detects a strong **emergent theme** the story is really telling that isn't in the declared list — offering to add it (or reconciling it when the story drifts into a competing argument). It reads your reverse-outline scene segmentation as context so it can attribute a theme's setup/payoff to a scene + issue, and **degrades gracefully** — no authored themes ⇒ it works from the prose alone to surface emergent themes; no outline ⇒ it scans the whole manuscript. Whole-arc judgments (a dropped theme, an unpaid climax) are deferred until it has seen the final chunk, and cross-chunk findings + clean-setup digests keep a long book reviewed in pieces from false-flagging a theme whose payoff lands later. Findings render as `Theme` notes anchored to the issue + a verbatim quote. Ships a new stage prompt (`pipeline-editorial-theme-coherence`) that migrates for existing installs (115). (`server/lib/editorial/checkRegistry.js`, `server/services/pipeline/editorial/checkRunner.js`, `data.reference/prompts/stages/pipeline-editorial-theme-coherence.md`, `scripts/migrations/115-editorial-theme-coherence-stage.js`, Part of #1283, #1317)
+
+ - **[issue-1316] Editorial health score + revision-trend tracking — *manage* the draft, not just receive findings.** A new **Editorial Health** panel (Create → Editorial Checks, alongside the findings triage) turns the point-in-time manuscript-review findings into a metric you can steer by. A transparent, deterministic **health score** (0–100, per series with a per-issue drill-down) is computed from the OPEN findings weighted by severity — `100 − Σ weight(severity)` with published weights (high 12 / medium 5 / low 1), so it's never a black box; accepted (fixed) and dismissed (waived) findings cost nothing. A **revision-trend ledger** snapshots the open-finding counts (by severity + category) on each editorial-checks / completeness run — the run is the revision boundary — so the panel renders a **score sparkline** across revisions, the most-recent-revision **delta**, and per-category **regressions** (a category that got *worse* after an edit pass). A configurable **readiness gate** ("no open high findings" by default, or the stricter "no high or medium", or "none") is the convergence signal the UI shows as **Ready / Not ready** *and* that the **autopilot editorial loop** now reads as a final gate (`editorialHealthGate`): after both editorial passes seed their findings, autopilot pauses with the residual blockers if the manuscript isn't clean — catching a blocker the registry checks surface *after* the completeness loop converged. The trend ledger is install-local telemetry (`data/pipeline-editorial-health/{seriesId}.json`, not synced); the score/readiness are derived live from the synced review. Scoring is pure + unit-tested. (`server/services/pipeline/editorialScore.js`, `server/routes/pipeline/editorial.js`, `server/services/pipeline/{editorial/checkRunner,manuscriptCompletenessRunner,seriesAutopilot}.js`, `client/src/components/pipeline/editorial/EditorialHealthPanel.jsx`, `client/src/lib/editorialHealth.js`, Part of #1283, #1316)
+
+ - **[issue-1315] Storyboard shots now record camera framing + screen direction, and a new editorial check catches film-grammar continuity errors before render.** Each storyboard shot gains two film-grammar fields — **shot type** (extreme-wide / wide / medium / close / extreme-close / over-the-shoulder / two-shot / POV) and **screen direction** (the side the subject faces or moves: left / right / neutral) — captured by the scene extractor (the teleplay→scenes prompt now asks the model to tag them) and carried on the shot record. A new deterministic **Storyboard shot continuity** check (Create → Editorial Checks) reads those fields and flags two classic film-grammar mistakes *before* you spend render time on a clip: a **180-degree-rule axis reversal** — a shot that continues from an earlier one but flips the subject to the opposite side of the screen, so they appear to jump sides across the cut — and **shot-type monotony**, a scene whose shots all share one framing and read as flat, slideshow coverage with no establishing wide or punch-in. Findings render as `Continuity` notes anchored to the offending issue + scene, and (being deterministic) need no LLM. Both fields are backward-compatible and default to "not captured," so older storyboards simply aren't flagged until re-extracted; the extraction-prompt change migrates for existing installs (114). Eyeline-match and appearance/prop continuity (which need a vision/LLM pass) and a hard pre-render render-gate are tracked as follow-ups. (`server/lib/shotGrammar.js`, `server/lib/sceneExtractor.js`, `server/lib/editorial/shotContinuity.js`, `server/lib/editorial/checkRegistry.js`, `server/services/pipeline/editorial/checkRunner.js`, `scripts/migrations/114-extract-scenes-shot-grammar.js`, #1315)
+ - **Digital Twin federation now syncs your *whole* identity — taste profile, documents, and autobiography — not just the four core files.** The `digitalTwin` sync category only ever transferred `identity` / `chronotype` / `longevity` / `feedback`, so a peer could read **"Digital Twin: synced"** while your taste questionnaire, soul documents, and autobiography stories never crossed between machines (they were never wired into the snapshot at all). The snapshot now covers everything under `data/digital-twin/`: the **taste profile** (responses union per section by `questionId`, LWW — answers given on either machine survive), **meta.json** (documents/test-histories/personas union by id, enrichment deep-unioned, settings fill-missing), the **`.md` documents** themselves (shipped by filename, written **add-only** so a local doc is never overwritten — with a path-traversal guard on peer-supplied names), and the **autobiography** (stories union by id with LWW, prompt schedule stays machine-local). The merge is additive and key-presence-guarded, so an older peer that still sends only the four legacy keys can't blank out the new data, and no schemaVersions gate is needed (digitalTwin stays unversioned). The "Digital Twin" sync-category description in the Instances UI now reflects the full coverage. (`server/services/digital-twin-sync.js`, `server/services/dataSync.js`, `client/src/pages/Instances.jsx`)
+ - **[issue-1312] Editorial check flags cast representation & balance — Bechdel signal, dialogue share, screen-time skew.** A new **Cast representation & balance** check (Create → Editorial Checks) surfaces three coarse, computable casting signals so a lopsided cast doesn't slip by unnoticed: a **Bechdel co-presence signal** (does *any* scene put two or more non-male characters on the page together — the structural precondition for two women talking?), **dialogue share** (does one character dominate the spoken lines — e.g. 80% of all attributed dialogue?), and **screen-time balance** (is the appearing named cast strongly skewed toward one gender?). Gender is inferred only from each character's canon *pronouns* field — characters with absent or ambiguous pronouns are left out of the gender-dependent signals rather than guessed — and the co-presence signal reads your reverse-outline scene segmentation, so it stays silent until an outline records who's on the page. Every signal is advisory (representation is an authorial choice) and independently toggleable + threshold-configurable, and the whole check is deterministic — no model call, no new stage prompt. Findings render as `Casting` notes in the manuscript editor. (#1312)
+
+ - **Digital Twin federation now syncs your social accounts and analyzed personality traits too.** Two pieces of the identity dataset were still being left behind by peer sync. **Social accounts** (`data/digital-twin/social-accounts.json` — your own GitHub/X/LinkedIn/etc. accounts) were owned by an isolated service and never wired into the snapshot at all, so they never crossed between machines. They now sync as part of the `digitalTwin` category — accounts union by id with LWW on `updatedAt`, so an account added on either machine survives and the more-recently-edited copy wins a collision; the write routes through the owning service's cache-invalidate + change-event so the UI reflects synced accounts immediately. Separately, the **analyzed personality-trait confidence** block in `meta.json` (the Big-Five + values/communication/decision-making/boundaries/identity dimension scores, gaps, and `lastCalculated`) was present in the file but **`mergeMeta` never merged it** — so a machine that had run the trait analysis couldn't share it, and the receiving peer would have had to reprocess from scratch. The confidence block now merges **max-per-dimension** (the scores accumulate monotonically as enrichment answers are processed, so the max loses no analysis from either machine), recomputes `overall` as the mean of the merged dimensions, and carries `gaps`/`lastCalculated` from the more-recently-calculated side. Both merges are additive and key-presence-guarded, so an older peer that sends neither can't blank the local data. (`server/services/digital-twin-sync.js`)
- **[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-1313] Editorial check flags over-stuffed comic panels (lettering density / balloon load).** A new **Comic lettering density / balloon load** check (Create → Editorial Checks) reads each issue's comic script and counts the lettering load the art has to make room for — the #1 reader gripe in comics being a wall of text crammed into one panel. It flags **over-stuffed balloons** (a single balloon past ~25 words), **over-stuffed panels** (more than ~50 words of dialogue + caption + SFX, or more than ~3 balloons fighting for room), and **text-heavy pages** whose total lettering would overwhelm the illustration — all thresholds configurable, with severity scaled by how far over the limit a panel runs and a fix suggestion (split the balloon, move to a caption, or break into another panel). Findings render as `Lettering` notes in the manuscript editor anchored to the issue/page/panel; the same accounting also surfaces **inline in the comic-script stage**, so over-stuffed pages warn you as you edit without waiting for an editorial-checks run. The check is deterministic — no model needed. (`server/lib/editorial/letteringDensity.js`, `server/lib/editorial/checkRegistry.js`, `client/src/lib/letteringDensity.js`, `client/src/components/pipeline/stages/ComicScriptStage.jsx`, #1313)
- **[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)
- **[issue-1306] Line-edit / copy-edit pass — eight prose-tic editorial checks.** A bundle of deterministic copy-edit checks (Create → Editorial Checks) that catch the most common reader pet peeves and editorial red ink, each independently toggleable + configurable: **Filter words** (distancing verbs — saw/felt/noticed/began-to), **Crutch / filler words** (just/really/very/suddenly/"in order to"; bare "that" behind a toggle so grammatical "that" doesn't swamp the count), **Adverb overuse** (`-ly` adverbs, with adverb-laden dialogue tags — "said angrily" — flagged at higher severity), **Passive voice** (be-verb + past-participle heuristic, advisory), **Repeated gestures / body-part autonomy** (a gesture tally across the manuscript — nodded/smiled/shrugged — plus detached body parts that act on their own, "her eyes followed him across the room"), **Word repetition / echoes** (a distinctive word repeated within a window, plus repeated sentence openers — "He… He… He…"), and **Sentence rhythm & variety** (monotonous, uniform-length sentences). All are density-scaled — one "just" is fine, forty is a tic — with house-style allow/extra word lists and per-check thresholds, and ship sensible defaults so they don't drown the author. A ninth, LLM-judged sibling — **Telling-not-showing emotion** ("she was sad" → dramatize) — handles the false-positive-prone case a keyword scan can't, via a new stage prompt (`pipeline-editorial-telling-emotion`) that migrates for existing installs (110). The pure scanners live in `server/lib/editorial/proseTics.js` + `repetition.js` (no new deps). Reading-grade level is already covered by the existing `style.reading-level` check. (`server/lib/editorial/{proseTics,repetition,checkRegistry}.js`, `scripts/migrations/110-editorial-telling-emotion-stage.js`, #1306)
diff --cc scripts/migrations/117-editorial-comic-page-turn-stage.js
index d732a39b7d,0000000000..d732a39b7d
mode 100644,000000..100644
--- a/scripts/migrations/117-editorial-comic-page-turn-stage.js
+++ b/scripts/migrations/117-editorial-comic-page-turn-stage.js
diff --cc scripts/migrations/117-editorial-comic-page-turn-stage.test.js
index 50c94686c4,0000000000..f86441ffa0
mode 100644,000000..100644
--- a/scripts/migrations/117-editorial-comic-page-turn-stage.test.js
+++ b/scripts/migrations/117-editorial-comic-page-turn-stage.test.js
@@@ -1,86 -1,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';
++import migration from './117-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
++// First-shipment seed migration (mirrors 110–116) — 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', () => {
++describe('migration 117 — 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-'));
++ rootDir = mkdtempSync(join(tmpdir(), 'migration-117-'));
+ 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 --cc server/lib/editorial/README.md
index d9ec388c0b,0ed639471c..2e0f02fcb6
--- a/server/lib/editorial/README.md
+++ b/server/lib/editorial/README.md
@@@ -103,6 -132,7 +132,8 @@@ runner-injected `ctx.callInlineLLM` (a
| `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. |
+ | `shotContinuity.js` | Pure, dependency-free storyboard shot-continuity primitives for the deterministic `visual.shot-continuity` check (#1315): `findAxisReversals` (180°-rule axis flips across a continuity-linked shot pair using `screenDirection`) and `findShotTypeMonotony` (a scene whose classified shots all share one `shotType`). Reads the shot-grammar fields from `server/lib/shotGrammar.js`. The judgment cases (eyeline match, appearance/prop continuity) are LLM-sibling follow-ups. |
+ | `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 `attributeDialogueByOwner` (the coarse per-character dialogue-line tally behind `cast.representation-balance`'s dialogue-share signal, #1312 — credits each quoted paragraph to the first owner named in its beat) and 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. |
+ | `letteringDensity.js` | Pure, dependency-free comic lettering-density primitives for `comic.lettering-density` (#1313): `countWords`, `panelLetteringMetrics` (per-panel balloon/caption/SFX word + balloon tally over the `comicScriptParser` output), `analyzeComicLettering` (flags balloons/panels/pages over the configurable thresholds in `DEFAULT_LETTERING_THRESHOLDS`), `overflowSeverity` (severity scaled by how far over the limit), and `sanitizeLetteringThresholds`. Mirrored to `client/src/lib/letteringDensity.js` for the comic-script stage's inline warnings — keep the two in sync. |
| `index.js` | Barrel re-export of the above. |
diff --cc server/lib/editorial/checkRegistry.js
index e64e846522,003743c3bf..9c814525a0
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@@ -43,11 -48,7 +48,12 @@@ import
findRepeatedOpeners,
measureSentenceRhythm,
} from './repetition.js';
+import {
+ analyzePanelRhythm,
+ comicPageTurnSummary,
+ authoredRevealSummary,
+} from './comicPacing.js';
+ import { findAxisReversals, findShotTypeMonotony } from './shotContinuity.js';
export const CHECK_SCOPES = Object.freeze(['series', 'issue', 'scene', 'noun']);
export const CHECK_KINDS = Object.freeze(['deterministic', 'llm']);
@@@ -91,12 -92,23 +97,27 @@@ 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.
+ // - 'storyboard.shots' — the per-issue storyboard shot lists
+ // (`stages.storyboards.scenes[].shots[]`) the
+ // visual-continuity check (#1315) reasons over:
+ // each shot carries `shotType` / `screenDirection`
+ // / `continuityFromShotId` (server/lib/shotGrammar.js).
+ // Served off the already-loaded `ctx.issues` (no
+ // extra I/O); the runner injects `ctx.storyboardScenes`
+ // (a flat list of `{ issueNumber, scene }` for every
+ // issue that has storyboard scenes).
+ // - 'comicScript' — every issue's AUTHORITATIVE comic content, keyed by
+ // issue number: the edited comic-pages split
+ // (`stages.comicPages.pages[]`) when present, else the
+ // generated `stages.comicScript.output`. The
+ // lettering-density check (#1313) counts per-panel/per-page
-// word + balloon load over it. The runner fingerprints the
-// lettering-relevant fields so a finding goes stale when the
-// comic text (not the prose manuscript) is edited.
++// word + balloon load over it; the comic-pacing checks
++// (#1314) read the same parsed page/panel structure for
++// splash usage, panel rhythm, and page-turn beat placement.
++// Both read it via the shared `comicLetteringIssues(ctx.issues)`
++// projection (`[{ number, pages }]`). The runner fingerprints
++// the lettering-relevant fields so a finding goes stale when
++// the comic text (not the prose manuscript) is edited.
export const EDITORIAL_SOURCES = Object.freeze([
'manuscript',
'canon',
@@@ -295,17 -309,69 +318,80 @@@ export const PLOT_STRUCTURE_STAGE = 'pi
// 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
++// setup-data.js) and migrates to existing installs via migration 117 (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';
+
+ // Stage name for the theme-coherence / thematic-throughline LLM check (#1317).
+ // Ships in data.reference/prompts/stages/ + stage-config.json (fresh installs via
+ // setup-data.js) and migrates to existing installs via migration 115 (boot runs
+ // migrations but NOT setup-data, so the migration is required). Reads the stitched
+ // manuscript plus the AUTHORED arc themes (series.arc.themes) and the reverse-outline
+ // scene map, and reconciles whether each declared theme is set up / complicated /
+ // paid off — surfacing stated-but-undramatized themes, dropped themes, a strong
+ // emergent theme not in the arc, and a climax that resolves plot but not theme.
+ export const THEME_COHERENCE_STAGE = 'pipeline-editorial-theme-coherence';
+
+ // Render the authored arc themes (#1317) into a compact text block the
+ // theme-coherence check passes alongside the manuscript, so the model reconciles
+ // whether the prose actually sets up / complicates / pays off each DECLARED theme
+ // (vs. stating it but never dramatizing it, or dropping it after the opening).
+ // Pure + deterministic so it's unit-testable and its token cost can be counted
+ // into the per-chunk overhead. Returns '' when no themes are authored (the
+ // prompt's `{{#declaredThemes}}` section then renders nothing and the check still
+ // runs to detect a strong emergent theme).
+ export function declaredThemesSummary(themes) {
+ const lines = (Array.isArray(themes) ? themes : [])
+ .map((t) => (typeof t === 'string' ? t.trim() : ''))
+ .filter(Boolean)
+ .map((t) => `- ${t}`);
+ if (!lines.length) return '';
+ return `Declared themes (authored on the story arc):\n${lines.join('\n')}`;
+ }
+
+ // Stage name for the unmodeled-proper-nouns LLM check (#1412). Ships in
+ // data.reference/prompts/stages/ + stage-config.json (fresh installs via
+ // setup-data.js) and migrates to existing installs via migration 116 (boot runs
+ // migrations but NOT setup-data, so the migration is required). Reads the stitched
+ // manuscript plus the canon roster (names + aliases) and asks the model to surface
+ // capitalized proper nouns used as apparent CHARACTER names that are absent from
+ // canon — the LLM-assisted half of roster economy (#1292) the deterministic
+ // `roster.economy` scan deliberately leaves alone (it can't tell a person from a
+ // place/org/brand/honorific).
+ export const UNMODELED_NAMES_STAGE = 'pipeline-editorial-unmodeled-names';
+
+ // 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
+ // surfaces apparent character names absent from this list. Pure + deterministic so
+ // it's unit-testable and its token cost can be counted into the per-chunk overhead.
+ // Returns '' when no canon character has a usable name (the prompt's
+ // `{{#knownCharacters}}` section then renders nothing and EVERY named proper noun in
+ // the prose is a candidate — exactly right when the bible is empty). Reuses
+ // `characterNameTokens` so name + aliases render with the same trim/de-dup the
+ // deterministic matcher uses.
+ export function canonRosterNamesSummary(canon) {
+ const chars = Array.isArray(canon?.characters) ? canon.characters : [];
+ const lines = [];
+ for (const c of chars) {
+ // Require a real name — an alias-only row isn't a named character (mirrors
+ // buildRosterAppearances, which skips nameless rows). characterNameTokens then
+ // returns the trimmed name first, followed by de-duped aliases.
+ if (!c || typeof c.name !== 'string' || !c.name.trim()) continue;
+ const [name, ...aliases] = characterNameTokens(c);
+ lines.push(aliases.length ? `- ${name} (also: ${aliases.join(', ')})` : `- ${name}`);
+ }
+ if (!lines.length) return '';
+ return `Known characters (already in the story bible — do NOT flag these or their aliases):\n${lines.join('\n')}`;
+ }
+
// 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
@@@ -3691,133 -4480,6 +4500,139 @@@ 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,
++ // Needs at least one issue with analyzable comic content — shares the
++ // cheap presence test with the lettering-density check (#1313).
++ gate: (ctx) => hasComicContent(ctx.issues),
+ run: (ctx) => {
+ const cfg = ctx.config || {};
+ const max = cfg.maxFindings ?? 20;
- const rows = Array.isArray(ctx.comicScripts) ? ctx.comicScripts : [];
++ // Reuse the shared parsed-pages projection (#1313) the lettering check reads
++ // off ctx.issues — prefers the edited comic-pages split over the generated
++ // script — so both comic checks analyze identical page/panel structure.
++ const rows = comicLetteringIssues(ctx.issues);
+ const findings = [];
- for (const { issueNumber, pages } of rows) {
++ for (const { number, 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 location = Number.isInteger(number) ? `Issue ${number}` : 'Comic script';
++ const issueNum = Number.isInteger(number) ? number : 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,
++ // Needs at least one issue with analyzable comic content — shares the
++ // cheap presence test with the lettering-density check (#1313).
++ gate: (ctx) => hasComicContent(ctx.issues),
+ 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 : [];
++ // Same shared parsed-pages projection (#1313) the panel-rhythm + lettering
++ // checks read off ctx.issues.
++ const rows = comicLetteringIssues(ctx.issues);
+ const findings = [];
- for (const { issueNumber, pages } of rows) {
++ for (const { number, pages } of rows) {
+ if (ctx.signal?.aborted || findings.length >= max) break;
- const pageLayout = comicPageTurnSummary(pages, issueNumber);
++ const pageLayout = comicPageTurnSummary(pages, number);
+ 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 issueNum = Number.isInteger(number) ? number : 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 --cc server/lib/editorial/checkRegistry.test.js
index 47466b2f07,afda9bc946..4cb50f49f0
--- a/server/lib/editorial/checkRegistry.test.js
+++ b/server/lib/editorial/checkRegistry.test.js
@@@ -2979,110 -3268,256 +3268,366 @@@ 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.
++ // The comic-pacing checks read each issue's pages off ctx.issues via the shared
++ // `comicLetteringIssues` projection — which prefers an edited `comicPages.pages`
++ // split (already panelized) over the generated script. 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) });
++ const issue = (number, counts) => ({ number, stages: { comicPages: { 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', () => {
++ it('only runs when at least one issue has comic content', () => {
+ 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);
++ expect(check.gate({ issues: [] })).toBeFalsy();
++ expect(check.gate({ issues: undefined })).toBeFalsy();
++ expect(check.gate({ issues: [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])],
++ issues: [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])],
++ issues: [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])],
++ issues: [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])],
++ issues: [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])],
++ issues: [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);
+ });
+ });
+});
++
+ describe('comic.lettering-density — deterministic check (#1313)', () => {
+ const COMIC = 'comic.lettering-density';
+ // A canonical comic-script page with one over-stuffed balloon (60 words).
+ const stuffedScript = `## Page 1
+
+ Panel 1
+ **Description:** A crowded throne room.
+ **Dialogue:**
+ - KING: "${Array.from({ length: 60 }, (_, i) => `word${i}`).join(' ')}"
+ `;
+ const cleanScript = `## Page 1
+
+ Panel 1
+ **Description:** A quiet field.
+ **Dialogue:**
+ - ANYA: "We should go."
+ `;
+ const issue = (number, script) => ({ number, stages: { comicScript: { output: script } } });
+ const ctxFor = (issues, config = {}) => ({ issues, config, severityDefault: 'low' });
+
+ it('is a deterministic, issue-scoped check reading the comicScript source', () => {
+ const check = getCheck(COMIC);
+ expect(check.kind).toBe('deterministic');
+ expect(check.scope).toBe('issue');
+ expect(check.category).toBe('lettering');
+ expect(check.sources).toEqual(['comicScript']);
+ });
+
+ it('gate is false with no comic scripts, true when one has content', () => {
+ const check = getCheck(COMIC);
+ expect(check.gate(ctxFor([]))).toBe(false);
+ expect(check.gate(ctxFor([issue(1, '')]))).toBe(false);
+ expect(check.gate(ctxFor([issue(1, stuffedScript)]))).toBe(true);
+ });
+
+ it('flags an over-stuffed balloon and stamps the issue number + location', () => {
+ const findings = getCheck(COMIC).run(ctxFor([issue(7, stuffedScript)]));
+ expect(findings.length).toBeGreaterThan(0);
+ const balloon = findings.find((f) => f.problem.includes('balloon'));
+ expect(balloon).toBeTruthy();
+ expect(balloon.category).toBe('lettering');
+ expect(balloon.issueNumber).toBe(7);
+ expect(balloon.location).toContain('Issue 7');
+ expect(balloon.location).toContain('Page 1');
+ expect(balloon.severity).toBe('high'); // 60/25 = 2.4×
+ expect(balloon.anchorQuote).toContain('word0');
+ });
+
+ it('returns no findings for a well-lettered script', () => {
+ expect(getCheck(COMIC).run(ctxFor([issue(1, cleanScript)]))).toEqual([]);
+ });
+
+ it('honors configured thresholds', () => {
+ // cleanScript's single 3-word balloon trips only when the limit drops below 3.
+ expect(getCheck(COMIC).run(ctxFor([issue(1, cleanScript)], { maxWordsPerBalloon: 2 })))
+ .not.toEqual([]);
+ });
+
+ it('skips issues without a comic script and scans in issue-number order', () => {
+ const findings = getCheck(COMIC).run(ctxFor([issue(2, stuffedScript), issue(1, ''), issue(3, stuffedScript)]));
+ const issueNums = [...new Set(findings.map((f) => f.issueNumber))];
+ expect(issueNums).toEqual([2, 3]);
+ });
+
+ // The edited comicPages split is the source of truth once a script is split —
+ // edits there never flow back to comicScript.output, so the check must read it.
+ const overflowBalloon = { dialogue: [{ character: 'KING', line: Array.from({ length: 60 }, (_, i) => `w${i}`).join(' ') }] };
+ const cleanBalloon = { dialogue: [{ character: 'ANYA', line: 'Short line.' }] };
+ const withPages = (number, script, panels) => ({
+ number,
+ stages: { comicScript: { output: script }, comicPages: { pages: [{ panels }] } },
+ });
+
+ it('reads the edited comicPages split when present (it wins over comicScript.output)', () => {
+ // The raw script is clean, but the EDITED page added an over-stuffed balloon —
+ // the check must flag it (reading comicPages), not pass on the stale script.
+ const findings = getCheck(COMIC).run(ctxFor([withPages(5, cleanScript, [overflowBalloon])]));
+ expect(findings.some((f) => f.problem.includes('balloon'))).toBe(true);
+ expect(findings[0].issueNumber).toBe(5);
+ });
+
+ it('does NOT flag when the edited pages are clean even if the stale script was stuffed', () => {
+ // The user edited the over-stuffed script down to a clean page — no finding.
+ expect(getCheck(COMIC).run(ctxFor([withPages(5, stuffedScript, [cleanBalloon])]))).toEqual([]);
+ });
+
+ it('gate is true when only an edited comicPages split exists (no script output)', () => {
+ const ctx = ctxFor([{ number: 5, stages: { comicPages: { pages: [{ panels: [overflowBalloon] }] } } }]);
+ expect(getCheck(COMIC).gate(ctx)).toBe(true);
+ expect(getCheck(COMIC).run(ctx).length).toBeGreaterThan(0);
+ });
+ });
+
+ describe('cast.representation-balance — deterministic check (#1312)', () => {
+ const REP = 'cast.representation-balance';
+ const sec = (number, content) => ({ number, content });
+ const runRep = (canon, { sections = [], reverseOutline = [], config = {} } = {}) =>
+ getCheck(REP).run({
+ canon,
+ sections,
+ // The runner injects the stitched corpus as ctx.manuscript; mirror it here.
+ manuscript: sections.map((s) => s.content || '').join('\n\n'),
+ reverseOutline,
+ config,
+ severityDefault: 'low',
+ });
+ const dialogue = (findings) => findings.find((f) => f.location === 'Series dialogue');
+ const bechdel = (findings) => findings.find((f) => /Bechdel/.test(f.problem));
+ const screenTime = (findings) => findings.find((f) => /strongly skewed cast/.test(f.problem));
+ // Config that silences the two OTHER signals so a test can isolate one.
+ const only = (over) => ({ maxDialogueShare: 1, maxGenderShare: 1, bechdelSignal: false, ...over });
+
+ it('declares the expected scope / kind / sources', () => {
+ const c = getCheck(REP);
+ expect(c.kind).toBe('deterministic');
+ expect(c.scope).toBe('series');
+ expect(c.category).toBe('casting');
+ expect(c.needsManuscript).toBe(true);
+ expect(c.sources).toEqual(expect.arrayContaining(['manuscript', 'canon', 'reverseOutline']));
+ });
+
+ it('flags a dominating speaker by dialogue share', () => {
+ const canon = { characters: [{ name: 'Aria', pronouns: 'she/her' }, { name: 'Bram', pronouns: 'he/him' }] };
+ // 4 Aria lines, 1 Bram line → Aria = 80% of 5 attributed lines.
+ const content = [
+ '"One," said Aria.',
+ '"Two," said Aria.',
+ '"Three," said Aria.',
+ '"Four," said Aria.',
+ '"Five," said Bram.',
+ ].join('\n');
+ const findings = runRep(canon, {
+ sections: [sec(1, content)],
+ config: only({ maxDialogueShare: 0.6, minDialogueLines: 5 }),
+ });
+ const f = dialogue(findings);
+ expect(f).toBeTruthy();
+ expect(f.category).toBe('casting');
+ expect(f.severity).toBe('medium'); // 80% → escalated above the low floor
+ expect(f.problem).toMatch(/"Aria" speaks about 80%/);
+ });
+
+ it('skips the dialogue-share check below the minimum line floor', () => {
+ const canon = { characters: [{ name: 'Aria' }, { name: 'Bram' }] };
+ const content = '"Hi," said Aria.\n"Hey," said Bram.';
+ const findings = runRep(canon, {
+ sections: [sec(1, content)],
+ config: only({ maxDialogueShare: 0.4, minDialogueLines: 12 }),
+ });
+ expect(dialogue(findings)).toBeUndefined();
+ });
+
+ it('flags a missing Bechdel co-presence signal when no scene pairs non-male characters', () => {
+ const canon = {
+ characters: [
+ { name: 'Aria', pronouns: 'she/her' },
+ { name: 'Mara', pronouns: 'she/her' },
+ { name: 'Bram', pronouns: 'he/him' },
+ ],
+ };
+ // Aria only ever shares the page with Bram; Aria + Mara never co-present.
+ const reverseOutline = [
+ { heading: 'S1', charactersPresent: ['Aria', 'Bram'] },
+ { heading: 'S2', charactersPresent: ['Mara', 'Bram'] },
+ ];
+ const findings = runRep(canon, { reverseOutline, config: only({ bechdelSignal: true }) });
+ expect(bechdel(findings)).toBeTruthy();
+ });
+
+ it('passes the Bechdel signal when two non-male characters share a scene', () => {
+ const canon = {
+ characters: [
+ { name: 'Aria', pronouns: 'she/her' },
+ { name: 'Mara', pronouns: 'they/them' },
+ ],
+ };
+ const reverseOutline = [{ heading: 'S1', charactersPresent: ['Aria', 'Mara'] }];
+ const findings = runRep(canon, { reverseOutline, config: only({ bechdelSignal: true }) });
+ expect(bechdel(findings)).toBeUndefined();
+ });
+
+ it('stays silent on Bechdel when no scene presence is recorded', () => {
+ const canon = { characters: [{ name: 'Aria', pronouns: 'she/her' }, { name: 'Mara', pronouns: 'she/her' }] };
+ const findings = runRep(canon, { reverseOutline: [], config: only({ bechdelSignal: true }) });
+ expect(bechdel(findings)).toBeUndefined();
+ });
+
+ it('flags a strongly gender-skewed appearing cast', () => {
+ const canon = {
+ characters: [
+ { name: 'Al', pronouns: 'he/him' },
+ { name: 'Bo', pronouns: 'he/him' },
+ { name: 'Cy', pronouns: 'he/him' },
+ { name: 'Di', pronouns: 'he/him' },
+ { name: 'Eve', pronouns: 'she/her' },
+ ],
+ };
+ // All five appear; 4/5 = 80% male → over an 80%? No, must EXCEED. Use 0.7.
+ const content = 'Al, Bo, Cy, Di, and Eve all gathered at dawn.';
+ const findings = runRep(canon, {
+ sections: [sec(1, content)],
+ config: only({ maxGenderShare: 0.7 }),
+ });
+ const f = screenTime(findings);
+ expect(f).toBeTruthy();
+ expect(f.problem).toMatch(/80% are male/);
+ });
+
+ it('leaves unknown/ambiguous-pronoun characters out of the gender signals', () => {
+ const canon = {
+ characters: [
+ { name: 'Al', pronouns: 'he/him' },
+ { name: 'Bo' }, // no pronouns → unknown
+ { name: 'Cy', pronouns: 'she/he' }, // ambiguous → unknown
+ ],
+ };
+ const content = 'Al, Bo, and Cy gathered.';
+ // Only Al is gender-known → known < 2 → no screen-time finding.
+ const findings = runRep(canon, { sections: [sec(1, content)], config: only({ maxGenderShare: 0.5 }) });
+ expect(screenTime(findings)).toBeUndefined();
+ });
+
+ it('treats a primary+secondary set (she/they) as the primary gender, not ambiguous', () => {
+ // inferGender resolves "she/they" to female (a definite identity with a
+ // secondary set), unlike "she/he" which is genuinely ambiguous → unknown.
+ // Pin that contract via the screen-time signal: two she/they characters
+ // count as 2 known-female, so an all-female roster trips the skew.
+ const canon = {
+ characters: [
+ { name: 'Aria', pronouns: 'she/they' },
+ { name: 'Mara', pronouns: 'she/her' },
+ ],
+ };
+ const findings = runRep(canon, {
+ sections: [sec(1, 'Aria and Mara spoke at dawn.')],
+ config: only({ maxGenderShare: 0.7 }),
+ });
+ const f = screenTime(findings);
+ expect(f).toBeTruthy();
+ expect(f.problem).toMatch(/100% are female/);
+ });
+
+ it('gate requires at least one named canon character', () => {
+ const c = getCheck(REP);
+ expect(c.gate({ canon: { characters: [] } })).toBeFalsy();
+ expect(c.gate({ canon: { characters: [{ name: 'Aria' }] } })).toBe(true);
+ });
+
+ it('tolerates empty canon / sections / outline without throwing', () => {
+ expect(() => runRep({ characters: [] })).not.toThrow();
+ expect(runRep({ characters: [{}, { name: '' }] }, { sections: [sec(1, 'x')] })).toEqual([]);
+ });
+ });
diff --cc server/lib/editorial/index.js
index 58709cfb59,46fc834949..245c1b8b61
--- a/server/lib/editorial/index.js
+++ b/server/lib/editorial/index.js
@@@ -2,9 -2,9 +2,10 @@@
// (#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 './letteringDensity.js';
export * from './nameSimilarity.js';
export * from './proseTics.js';
export * from './repetition.js';
diff --cc server/services/pipeline/editorial/checkRunner.js
index f2b5a16f55,dc74a668c8..7fe9ccfbfd
--- a/server/services/pipeline/editorial/checkRunner.js
+++ b/server/services/pipeline/editorial/checkRunner.js
@@@ -410,11 -485,14 +485,14 @@@ export async function getReviewWithStal
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).
+ // Issues are fetched here only when a storyboard-shots (#1315) OR comic-script
- // (#1313) finding needs re-fingerprinting — both derive from the issue records,
- // so a single gated fetch serves both. Mirrors the other per-source I/O gates.
++ // (#1313/#1314) finding needs re-fingerprinting — both derive from the issue
++ // records, so a single gated fetch serves both. Mirrors the other per-source I/O gates.
+ const needsStoryboards = evaluable.some((c) => checkSources(checkFor(c.checkId)).includes('storyboard.shots'));
const needsComicScript = evaluable.some((c) => checkSources(checkFor(c.checkId)).includes('comicScript'));
+ const needsIssues = needsStoryboards || needsComicScript;
const series = await getSeries(seriesId);
- const [sections, canon, outline, editorial, comicIssues] = await Promise.all([
+ const [sections, canon, outline, editorial, issues] = await Promise.all([
needsManuscript ? collectManuscriptSections(seriesId) : Promise.resolve([]),
getSeriesCanon(series),
needsReverseOutline ? getReverseOutline(seriesId).catch(() => null) : Promise.resolve(null),
diff --cc server/services/pipeline/editorial/checkRunner.test.js
index 819a5383d8,cc38574021..8700233361
--- a/server/services/pipeline/editorial/checkRunner.test.js
+++ b/server/services/pipeline/editorial/checkRunner.test.js
@@@ -97,8 -101,6 +102,7 @@@ beforeEach(() =>
resolveStageContext.mockClear();
collectManuscriptSections.mockClear();
getSeriesCanon.mockClear();
+ listIssues.mockClear();
- listIssues.mockResolvedValue([]);
});
describe('runEditorialChecks', () => {
@@@ -146,31 -148,6 +150,31 @@@
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([
++ it('feeds the comic-pacing checks off each issue\'s comic script (#1314)', async () => {
++ // Issue 1 is two splash pages in a row — the deterministic comic.panel-rhythm
++ // check flags the back-to-back splash run. Both comic checks read the same
++ // parsed pages off ctx.issues via the shared comicLetteringIssues projection.
++ issuesState = [
+ { 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([
++ it('produces no comic-pacing findings when no comic-pacing check is enabled', async () => {
++ issuesState = [
+ { 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).
++ ];
++ // Only the naming check runs — its gate never reads comic content, so the
++ // comic checks stay 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.