Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-1313]): comic lettering-density editorial check + inline stage warnings
[._.]/ Adam Eivyfb87a9767422
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 8a54964689..0679bdd789 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -5,6 +5,7 @@- **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-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 --git a/client/src/components/pipeline/manuscript/constants.js b/client/src/components/pipeline/manuscript/constants.jsindex ee7156a602..e74b7dea3b 100644--- a/client/src/components/pipeline/manuscript/constants.js+++ b/client/src/components/pipeline/manuscript/constants.js@@ -42,6 +42,9 @@ export const CATEGORY_LABEL = {continuity: 'Continuity',style: 'Style',exposition: 'Exposition',+ // Comic lettering-density findings (#1313): over-stuffed balloons/panels/pages+ // from the comic.lettering-density editorial check.+ lettering: 'Lettering',other: 'Note',};diff --git a/client/src/components/pipeline/stages/ComicScriptStage.jsx b/client/src/components/pipeline/stages/ComicScriptStage.jsxindex ab182383c6..ee3095a411 100644--- a/client/src/components/pipeline/stages/ComicScriptStage.jsx+++ b/client/src/components/pipeline/stages/ComicScriptStage.jsx@@ -40,6 +40,30 @@ import {readPipelineImageSettings,pipelineImageCfgToRenderOpts,} from '../../../lib/pipelineImageDefaults';+import { analyzeComicLettering } from '../../../lib/letteringDensity';++// Severity → Tailwind text color for the inline lettering warnings. Mirrors the+// editorial check's overflow-scaled severity.+const LETTERING_TONE = { high: 'text-port-error', medium: 'text-port-warning', low: 'text-gray-400' };++// A short, page-row-scoped label for a lettering violation (the same accounting+// the server `comic.lettering-density` check surfaces in the manuscript editor —+// here it's shown inline as the author edits, using the default thresholds).+function letteringWarningLabel(v) {+ switch (v.kind) {+ case 'balloon-words':+ return `Panel ${v.panelNumber}: a balloon runs ${v.count} words (over ~${v.threshold})`;+ case 'caption-words':+ return `Panel ${v.panelNumber}: a caption box runs ${v.count} words (over ~${v.threshold})`;+ case 'panel-words':+ return `Panel ${v.panelNumber}: ${v.count} words of lettering (over ~${v.threshold})`;+ case 'panel-balloons':+ return `Panel ${v.panelNumber}: ${v.count} balloons (over ~${v.threshold})`;+ case 'page-words':+ default:+ return `Page total ${v.count} words of lettering (over ~${v.threshold}) — would overwhelm the art`;+ }+}// Legacy records (pre-proof/final split) carry `imageJobId`/`filename` at// the record root; surface those as the proof slot so the UI keeps showing@@ -765,6 +789,14 @@ function PageRow({() => page.rawText || panelsToMarkdown(page.panels, pageIndex + 1),[page.rawText, page.panels, pageIndex],);+ // Inline lettering-density warnings (#1313): the same pure accounting the+ // server `comic.lettering-density` editorial check runs, computed here from the+ // parsed panels so over-stuffed panels surface in the comic-script stage itself,+ // not only after an editorial-checks run. Uses the default thresholds.+ const letteringWarnings = useMemo(+ () => analyzeComicLettering([{ panels: page.panels }]),+ [page.panels],+ );const [draft, setDraft] = useState(rawText);const [saving, setSaving] = useState(false);const [renderingProof, setRenderingProof] = useState(false);@@ -908,6 +940,17 @@ function PageRow({)}</div></div>+ {letteringWarnings.length > 0 ? (+ <div className="px-3 pt-2">+ <ul className="rounded border border-port-warning/30 bg-port-warning/5 px-2.5 py-1.5 space-y-0.5">+ {letteringWarnings.map((v, i) => (+ <li key={i} className={`text-[11px] ${LETTERING_TONE[v.severity] || 'text-gray-400'}`}>+ ⚠ Lettering — {letteringWarningLabel(v)}+ </li>+ ))}+ </ul>+ </div>+ ) : null}<div className="grid md:grid-cols-2 gap-3 p-3"><textareavalue={draft}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex f00c00244b..ff955b9ea9 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -79,6 +79,7 @@ grep -i "what you want to do" client/src/lib/README.md| `healthProvenance.js` | `PROVENANCE_LEVELS` / `getProvenanceLevel(level)` — the `data-backed`/`inferred`/`experimental`/`speculative` trust taxonomy (label, tone, description, "what would change this?" copy) behind the `ProvenanceChip` source-style chips on MeatSpace / genome / death-clock / longevity views. Pure data; the chip component maps tone→color and id→icon. || `joinInfluenceList.js` | Mirror of `joinInfluenceList` in server universe builder. || `localLlmTargetKey.js` | `localLlmTargetKey({ backend, modelId })` — stable string key for a local-LLM compare target. Shared by the LocalLlmTab checkbox grid and the LocalLlmPlayground compare URL so a delimiter change can't desync the round-trip. |+| `letteringDensity.js` | `analyzeComicLettering` / `panelLetteringMetrics` / `countWords` / `overflowSeverity` / `DEFAULT_LETTERING_THRESHOLDS` — comic lettering-density accounting over parsed comic pages, powering the comic-script stage's inline over-stuffed-panel warnings (#1313). Byte-for-byte mirror of `server/lib/editorial/letteringDensity.js` (the server `comic.lettering-density` check is authoritative). Pure/DOM-free. || `loopbackHost.js` | `isLoopbackHost(host)` / `isLoopbackOrigin()` / `describeMicAvailability()` — Secure Context / loopback-origin heuristics. Use these in any new mic, clipboard, or `getUserMedia`-gated surface; matches the full `127.0.0.0/8` range, IPv6 `::1`, and the browser-bracketed `[::1]` form. || `manuscriptAnchors.js` | `locateFind` / `locateAnchors` / `buildHighlightSegments` — resolve editorial-comment `anchorQuote`s to spans in manuscript text and tile the text into plain + highlighted (severity-toned) segments for the Manuscript editor's in-context feedback. Mirrors the nearest-occurrence `locateFind` in `server/services/pipeline/manuscriptFix.js`. || `manuscriptFormat.js` | `formatManuscript(text, stageId)` / `REFLOW_STAGES` — normalize a manuscript section's text for the editor's "Format" button: undo PDF-paste artifacts (stylized drop-cap split onto its own line, hyphen-split words, trailing whitespace, runaway blank lines) for every stage, and additionally reflow soft-wrapped lines back into paragraphs for `prose` only (scripts keep their structural line breaks). Pure/DOM-free. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 29d47c4377..4394c6f55f 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -23,6 +23,7 @@ export * from './imageGenBackends.js';export * from './imageGenDefaults.js';export * from './imageGenResolutions.js';export * from './importerDeepLink.js';+export * from './letteringDensity.js';export * from './issueLength.js';export * from './pipelineImageDefaults.js';export * from './reverseOutlineGrid.js';diff --git a/client/src/lib/letteringDensity.js b/client/src/lib/letteringDensity.jsnew file mode 100644index 0000000000..71dc4c037b--- /dev/null+++ b/client/src/lib/letteringDensity.js@@ -0,0 +1,193 @@+// Mirror of server/lib/editorial/letteringDensity.js (#1313) — the comic+// lettering-density accounting (`countWords`, `panelLetteringMetrics`,+// `analyzeComicLettering`, `overflowSeverity`, `sanitizeLetteringThresholds`,+// `DEFAULT_LETTERING_THRESHOLDS`) must match the server side exactly. The server+// editorial check (`comic.lettering-density`) is authoritative and tested in+// server/lib/editorial/letteringDensity.test.js; this copy powers the comic-script+// stage's INLINE per-page warnings so the author sees over-stuffed panels while+// editing — without a round-trip through an editorial-checks run. Port any logic+// change to both sides verbatim; commentary is scoped per side.+//+// A "balloon" is a discrete lettering element: each dialogue entry is one, and+// each caption box is one (the parser folds repeated captions into one+// newline-joined string, so each non-empty line counts). SFX counts toward the+// panel/page WORD load but is not a balloon.++export const DEFAULT_LETTERING_THRESHOLDS = Object.freeze({+ maxWordsPerBalloon: 25,+ maxWordsPerPanel: 50,+ maxBalloonsPerPanel: 3,+ maxWordsPerPage: 150,+});++const LETTERING_SEVERITIES = ['high', 'medium', 'low'];++// Count words in a free-text lettering string (runs of non-whitespace). 0 for+// non-strings.+export function countWords(text) {+ if (typeof text !== 'string') return 0;+ const matched = text.trim().match(/\S+/g);+ return matched ? matched.length : 0;+}++// Severity scaled by how far over the threshold a count runs: ≥2× → high, ≥1.4×+// → medium, else low.+export function overflowSeverity(count, threshold) {+ if (!(threshold > 0)) return 'medium';+ const ratio = count / threshold;+ if (ratio >= 2) return 'high';+ if (ratio >= 1.4) return 'medium';+ return 'low';+}++// Merge a (possibly partial) config over the defaults, guarding each field. A+// non-positive threshold falls back to the default.+export function sanitizeLetteringThresholds(config) {+ const c = config && typeof config === 'object' ? config : {};+ const pick = (key) => {+ const v = c[key];+ if (typeof v === 'number' && Number.isFinite(v) && v > 0) return v;+ return DEFAULT_LETTERING_THRESHOLDS[key];+ };+ return {+ maxWordsPerBalloon: pick('maxWordsPerBalloon'),+ maxWordsPerPanel: pick('maxWordsPerPanel'),+ maxBalloonsPerPanel: pick('maxBalloonsPerPanel'),+ maxWordsPerPage: pick('maxWordsPerPage'),+ };+}++// Per-panel lettering metrics from a parsed panel+// (`{ description, caption, dialogue: [{ character, line }], sfx }`).+export function panelLetteringMetrics(panel) {+ const dialogue = Array.isArray(panel?.dialogue) ? panel.dialogue : [];+ const balloons = dialogue.map((d) => {+ const line = typeof d?.line === 'string' ? d.line : '';+ return {+ speaker: typeof d?.character === 'string' ? d.character.trim() : '',+ words: countWords(line),+ line,+ };+ });+ const caption = typeof panel?.caption === 'string' ? panel.caption : '';+ const captionBoxes = caption+ .split('\n')+ .map((l) => l.trim())+ .filter(Boolean)+ .map((text) => ({ words: countWords(text), text }));+ const sfx = typeof panel?.sfx === 'string' ? panel.sfx : '';+ const dialogueWords = balloons.reduce((sum, b) => sum + b.words, 0);+ const captionWords = captionBoxes.reduce((sum, b) => sum + b.words, 0);+ const sfxWords = countWords(sfx);+ return {+ balloons,+ captionBoxes,+ balloonCount: balloons.length + captionBoxes.length,+ dialogueWords,+ captionWords,+ sfxWords,+ totalWords: dialogueWords + captionWords + sfxWords,+ };+}++function firstLetteringText(metrics) {+ const balloon = metrics.balloons.find((b) => b.line.trim());+ if (balloon) return balloon.line.trim();+ const box = metrics.captionBoxes.find((b) => b.text);+ return box ? box.text : '';+}++// Analyze the parsed pages of ONE comic script for lettering overflows. Returns+// a flat list of violations: { kind, pageNumber, panelNumber?, balloonIndex?,+// speaker?, count, threshold, limitLabel, severity, anchorQuote }.+export function analyzeComicLettering(pages, config) {+ const t = sanitizeLetteringThresholds(config);+ const list = Array.isArray(pages) ? pages : [];+ const violations = [];+ list.forEach((page, pageIdx) => {+ const pageNumber = pageIdx + 1;+ const panels = Array.isArray(page?.panels) ? page.panels : [];+ let pageWords = 0;+ panels.forEach((panel, panelIdx) => {+ const panelNumber = panelIdx + 1;+ const m = panelLetteringMetrics(panel);+ pageWords += m.totalWords;++ m.balloons.forEach((balloon, balloonIndex) => {+ if (balloon.words > t.maxWordsPerBalloon) {+ violations.push({+ kind: 'balloon-words',+ pageNumber,+ panelNumber,+ balloonIndex,+ speaker: balloon.speaker,+ count: balloon.words,+ threshold: t.maxWordsPerBalloon,+ limitLabel: 'words in one balloon',+ severity: overflowSeverity(balloon.words, t.maxWordsPerBalloon),+ anchorQuote: balloon.line.trim(),+ });+ }+ });++ // Caption boxes count as balloons, so an over-stuffed caption trips the same+ // per-balloon word ceiling as a speech balloon.+ m.captionBoxes.forEach((box, boxIndex) => {+ if (box.words > t.maxWordsPerBalloon) {+ violations.push({+ kind: 'caption-words',+ pageNumber,+ panelNumber,+ boxIndex,+ count: box.words,+ threshold: t.maxWordsPerBalloon,+ limitLabel: 'words in one caption box',+ severity: overflowSeverity(box.words, t.maxWordsPerBalloon),+ anchorQuote: box.text,+ });+ }+ });++ if (m.totalWords > t.maxWordsPerPanel) {+ violations.push({+ kind: 'panel-words',+ pageNumber,+ panelNumber,+ count: m.totalWords,+ threshold: t.maxWordsPerPanel,+ limitLabel: 'words in one panel',+ severity: overflowSeverity(m.totalWords, t.maxWordsPerPanel),+ anchorQuote: firstLetteringText(m),+ });+ }++ if (m.balloonCount > t.maxBalloonsPerPanel) {+ violations.push({+ kind: 'panel-balloons',+ pageNumber,+ panelNumber,+ count: m.balloonCount,+ threshold: t.maxBalloonsPerPanel,+ limitLabel: 'balloons in one panel',+ severity: overflowSeverity(m.balloonCount, t.maxBalloonsPerPanel),+ anchorQuote: firstLetteringText(m),+ });+ }+ });++ if (pageWords > t.maxWordsPerPage) {+ violations.push({+ kind: 'page-words',+ pageNumber,+ count: pageWords,+ threshold: t.maxWordsPerPage,+ limitLabel: 'words on one page',+ severity: overflowSeverity(pageWords, t.maxWordsPerPage),+ anchorQuote: '',+ });+ }+ });+ return violations;+}++export { LETTERING_SEVERITIES };diff --git a/client/src/lib/letteringDensity.test.js b/client/src/lib/letteringDensity.test.jsnew file mode 100644index 0000000000..847e145be4--- /dev/null+++ b/client/src/lib/letteringDensity.test.js@@ -0,0 +1,49 @@+import { describe, it, expect } from 'vitest';+import {+ countWords,+ overflowSeverity,+ panelLetteringMetrics,+ analyzeComicLettering,+} from './letteringDensity';++// Mirror of server/lib/editorial/letteringDensity.js — the server test is the+// authoritative contract; this covers the client copy used by the comic-script+// stage's inline warnings so a drift in the mirror is caught here too.++const balloon = (character, n) => ({ character, line: Array.from({ length: n }, (_, i) => `w${i}`).join(' ') });++describe('letteringDensity (client mirror)', () => {+ it('countWords counts whitespace tokens, 0 for non-strings', () => {+ expect(countWords('one two three')).toBe(3);+ expect(countWords(null)).toBe(0);+ });++ it('overflowSeverity scales by overflow ratio', () => {+ expect(overflowSeverity(26, 25)).toBe('low');+ expect(overflowSeverity(35, 25)).toBe('medium');+ expect(overflowSeverity(50, 25)).toBe('high');+ });++ it('panelLetteringMetrics counts dialogue + caption + SFX and balloons', () => {+ const m = panelLetteringMetrics({+ dialogue: [balloon('A', 4), balloon('B', 2)],+ caption: 'Box one.\nBox two.',+ sfx: 'BOOM',+ });+ expect(m.totalWords).toBe(6 + 4 + 1);+ expect(m.balloonCount).toBe(4); // 2 dialogue + 2 caption boxes+ });++ it('analyzeComicLettering flags an over-stuffed balloon', () => {+ const v = analyzeComicLettering([{ panels: [{ dialogue: [balloon('NARRATOR', 60)] }] }]);+ const balloonV = v.find((x) => x.kind === 'balloon-words');+ expect(balloonV.count).toBe(60);+ expect(balloonV.severity).toBe('high');+ expect(balloonV.pageNumber).toBe(1);+ expect(balloonV.panelNumber).toBe(1);+ });++ it('returns nothing for a clean page', () => {+ expect(analyzeComicLettering([{ panels: [{ dialogue: [balloon('A', 8)], caption: 'A beat.' }] }])).toEqual([]);+ });+});diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.mdindex a18c11ee75..f5774473a9 100644--- a/server/lib/editorial/README.md+++ b/server/lib/editorial/README.md@@ -58,7 +58,7 @@ Declare every input the check's `run(ctx)` reads in its `sources` array (anon-empty subset of `EDITORIAL_SOURCES`: `manuscript`, `canon`,`series.styleGuide`, `series.arc.tickingClock`, `series.arc.readerMap`,`reverseOutline`, `reverseOutline.plotlines`, `editorialArcs`,-`series.characterArcs`). The staleness+`series.characterArcs`, `comicScript`). The stalenessrunner fingerprints exactly those sources, so a finding goes stale only whencontent the check actually analyzed drifts — declare too few and a finding staysfalsely fresh; a `manuscript` source must pair with `needsManuscript: true`, and@@ -76,7 +76,13 @@ because not-yet-analyzed" under a partial coverage batch. `series.characterArcs`(#1293) reads the AUTHORED per-character arcs off the already-loaded seriesrecord (`series.characterArcs[]` — want/need, start → end state, transitionbeats), which the `arc.transitions` check reconciles detected change moments-against. When a new check reads a+against. `comicScript` (#1313) fingerprints 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` (derived from the+already-loaded `ctx.issues`, no extra fetch). The `comic.lettering-density` check+reads the same content (via the shared `comicLetteringIssues`) to count+balloon/panel/page word load, so a finding stales exactly when the comic text the+check read changes — not when an unrelated image renders. When a new check reads a`ctx.series` field (or another artifact) that isn't yet a token, add the token to`EDITORIAL_SOURCES` and a matching resolver in the runner's `SOURCE_RESOLVERS`.@@ -104,4 +110,5 @@ runner-injected `ctx.callInlineLLM` (an inline-prompt sibling of| `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`. || `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. |+| `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 --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.jsindex 7fe547f60e..0bf4e12183 100644--- a/server/lib/editorial/checkRegistry.js+++ b/server/lib/editorial/checkRegistry.js@@ -27,6 +27,11 @@import { z } from 'zod';import { estimateTokens } from '../contextBudget.js';import { renderCharacterArcsForPrompt } from '../seriesCharacterArc.js';+import { parseComicScript } from '../comicScriptParser.js';+import {+ analyzeComicLettering,+ DEFAULT_LETTERING_THRESHOLDS,+} from './letteringDensity.js';import { analyzeNamePair, findFirstLetterClusters, normalizeName } from './nameSimilarity.js';import { findCliches, findModifierStacking } from './cliches.js';import { findSaidBookisms, findUnattributedDialogueRuns } from './dialogue.js';@@ -86,6 +91,14 @@ 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' — 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.export const EDITORIAL_SOURCES = Object.freeze(['manuscript','canon',@@ -96,6 +109,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@@ -1214,6 +1228,122 @@ function runDensityCheck(ctx, opts) {return findings;}+// ---------------------------------------------------------------------------+// Comic lettering density / balloon load (#1313) — deterministic over each+// issue's parsed comic script. The pure word/balloon accounting + threshold+// evaluation lives in ./letteringDensity.js (shared with the client comic-script+// stage's inline warnings); the helpers below turn its violations into+// manuscriptReview findings and pre-flight whether any issue even has a script+// (the check's gate). Scope is 'issue' — findings carry the issue number so the+// editor groups them per issue / per page.+// ---------------------------------------------------------------------------++// The AUTHORITATIVE comic pages for an issue (parser-shaped `[{ panels: [...] }]`).+// A POPULATED per-page split (`stages.comicPages.pages[]`) WINS over the generated+// markdown (`stages.comicScript.output`): once a script is split into pages, edits+// in the Comic tab persist to `comicPages.pages[].rawText/panels` and never flow+// back to `comicScript.output`, so reading the raw script would analyze stale text+// (flag balloons the user already cut, miss ones they added). The client+// comic-script stage reads the same `comicPages.pages[].panels`, so both surfaces+// judge the same edited content.+//+// We key on `pages.length`, not `Array.isArray(pages)`, on purpose: the issue+// sanitizer (`sanitizeVisualStage`) ALWAYS materializes `comicPages.pages` as `[]`,+// so an EMPTY array can't distinguish "never split" from "split then all pages+// deleted" — they are byte-identical on disk. Falling back to the still-present+// generated script when the split is empty means an UNSPLIT or IMPORTED script+// (the common pre-render case, where lettering feedback matters most) is still+// checked; the script remains the issue's authored comic text even if a prior+// split was emptied.+export function comicIssuePages(issue) {+ const pages = issue?.stages?.comicPages?.pages;+ if (Array.isArray(pages) && pages.length) {+ return pages.filter((p) => p && typeof p === 'object');+ }+ const output = typeof issue?.stages?.comicScript?.output === 'string' ? issue.stages.comicScript.output : '';+ return output.trim() ? parseComicScript(output).pages : [];+}++// Issues with analyzable comic content, as { number, pages }, sorted by issue+// number for a stable scan order. Shared by the lettering check's `run` AND the+// staleness runner's fingerprint (which projects the lettering-relevant fields off+// this), so the fingerprinted content is exactly what the check analyzes.+export function comicLetteringIssues(issues) {+ return (Array.isArray(issues) ? issues : [])+ .map((i) => ({+ number: Number.isInteger(i?.number) ? i.number : null,+ pages: comicIssuePages(i),+ }))+ .filter((i) => i.pages.length)+ .sort((a, b) => (a.number ?? 0) - (b.number ?? 0));+}++// Cheap presence test for the check's gate — true when any issue has an edited+// comic-pages split OR a non-empty generated script — without paying the parse+// that `comicLetteringIssues` does.+function hasComicContent(issues) {+ return (Array.isArray(issues) ? issues : []).some((i) => {+ const pages = i?.stages?.comicPages?.pages;+ if (Array.isArray(pages) && pages.length) return true;+ return (typeof i?.stages?.comicScript?.output === 'string' ? i.stages.comicScript.output : '').trim();+ });+}++// One human-readable { problem, suggestion } per violation kind. Kept here (not+// in the pure helper) because the wording is PortOS-facing copy, while the helper+// stays a reusable counting primitive.+function comicLetteringText(v) {+ const who = v.speaker ? ` (${v.speaker})` : '';+ switch (v.kind) {+ case 'balloon-words':+ return {+ problem: `A balloon${who} runs ${v.count} words — over the ~${v.threshold}-word balloon limit. A wall of text crammed into one balloon is the #1 reader gripe in comics.`,+ suggestion: 'Split the balloon in two, move some of it to a caption, or trim the line.',+ };+ case 'caption-words':+ return {+ problem: `A caption box runs ${v.count} words — over the ~${v.threshold}-word limit. A dense narration box buries the art the same way an over-stuffed balloon does.`,+ suggestion: 'Tighten the caption, split it across panels, or cut it down.',+ };+ case 'panel-words':+ return {+ problem: `This panel carries ${v.count} words of lettering — over the ~${v.threshold}-word panel limit, crowding the art.`,+ suggestion: 'Spread the lettering across more panels, or cut copy so the art can breathe.',+ };+ case 'panel-balloons':+ return {+ problem: `This panel has ${v.count} balloons — more than the ~${v.threshold} a single panel reads cleanly with.`,+ suggestion: 'Break the exchange across more panels, or merge balloons from the same speaker.',+ };+ case 'page-words':+ default:+ return {+ problem: `This page carries ${v.count} words of lettering — over the ~${v.threshold}-word page ceiling; the text load would overwhelm the art.`,+ suggestion: 'Move some beats to adjacent pages, or trim copy so the page is not text-heavy.',+ };+ }+}++// Map a lettering violation to a manuscriptReview finding for issue `number`.+// `panelNumber` is absent for page-level findings, so the location degrades to+// "Issue N · Page P" cleanly. Severity rides the violation's overflow-scaled+// value (#1313).+function comicLetteringFinding(v, number) {+ const { problem, suggestion } = comicLetteringText(v);+ const where = v.panelNumber != null+ ? `Page ${v.pageNumber} · Panel ${v.panelNumber}`+ : `Page ${v.pageNumber}`;+ return {+ severity: v.severity,+ category: 'lettering',+ location: number != null ? `Issue ${number} · ${where}` : where,+ problem,+ suggestion,+ anchorQuote: typeof v.anchorQuote === 'string' ? v.anchorQuote : '',+ issueNumber: number,+ };+}+export const EDITORIAL_CHECKS = [{id: 'naming.dissimilar-names',@@ -1523,6 +1653,80 @@ export const EDITORIAL_CHECKS = [return findings;},},+ {+ id: 'comic.lettering-density',+ sources: ['comicScript'],+ label: 'Comic lettering density / balloon load',+ description:+ 'Flags over-stuffed comic panels — the #1 reader gripe in comics: a wall of text crammed into one balloon, too many balloons fighting for room, or a page whose total lettering load overwhelms the art. Parses each issue\'s comic script and counts words + balloons per panel and per page against configurable industry rules-of-thumb.',+ scope: 'issue',+ kind: 'deterministic',+ category: 'lettering',+ severityDefault: 'low',+ defaultEnabled: true,+ configSchema: z.object({+ // Per-balloon word ceiling (~20–25 reads cleanly; much past it is a wall of text).+ maxWordsPerBalloon: z.number().int().min(1).max(200).default(DEFAULT_LETTERING_THRESHOLDS.maxWordsPerBalloon),+ // Per-panel total lettering word ceiling (dialogue + caption + SFX).+ maxWordsPerPanel: z.number().int().min(1).max(500).default(DEFAULT_LETTERING_THRESHOLDS.maxWordsPerPanel),+ // Distinct balloons (dialogue + caption boxes) a single panel reads cleanly with.+ maxBalloonsPerPanel: z.number().int().min(1).max(20).default(DEFAULT_LETTERING_THRESHOLDS.maxBalloonsPerPanel),+ // Whole-page lettering word ceiling — past it the text load buries the art.+ maxWordsPerPage: z.number().int().min(1).max(2000).default(DEFAULT_LETTERING_THRESHOLDS.maxWordsPerPage),+ }),+ configFields: [+ {+ key: 'maxWordsPerBalloon',+ label: 'Max words per balloon',+ type: 'number',+ min: 1,+ max: 200,+ step: 1,+ help: 'Flag a single speech balloon / caption box over this many words (~25 is the industry rule-of-thumb).',+ },+ {+ key: 'maxWordsPerPanel',+ label: 'Max words per panel',+ type: 'number',+ min: 1,+ max: 500,+ step: 1,+ help: 'Flag a panel whose total lettering (dialogue + caption + SFX) exceeds this many words (~50).',+ },+ {+ key: 'maxBalloonsPerPanel',+ label: 'Max balloons per panel',+ type: 'number',+ min: 1,+ max: 20,+ step: 1,+ help: 'Flag a panel with more than this many distinct balloons + caption boxes (~3).',+ },+ {+ key: 'maxWordsPerPage',+ label: 'Max words per page',+ type: 'number',+ min: 1,+ max: 2000,+ step: 10,+ help: 'Flag a page whose total lettering load would overwhelm the art (~150).',+ },+ ],+ // Needs at least one issue with comic content (an edited page split or a+ // generated script). A cheap presence test — run() builds the full parsed+ // projection only when the gate passes.+ gate: (ctx) => hasComicContent(ctx.issues),+ run: (ctx) => {+ const config = ctx.config || {};+ const findings = [];+ for (const { number, pages } of comicLetteringIssues(ctx.issues)) {+ for (const v of analyzeComicLettering(pages, config)) {+ findings.push(comicLetteringFinding(v, number));+ }+ }+ return findings;+ },+ },{id: 'scene.component-balance',sources: ['reverseOutline'],diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.jsindex 1686d887ea..004357560e 100644--- a/server/lib/editorial/checkRegistry.test.js+++ b/server/lib/editorial/checkRegistry.test.js@@ -2978,3 +2978,96 @@ describe('dialogue-craft bundle (#1307)', () => {});});});++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);+ });+});diff --git a/server/lib/editorial/index.js b/server/lib/editorial/index.jsindex 85466f6f37..3a3e7aa2f4 100644--- a/server/lib/editorial/index.js+++ b/server/lib/editorial/index.js@@ -4,6 +4,7 @@ export * from './checkRegistry.js';export * from './cliches.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 --git a/server/lib/editorial/letteringDensity.js b/server/lib/editorial/letteringDensity.jsnew file mode 100644index 0000000000..026c5e3e7a--- /dev/null+++ b/server/lib/editorial/letteringDensity.js@@ -0,0 +1,240 @@+/**+ * Comic lettering density / balloon load (#1313) — pure word/balloon accounting+ * over the parsed comic-script pages the `comicScriptParser` emits.+ *+ * The #1 reader gripe in comics is a wall of text crammed into one panel: an+ * over-stuffed balloon, too many balloons fighting for room, or a page whose+ * total lettering load overwhelms the art. `comicScriptParser.js` already parses+ * per-panel dialogue / caption / SFX but never counts words — this module does+ * the counting and flags overflows against industry rules-of-thumb (all+ * configurable): ~25 words per balloon, ~50 words per panel, ~3 balloons per+ * panel, and a per-page lettering ceiling.+ *+ * PURE + side-effect-free so it is unit-testable and so the SAME helper backs+ * both the server-side editorial check (`comic.lettering-density` in+ * checkRegistry.js) and the client comic-script stage inline warnings (mirrored+ * to `client/src/lib/letteringDensity.js` — keep the two byte-for-byte in sync).+ *+ * A "balloon" is a discrete lettering element the reader's eye lands on: each+ * dialogue entry is one balloon, and each caption box is one (captions repeat —+ * the parser folds `Caption` / `Caption 2` into one newline-joined string, so+ * each non-empty line counts as a box). SFX is lettering and counts toward the+ * panel/page WORD load, but it is rendered as a sound effect rather than a+ * balloon, so it does NOT count toward the balloon tally.+ */++// Industry rules-of-thumb (all overridable via the check's config). A balloon+// much over ~20–25 words reads as a wall of text; a panel over ~45–50 words+// crowds the art; more than ~3 balloons in a panel is hard to follow; and a+// page much past ~150 words of lettering starts to bury the illustration.+export const DEFAULT_LETTERING_THRESHOLDS = Object.freeze({+ maxWordsPerBalloon: 25,+ maxWordsPerPanel: 50,+ maxBalloonsPerPanel: 3,+ maxWordsPerPage: 150,+});++// The severity ranks an overflow can scale to (high → low), most-severe first.+// Local copy so this stays self-contained and the client mirror needs nothing+// from checkRegistry.+const LETTERING_SEVERITIES = ['high', 'medium', 'low'];++// Count words in a free-text lettering string. A "word" is a run of+// non-whitespace, so hyphenates and contractions count once and punctuation+// rides along — close enough for a density heuristic. Non-strings → 0.+export function countWords(text) {+ if (typeof text !== 'string') return 0;+ const matched = text.trim().match(/\S+/g);+ return matched ? matched.length : 0;+}++// Severity scaled by how far over the threshold a count runs (#1313 "severity+// scaled by overflow"): ≥2× the limit is `high`, ≥1.4× is `medium`, otherwise a+// mild overflow is `low`. Pure so it's unit-testable. A count at/under the+// threshold returns `low` but callers only invoke it for genuine overflows.+export function overflowSeverity(count, threshold) {+ if (!(threshold > 0)) return 'medium';+ const ratio = count / threshold;+ if (ratio >= 2) return 'high';+ if (ratio >= 1.4) return 'medium';+ return 'low';+}++// Merge a (possibly hand-edited / partial) config object over the defaults,+// guarding each field's type so a bad value can't crash the scan. A+// non-positive threshold disables that rule (treated as Infinity).+export function sanitizeLetteringThresholds(config) {+ const c = config && typeof config === 'object' ? config : {};+ const pick = (key) => {+ const v = c[key];+ if (typeof v === 'number' && Number.isFinite(v) && v > 0) return v;+ return DEFAULT_LETTERING_THRESHOLDS[key];+ };+ return {+ maxWordsPerBalloon: pick('maxWordsPerBalloon'),+ maxWordsPerPanel: pick('maxWordsPerPanel'),+ maxBalloonsPerPanel: pick('maxBalloonsPerPanel'),+ maxWordsPerPage: pick('maxWordsPerPage'),+ };+}++// Per-panel lettering metrics from a parsed panel+// (`{ description, caption, dialogue: [{ character, line }], sfx }`). Pure.+//+// - `balloons` — one entry per dialogue balloon: { speaker, words, line }.+// - `captionBoxes` — one entry per non-empty caption line: { words, text }.+// - `balloonCount` — dialogue balloons + caption boxes (the reader-facing tally).+// - `totalWords` — dialogue + caption + SFX words (the full lettering load).+export function panelLetteringMetrics(panel) {+ const dialogue = Array.isArray(panel?.dialogue) ? panel.dialogue : [];+ const balloons = dialogue.map((d) => {+ const line = typeof d?.line === 'string' ? d.line : '';+ return {+ speaker: typeof d?.character === 'string' ? d.character.trim() : '',+ words: countWords(line),+ line,+ };+ });+ const caption = typeof panel?.caption === 'string' ? panel.caption : '';+ const captionBoxes = caption+ .split('\n')+ .map((l) => l.trim())+ .filter(Boolean)+ .map((text) => ({ words: countWords(text), text }));+ const sfx = typeof panel?.sfx === 'string' ? panel.sfx : '';+ const dialogueWords = balloons.reduce((sum, b) => sum + b.words, 0);+ const captionWords = captionBoxes.reduce((sum, b) => sum + b.words, 0);+ const sfxWords = countWords(sfx);+ return {+ balloons,+ captionBoxes,+ balloonCount: balloons.length + captionBoxes.length,+ dialogueWords,+ captionWords,+ sfxWords,+ totalWords: dialogueWords + captionWords + sfxWords,+ };+}++// First real lettering text in a panel, for anchoring a panel/page-level finding+// to something the editor can actually locate in the script (prefer a dialogue+// line, then a caption, then SFX). '' when the panel has no lettering at all.+function firstLetteringText(metrics) {+ const balloon = metrics.balloons.find((b) => b.line.trim());+ if (balloon) return balloon.line.trim();+ const box = metrics.captionBoxes.find((b) => b.text);+ return box ? box.text : '';+}++/**+ * Analyze the parsed pages of ONE comic script for lettering overflows.+ *+ * @param {Array<{ panels: Array<object> }>} pages parseComicScript(...).pages+ * @param {object} [config] threshold overrides (see DEFAULT_LETTERING_THRESHOLDS)+ * @returns {Array<object>} flat list of violations, each:+ * { kind, pageNumber, panelNumber?, balloonIndex?, boxIndex?, speaker?, count,+ * threshold, limitLabel, severity, anchorQuote }+ * `kind` ∈ 'balloon-words' | 'caption-words' | 'panel-words' | 'panel-balloons' | 'page-words'.+ * `pageNumber` / `panelNumber` are 1-based (panel within its page).+ */+export function analyzeComicLettering(pages, config) {+ const t = sanitizeLetteringThresholds(config);+ const list = Array.isArray(pages) ? pages : [];+ const violations = [];+ list.forEach((page, pageIdx) => {+ const pageNumber = pageIdx + 1;+ const panels = Array.isArray(page?.panels) ? page.panels : [];+ let pageWords = 0;+ panels.forEach((panel, panelIdx) => {+ const panelNumber = panelIdx + 1;+ const m = panelLetteringMetrics(panel);+ pageWords += m.totalWords;++ // An individual balloon over the per-balloon word ceiling — the most+ // actionable signal (split it, or move some to a caption).+ m.balloons.forEach((balloon, balloonIndex) => {+ if (balloon.words > t.maxWordsPerBalloon) {+ violations.push({+ kind: 'balloon-words',+ pageNumber,+ panelNumber,+ balloonIndex,+ speaker: balloon.speaker,+ count: balloon.words,+ threshold: t.maxWordsPerBalloon,+ limitLabel: 'words in one balloon',+ severity: overflowSeverity(balloon.words, t.maxWordsPerBalloon),+ anchorQuote: balloon.line.trim(),+ });+ }+ });++ // A single caption box over the same per-balloon word ceiling. Caption boxes+ // count as balloons (toward `maxBalloonsPerPanel`) and the threshold's help+ // says it applies to caption boxes too, so an over-stuffed narration box must+ // trip the word limit just like a speech balloon — even when the panel total+ // stays under `maxWordsPerPanel`.+ m.captionBoxes.forEach((box, boxIndex) => {+ if (box.words > t.maxWordsPerBalloon) {+ violations.push({+ kind: 'caption-words',+ pageNumber,+ panelNumber,+ boxIndex,+ count: box.words,+ threshold: t.maxWordsPerBalloon,+ limitLabel: 'words in one caption box',+ severity: overflowSeverity(box.words, t.maxWordsPerBalloon),+ anchorQuote: box.text,+ });+ }+ });++ // The whole panel carries too much lettering across all its balloons.+ if (m.totalWords > t.maxWordsPerPanel) {+ violations.push({+ kind: 'panel-words',+ pageNumber,+ panelNumber,+ count: m.totalWords,+ threshold: t.maxWordsPerPanel,+ limitLabel: 'words in one panel',+ severity: overflowSeverity(m.totalWords, t.maxWordsPerPanel),+ anchorQuote: firstLetteringText(m),+ });+ }++ // Too many discrete balloons fighting for room in one panel.+ if (m.balloonCount > t.maxBalloonsPerPanel) {+ violations.push({+ kind: 'panel-balloons',+ pageNumber,+ panelNumber,+ count: m.balloonCount,+ threshold: t.maxBalloonsPerPanel,+ limitLabel: 'balloons in one panel',+ severity: overflowSeverity(m.balloonCount, t.maxBalloonsPerPanel),+ anchorQuote: firstLetteringText(m),+ });+ }+ });++ // The page's total lettering load would overwhelm the art.+ if (pageWords > t.maxWordsPerPage) {+ violations.push({+ kind: 'page-words',+ pageNumber,+ count: pageWords,+ threshold: t.maxWordsPerPage,+ limitLabel: 'words on one page',+ severity: overflowSeverity(pageWords, t.maxWordsPerPage),+ anchorQuote: '',+ });+ }+ });+ return violations;+}++// Re-export the severity vocabulary so a consumer can reason about ordering+// without importing the registry.+export { LETTERING_SEVERITIES };diff --git a/server/lib/editorial/letteringDensity.test.js b/server/lib/editorial/letteringDensity.test.jsnew file mode 100644index 0000000000..4163615e1c--- /dev/null+++ b/server/lib/editorial/letteringDensity.test.js@@ -0,0 +1,168 @@+import { describe, it, expect } from 'vitest';+import {+ countWords,+ overflowSeverity,+ sanitizeLetteringThresholds,+ panelLetteringMetrics,+ analyzeComicLettering,+ DEFAULT_LETTERING_THRESHOLDS,+} from './letteringDensity.js';++// Build a panel of N words across a single balloon.+const balloon = (character, n) => ({ character, line: Array.from({ length: n }, (_, i) => `w${i}`).join(' ') });++describe('countWords', () => {+ it('counts whitespace-separated tokens', () => {+ expect(countWords('one two three')).toBe(3);+ expect(countWords(' spaced out ')).toBe(2);+ expect(countWords('hyphen-ated counts once')).toBe(3);+ });+ it('returns 0 for empty / non-string', () => {+ expect(countWords('')).toBe(0);+ expect(countWords(' ')).toBe(0);+ expect(countWords(null)).toBe(0);+ expect(countWords(undefined)).toBe(0);+ expect(countWords(42)).toBe(0);+ });+});++describe('overflowSeverity', () => {+ it('scales with how far over the threshold the count runs', () => {+ expect(overflowSeverity(26, 25)).toBe('low'); // ~1.04×+ expect(overflowSeverity(35, 25)).toBe('medium'); // 1.4×+ expect(overflowSeverity(50, 25)).toBe('high'); // 2×+ expect(overflowSeverity(120, 25)).toBe('high');+ });+ it('falls back to medium for a non-positive threshold', () => {+ expect(overflowSeverity(10, 0)).toBe('medium');+ expect(overflowSeverity(10, -5)).toBe('medium');+ });+});++describe('sanitizeLetteringThresholds', () => {+ it('fills defaults and overrides valid positive numbers', () => {+ expect(sanitizeLetteringThresholds(undefined)).toEqual(DEFAULT_LETTERING_THRESHOLDS);+ expect(sanitizeLetteringThresholds({ maxWordsPerBalloon: 10 })).toMatchObject({+ maxWordsPerBalloon: 10,+ maxWordsPerPanel: DEFAULT_LETTERING_THRESHOLDS.maxWordsPerPanel,+ });+ });+ it('ignores invalid / non-positive values, keeping the default', () => {+ expect(sanitizeLetteringThresholds({ maxWordsPerBalloon: 0 }).maxWordsPerBalloon)+ .toBe(DEFAULT_LETTERING_THRESHOLDS.maxWordsPerBalloon);+ expect(sanitizeLetteringThresholds({ maxWordsPerPanel: -3 }).maxWordsPerPanel)+ .toBe(DEFAULT_LETTERING_THRESHOLDS.maxWordsPerPanel);+ expect(sanitizeLetteringThresholds({ maxWordsPerPage: 'lots' }).maxWordsPerPage)+ .toBe(DEFAULT_LETTERING_THRESHOLDS.maxWordsPerPage);+ });+});++describe('panelLetteringMetrics', () => {+ it('counts dialogue + caption + SFX words and balloon boxes', () => {+ const panel = {+ description: 'A wide shot of the room.',+ dialogue: [balloon('ANYA', 5), balloon('BORIS', 3)],+ caption: 'Later that night.\nThe rain had not stopped.',+ sfx: 'KRAKOOM',+ };+ const m = panelLetteringMetrics(panel);+ expect(m.dialogueWords).toBe(8);+ expect(m.captionWords).toBe(3 + 5); // two caption lines+ expect(m.sfxWords).toBe(1);+ expect(m.totalWords).toBe(8 + 8 + 1);+ // 2 dialogue balloons + 2 caption boxes = 4 distinct balloons.+ expect(m.balloonCount).toBe(4);+ expect(m.balloons).toHaveLength(2);+ expect(m.captionBoxes).toHaveLength(2);+ });+ it('tolerates a panel with no lettering', () => {+ const m = panelLetteringMetrics({ description: 'Silent splash.' });+ expect(m.totalWords).toBe(0);+ expect(m.balloonCount).toBe(0);+ });+ it('tolerates non-array dialogue / non-string fields', () => {+ const m = panelLetteringMetrics({ dialogue: null, caption: 42, sfx: undefined });+ expect(m.totalWords).toBe(0);+ expect(m.balloonCount).toBe(0);+ });+});++describe('analyzeComicLettering', () => {+ it('flags an over-stuffed balloon, scaling severity by overflow', () => {+ const pages = [{ panels: [{ dialogue: [balloon('NARRATOR', 60)] }] }];+ const v = analyzeComicLettering(pages);+ const balloonViolation = v.find((x) => x.kind === 'balloon-words');+ expect(balloonViolation).toBeTruthy();+ expect(balloonViolation.count).toBe(60);+ expect(balloonViolation.threshold).toBe(25);+ expect(balloonViolation.severity).toBe('high'); // 60/25 = 2.4×+ expect(balloonViolation.pageNumber).toBe(1);+ expect(balloonViolation.panelNumber).toBe(1);+ expect(balloonViolation.anchorQuote).toContain('w0');+ });++ it('flags an over-stuffed caption box on the per-balloon word limit', () => {+ // A single 40-word caption is under the 50-word panel limit, so only the+ // caption-words violation should fire (caption boxes count as balloons).+ const caption = Array.from({ length: 40 }, (_, i) => `c${i}`).join(' ');+ const v = analyzeComicLettering([{ panels: [{ caption }] }]);+ const captionV = v.find((x) => x.kind === 'caption-words');+ expect(captionV).toBeTruthy();+ expect(captionV.count).toBe(40);+ expect(captionV.threshold).toBe(25);+ expect(captionV.anchorQuote).toContain('c0');+ expect(v.some((x) => x.kind === 'panel-words')).toBe(false);+ });++ it('flags a panel over the total-word limit', () => {+ // Three balloons of 20 words each = 60 > 50 panel limit, but each balloon is+ // under the 25-word balloon limit, so ONLY the panel-words violation fires.+ const pages = [{ panels: [{ dialogue: [balloon('A', 20), balloon('B', 20), balloon('C', 20)] }] }];+ const v = analyzeComicLettering(pages);+ expect(v.some((x) => x.kind === 'balloon-words')).toBe(false);+ const panelV = v.find((x) => x.kind === 'panel-words');+ expect(panelV).toBeTruthy();+ expect(panelV.count).toBe(60);+ // 3 balloons also trips nothing (== limit, not >).+ expect(v.some((x) => x.kind === 'panel-balloons')).toBe(false);+ });++ it('flags too many balloons in a panel', () => {+ const pages = [{ panels: [{ dialogue: [balloon('A', 2), balloon('B', 2), balloon('C', 2), balloon('D', 2)] }] }];+ const v = analyzeComicLettering(pages);+ const balloonsV = v.find((x) => x.kind === 'panel-balloons');+ expect(balloonsV).toBeTruthy();+ expect(balloonsV.count).toBe(4);+ expect(balloonsV.threshold).toBe(3);+ });++ it('flags a page whose total lettering load overwhelms the art', () => {+ // 4 panels × 40 words = 160 > 150 page limit. Each panel (40) is under the+ // 50-word panel limit, so only the page-words violation fires.+ const panels = Array.from({ length: 4 }, () => ({ dialogue: [balloon('X', 40)] }));+ const v = analyzeComicLettering([{ panels }]);+ const pageV = v.find((x) => x.kind === 'page-words');+ expect(pageV).toBeTruthy();+ expect(pageV.count).toBe(160);+ expect(pageV.panelNumber).toBeUndefined();+ expect(v.some((x) => x.kind === 'panel-words')).toBe(false);+ });++ it('returns nothing for a well-lettered script', () => {+ const pages = [{ panels: [{ dialogue: [balloon('A', 10)], caption: 'A quiet beat.' }] }];+ expect(analyzeComicLettering(pages)).toEqual([]);+ });++ it('honors custom thresholds', () => {+ const pages = [{ panels: [{ dialogue: [balloon('A', 10)] }] }];+ // Default: clean. Tighten the balloon limit to 5 → the 10-word balloon trips.+ expect(analyzeComicLettering(pages)).toEqual([]);+ const v = analyzeComicLettering(pages, { maxWordsPerBalloon: 5 });+ expect(v.find((x) => x.kind === 'balloon-words').count).toBe(10);+ });++ it('tolerates malformed pages / panels', () => {+ expect(analyzeComicLettering(null)).toEqual([]);+ expect(analyzeComicLettering([null, { panels: null }, {}])).toEqual([]);+ });+});diff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.jsindex 731c15feb1..5635176a9b 100644--- a/server/services/pipeline/editorial/checkRunner.js+++ b/server/services/pipeline/editorial/checkRunner.js@@ -19,7 +19,7 @@ import { randomUUID, createHash } from 'crypto';import { createSseRunner } from '../../../lib/sseUtils.js';import { runStagedLLM, runInlineLLM, runStageScopedInlineLLM, resolveStageContext } from '../../../lib/stageRunner.js';import { planManuscriptPass } from '../../../lib/contextBudget.js';-import { getEnabledChecks, getEnabledCheckRows, getAllChecks, EDITORIAL_SOURCES } from '../../../lib/editorial/index.js';+import { getEnabledChecks, getEnabledCheckRows, getAllChecks, EDITORIAL_SOURCES, comicLetteringIssues } from '../../../lib/editorial/index.js';import { getSettings } from '../../settings.js';import { getSeries } from '../series.js';import { listIssues } from '../issues.js';@@ -81,8 +81,38 @@ 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),+ // Every issue's AUTHORITATIVE comic lettering content, keyed by issue number+ // (#1313). The lettering-density check reads the edited comic-pages split (or the+ // generated script when unsplit) — NOT the prose manuscript — so it gets its own+ // source token: editing a comic script/page stales lettering findings without+ // staling prose findings, and vice-versa. `projectComicLetteringContent` builds+ // the stable [{ number, panels: [{ caption, dialogue, sfx }] }] off the SAME+ // `comicLetteringIssues` the check analyzes, so a finding stales exactly when the+ // text it read changes (and an unrelated image render — `panel.imageJobId` — does+ // NOT stale it, since only the lettering fields are projected).+ comicScript: ({ comicScripts }) => canonicalStringify(comicScripts ?? null),};+// Project the loaded issues down to the lettering-relevant comic content the check+// analyzes, via the registry's shared `comicLetteringIssues` (so the fingerprint+// can't drift from what `run` reads). Keeps ONLY caption/dialogue/SFX — the fields+// `panelLetteringMetrics` consumes — so the hash is stable across image renders and+// description edits that don't change lettering. PAGE GROUPING is preserved (not+// flattened): the check reports per-page totals and page/panel locations, so moving+// panels between pages must change the hash even when the lettering text is identical.+function projectComicLetteringContent(issues) {+ return comicLetteringIssues(issues).map(({ number, pages }) => ({+ number,+ pages: pages.map((p) => ({+ panels: (Array.isArray(p?.panels) ? p.panels : []).map((panel) => ({+ caption: typeof panel?.caption === 'string' ? panel.caption : '',+ dialogue: Array.isArray(panel?.dialogue) ? panel.dialogue : [],+ sfx: typeof panel?.sfx === 'string' ? panel.sfx : '',+ })),+ })),+ }));+}+// 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.@@ -219,10 +249,14 @@ export async function runEditorialChecks(seriesId, options = {}) {// series (canceled/early-stopped batch) doesn't flag a not-yet-analyzed POV// holder as arc-less (#1295). Folded into the editorialArcs fingerprint below.const editorialArcsComplete = editorialCoverageComplete(editorial);+ // The comic lettering content the check (#1313) reads — derived from the+ // already-loaded issues (no extra I/O), so a finding stales when an issue's comic+ // pages / script are edited.+ const comicScripts = projectComicLetteringContent(issues);// 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,@@ -380,19 +414,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'));+ // Issues are only fetched here when a comic-script-sourced finding (#1313) needs+ // re-fingerprinting — mirrors the other per-source I/O gates.+ 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, issues] = 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).+ // Reuse the already-loaded series.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 = projectComicLetteringContent(issues);+ const resolvedSources = resolveSources({ manuscript: sectionsCorpus(sections), canon, series, reverseOutline, reverseOutlinePlotlines, editorialArcs, editorialArcsComplete, comicScripts });return {...review,comments: review.comments.map((c) => {