Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: editorial check for dialogue-tag variety / within-scene monotony (#1587)

[._.]/ Adam Eivy935d16766615
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index abce69c20f..cb442bbc8c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -59,6 +59,8 @@
- **[issue-1585] A new editorial check catches flat secondary characters — a recurring side character who appears scene after scene but is exactly the same at the end as at the start.** The existing `pov.justified` check asks whether each *POV* character earns their viewpoint, but nothing judged the *non-POV* cast — so a recurring side character (a partner, a foil, a co-worker who shows up across half the book) could stay completely static, draining the story's texture, without ever being flagged. The new **Secondary-character arcs** check (`character.secondary-arc`) tallies the recurring non-POV cast from the reverse-outline scene map — characters present across multiple scenes who never hold the viewpoint — and judges whether each shows meaningful change, flagging a *flat arc* (the same situation, attitude, and standing at the end as the start) or a *purposeless regression* (an arc that quietly undoes itself with nothing in the story making it meaningful). It reads the stitched manuscript with the recurring-cast roster and the canon roster, deliberately ignoring genuine walk-ons (a one- or two-scene bit player owes the reader no arc) and a deliberately-static foil whose constancy is the point. Because a flat arc is a whole-story claim, it carries each recurring secondary's established state forward between manuscript chunks and gates its verdict on the final part — so a character established early whose change lands in a chapter no longer in view isn't falsely flagged — and degrades to a whole-manuscript scan when no outline exists. A configurable **recurring threshold** (default 2 scenes) tunes how prominent a character must be before it's held to an arc. It's a default-on series check that surfaces in the existing editorial-review UI and Series Autopilot like every other check, marking a prominent recurring character left wholly flat medium-severity. (`server/lib/editorial/checkRegistry.js`, `data.reference/prompts/stages/pipeline-editorial-secondary-arc.md`, `scripts/migrations/133-editorial-secondary-arc-stage.js`)
+- **[issue-1587] A new editorial check catches dialogue-tag tics — "she said" eight times in one scene, or a different fancy verb on nearly every line.** The existing `dialogue.said-bookisms` check flags ornate tags ("expostulated", "opined"), but nothing caught the opposite problems: within-scene **monotony** (one tag verb hammered over and over until it starts to call attention to itself) or **over-variation** (a fresh tag verb on almost every line — "said/asked/replied/murmured/whispered" thesaurus churn that's just as distracting). The new **Dialogue tag variety** check (`dialogue.tag-variety`) inventories the speech tags (plain and ornate) adjacent to quoted lines, scene by scene — splitting a manuscript on its scene dividers (`***`, centered rules, markdown scene headings) so the count isn't diluted across a whole issue — and collapses inflections onto a base verb so "said"/"says" count as one. It flags a scene where a single verb dominates a tag-dense exchange, or where nearly every tagged line uses a different verb, and leaves a healthily varied, mostly-invisible-"said" scene alone. It's a default-on, deterministic series check (no LLM call) with per-series thresholds for how many tags a scene needs before it's judged, how dominant a verb must be to read as monotonous, and how varied to read as churn — and a house-style allowlist to mute a tag verb. Findings surface in the existing editorial-review UI and Series Autopilot like every other check, at low severity. (`server/lib/editorial/dialogue.js`, `server/lib/editorial/checkRegistry.js`)
+
- **[issue-1586] A new editorial check catches narrator-voice whiplash — narration that's witty in issue 1, grim in issue 3, then witty again in issue 5.** The existing `dialogue.voice-distinctiveness` check guards each *character's* dialogue voice, but nothing watched the *narrator's* voice across a series — so the storytelling tone could lurch from issue to issue (a wry, ironic narrator turning flat and clinical, a spare hard-boiled voice going lush and lyrical) with no one flagging the inconsistency, even though voice consistency is part of the promise to the reader. The new **Narrative voice / tone consistency** check (`style.voice-consistency`) fingerprints each issue's narrative tone — diction, register, humor, emotional temperature, sentence rhythm — and flags two problems: a *cross-issue tonal shift* the story never earns, and *drift from the series style guide's intended voice* (the declared `tone` words) when one is set. It reads the stitched manuscript with the style guide's intended tone, deliberately ignoring a purposeful modulation the events justify (a grim chapter because the plot took a grim turn) and judging the narration only, not character dialogue. Because the comparison spans issues, it carries each issue's tone fingerprint forward between manuscript chunks, so a later issue's narration is judged against the voice the series established earlier; it degrades to a pure cross-issue consistency scan when no style guide tone is declared. It's a default-on series check that surfaces in the existing editorial-review UI and Series Autopilot like every other check, marking a sharp, unexplained whiplash medium-severity. (`server/lib/editorial/checkRegistry.js`, `data.reference/prompts/stages/pipeline-editorial-voice-consistency.md`, `scripts/migrations/134-editorial-voice-consistency-stage.js`)
## Series Autopilot
diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.md
index 659dcc2f3a..e8fe81027d 100644
--- a/server/lib/editorial/README.md
+++ b/server/lib/editorial/README.md
@@ -149,7 +149,7 @@ runner-injected `ctx.callInlineLLM` (an inline-prompt sibling of
| `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. |
| `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`). Also `summarizeStoryboardShots` (#1466) — renders the collected `{ issueNumber, scene }` storyboard list into a compact per-scene shot block shared by the LLM siblings `visual.eyeline-match` (gaze reciprocity / eyeline-vs-screen-direction) and `visual.appearance-continuity` (#1467 — diffs the same entity's wardrobe/prop/setting descriptions across shots for contradictions). Reads the shot-grammar fields from `server/lib/shotGrammar.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 `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. |
+| `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. Also `inventoryDialogueTags` + `splitScenes` + `findDialogueTagVariety` (`dialogue.tag-variety`, #1587 — per-scene tag inventory flagging within-scene **monotony** (one verb dominates) and **over-variation** (a fresh verb on nearly every line); collapses inflections onto a base lemma via `PLAIN_SPEECH_TAG_GROUPS`). 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. |
| `balloonAttribution.js` | Pure, dependency-free comic speech-balloon attribution primitives for `comic.balloon-attribution`: `analyzeBalloonAttribution` (flags a dialogue line whose speaker isn't shown in the panel description and carries no off-panel/broadcast cue — the case the image model mis-attributes to a visible character), `splitSpeaker`, `nameInText`, and `OFFPANEL_OK_MODIFIER` (the broadcast/off-panel/V.O./transmission modifier vocabulary — mirrors `visualStages.js` `BALLOON_STYLE_HINTS`, keep in sync). Severity scales `medium`/`low` by whether another canon character is visibly named in the panel. |
| `index.js` | Barrel re-export of the above. |
diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.js
index 8d207eca4c..98a9961acf 100644
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@ -35,7 +35,7 @@ import {
import { analyzeBalloonAttribution } from './balloonAttribution.js';
import { analyzeNamePair, comparisonName, findFirstLetterClusters, normalizeName } from './nameSimilarity.js';
import { findCliches, findModifierStacking } from './cliches.js';
-import { findSaidBookisms, findUnattributedDialogueRuns, attributeDialogueByOwner } from './dialogue.js';
+import { findSaidBookisms, findUnattributedDialogueRuns, attributeDialogueByOwner, findDialogueTagVariety } from './dialogue.js';
import { findItalicThoughts } from './italicThoughts.js';
import {
findFilterWords,
@@ -5171,6 +5171,89 @@ export const EDITORIAL_CHECKS = [
return findings;
},
},
+ {
+ id: 'dialogue.tag-variety',
+ sources: ['manuscript'],
+ label: 'Dialogue tag variety / within-scene tag monotony',
+ description:
+ 'Flags the opposite tics from said-bookisms at the scene grain: one tag verb hammered over and over ("she said" eight times in a scene — monotony) or a different fancy verb on nearly every line ("said/asked/replied/murmured/whispered" churn — over-variation). Deterministic scan that inventories speech tags (plain + ornate) adjacent to quoted lines, scene by scene. The craft target is mostly the invisible "said"/"asked" with enough variation to stay unnoticed.',
+ scope: 'issue',
+ kind: 'deterministic',
+ category: 'dialogue',
+ severityDefault: 'low',
+ defaultEnabled: true,
+ // Reads the stitched manuscript (per-issue sections), split into scenes.
+ needsManuscript: true,
+ configSchema: z.object({
+ // A scene needs at least this many speech tags before variety is judged —
+ // a handful of tags can't be "monotonous" or "over-varied" meaningfully.
+ minTags: z.number().int().min(3).max(40).default(6),
+ // Monotony: dominant verb must hit BOTH a raw count and a share-of-tags ratio.
+ monotonyCount: z.number().int().min(2).max(40).default(6),
+ monotonyRatio: z.number().min(0.4).max(1).default(0.7),
+ // Over-variation: distinct verbs ÷ tags must exceed this with ≥ minDistinct verbs.
+ overVariationRatio: z.number().min(0.5).max(1).default(0.85),
+ minDistinct: z.number().int().min(2).max(20).default(5),
+ // Cap findings per run so a dialogue-heavy draft can't flood the review.
+ maxFindings: z.number().int().min(1).max(50).default(20),
+ // House-style allowlist (mute a tag verb) / extra ornate tags to count.
+ allowWords: z.string().default(''),
+ extraWords: z.string().default(''),
+ }),
+ configFields: [
+ { key: 'minTags', label: 'Min tags per scene to judge', type: 'number', min: 3, max: 40, step: 1, help: 'A scene needs at least this many speech tags before its variety is assessed.' },
+ { key: 'monotonyCount', label: 'Monotony: dominant-verb count', type: 'number', min: 2, max: 40, step: 1, help: 'How many times one tag verb must recur in a scene to count toward monotony.' },
+ { key: 'monotonyRatio', label: 'Monotony: dominant-verb share', type: 'number', min: 0.4, max: 1, step: 0.05, help: 'Fraction of the scene\'s tags the dominant verb must own (0–1) to flag monotony.' },
+ { key: 'overVariationRatio', label: 'Over-variation: distinct share', type: 'number', min: 0.5, max: 1, step: 0.05, help: 'Distinct-verbs ÷ total-tags above this (0–1) reads as thesaurus churn.' },
+ { key: 'minDistinct', label: 'Over-variation: min distinct verbs', type: 'number', min: 2, max: 20, step: 1, help: 'At least this many distinct tag verbs before over-variation can fire.' },
+ { key: 'maxFindings', label: 'Max findings per run', type: 'number', min: 1, max: 50, step: 1, help: 'Cap findings so a dialogue-heavy draft can not flood the review.' },
+ { key: 'allowWords', label: 'House-style allowlist', type: 'text', help: 'Tag verbs to leave out of the inventory (comma-separated or one per line).' },
+ { key: 'extraWords', label: 'Extra ornate tags to count', type: 'text', help: 'Series-specific ornate tags to include in the inventory (comma-separated or one per line).' },
+ ],
+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,
+ run: (ctx) => {
+ const cfg = ctx.config || {};
+ const max = cfg.maxFindings ?? 20;
+ const allowWords = splitPhraseList(cfg.allowWords);
+ const extraWords = splitPhraseList(cfg.extraWords);
+ const opts = {
+ allowWords,
+ extraWords,
+ minTags: cfg.minTags ?? 6,
+ monotonyCount: cfg.monotonyCount ?? 6,
+ monotonyRatio: cfg.monotonyRatio ?? 0.7,
+ overVariationRatio: cfg.overVariationRatio ?? 0.85,
+ minDistinct: cfg.minDistinct ?? 5,
+ };
+ const sections = Array.isArray(ctx.sections) ? ctx.sections : [];
+ const findings = [];
+ for (const s of sections) {
+ if (findings.length >= max) break;
+ const hits = findDialogueTagVariety(s?.content || '', opts);
+ for (const hit of hits) {
+ if (findings.length >= max) break;
+ const issueNumber = Number.isInteger(s?.number) ? s.number : null;
+ const location = issueNumber != null ? `Issue ${issueNumber}` : 'Manuscript';
+ const sceneLabel = `scene ${hit.sceneOrdinal}`;
+ const problem = hit.type === 'monotony'
+ ? `The tag "${hit.verb}" carries ${hit.count} of ${hit.total} dialogue tags in ${sceneLabel} — one repeated tag verb turns monotonous and starts to call attention to itself.`
+ : `${sceneLabel} uses ${hit.distinct} different tag verbs across ${hit.total} tagged lines — a fresh verb on nearly every line reads as thesaurus churn and pulls the reader out.`;
+ findings.push({
+ severity: ctx.severityDefault,
+ category: 'dialogue',
+ location,
+ problem,
+ suggestion: hit.type === 'monotony'
+ ? 'Vary the rhythm: drop some tags entirely (let an action beat carry the speaker) and swap a few for "asked"/a beat so no single tag dominates.'
+ : 'Lean on the invisible "said"/"asked" for most lines and reserve a distinctive tag for the moments that earn it — constant variation is as distracting as monotony.',
+ anchorQuote: hit.anchor,
+ issueNumber,
+ });
+ }
+ }
+ return findings;
+ },
+ },
{
id: 'dialogue.on-the-nose',
sources: ['manuscript'],
diff --git a/server/lib/editorial/dialogue.js b/server/lib/editorial/dialogue.js
index e1e7586045..32ae3bd79e 100644
--- a/server/lib/editorial/dialogue.js
+++ b/server/lib/editorial/dialogue.js
@@ -52,16 +52,36 @@ export const NON_SPEECH_TAGS = Object.freeze([
// Plain, invisible speech tags — the ones a writer SHOULD use. Presence of any
// of these (or an action beat) is what makes a dialogue line "attributed" for
-// the attribution-clarity scan. Stored as surface forms (matched case-insens.).
-const PLAIN_SPEECH_TAGS = Object.freeze([
- 'said', 'says', 'say', 'asked', 'asks', 'ask', 'replied', 'replies',
- 'whispered', 'whispers', 'shouted', 'shouts', 'muttered', 'mutters',
- 'murmured', 'murmurs', 'answered', 'answers', 'called', 'calls', 'cried',
- 'cries', 'yelled', 'yells', 'snapped', 'snaps', 'breathed', 'breathes',
- 'added', 'adds', 'continued', 'continues', 'stated', 'states', 'demanded',
- 'demands', 'told', 'tells', 'spoke', 'speaks',
+// the attribution-clarity scan. Grouped by base lemma so the tag-variety check
+// (#1587) can collapse inflections ("said"/"says") onto one verb when measuring
+// per-scene monotony; the surface forms include irregulars (said, told, spoke)
+// that inflectVerb() can't generate, so the groups are the source of truth.
+export const PLAIN_SPEECH_TAG_GROUPS = Object.freeze([
+ { base: 'say', forms: ['said', 'says', 'say'] },
+ { base: 'ask', forms: ['asked', 'asks', 'ask'] },
+ { base: 'reply', forms: ['replied', 'replies'] },
+ { base: 'whisper', forms: ['whispered', 'whispers'] },
+ { base: 'shout', forms: ['shouted', 'shouts'] },
+ { base: 'mutter', forms: ['muttered', 'mutters'] },
+ { base: 'murmur', forms: ['murmured', 'murmurs'] },
+ { base: 'answer', forms: ['answered', 'answers'] },
+ { base: 'call', forms: ['called', 'calls'] },
+ { base: 'cry', forms: ['cried', 'cries'] },
+ { base: 'yell', forms: ['yelled', 'yells'] },
+ { base: 'snap', forms: ['snapped', 'snaps'] },
+ { base: 'breathe', forms: ['breathed', 'breathes'] },
+ { base: 'add', forms: ['added', 'adds'] },
+ { base: 'continue', forms: ['continued', 'continues'] },
+ { base: 'state', forms: ['stated', 'states'] },
+ { base: 'demand', forms: ['demanded', 'demands'] },
+ { base: 'tell', forms: ['told', 'tells'] },
+ { base: 'speak', forms: ['spoke', 'speaks'] },
]);
+// Flattened surface forms — kept for the attribution scan's PLAIN_TAG_RE, which
+// only needs "is this token a plain speech tag", not which lemma it maps to.
+const PLAIN_SPEECH_TAGS = Object.freeze(PLAIN_SPEECH_TAG_GROUPS.flatMap((g) => g.forms));
+
function escapeRegExp(s) {
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
@@ -369,3 +389,217 @@ export function attributeDialogueByOwner(text, owners) {
}
return result;
}
+
+// ---------------------------------------------------------------------------
+// Dialogue tag variety / within-scene tag monotony (#1587)
+// ---------------------------------------------------------------------------
+//
+// The said-bookisms scan flags ornate tags; this scan flags the opposite tics
+// at the *scene* grain: one tag verb hammered over and over ("she said" eight
+// times in a scene) reads as monotony, while a different fancy verb on nearly
+// every line ("said / asked / replied / murmured / whispered" churn) reads as a
+// thesaurus rummage. Both pull the reader out — the craft target is mostly the
+// invisible "said"/"asked" with enough variation to stay unnoticed.
+//
+// "Scene" is approximated by splitting on common manuscript scene dividers; a
+// section with no dividers is treated as a single scene (the right fallback).
+
+// Map a plain-tag base → its inflected surface forms, honoring an allow-list of
+// muted bases. Mirrors buildVerbForms() but reads the explicit PLAIN groups
+// (irregulars like said/told/spoke can't be generated by inflectVerb()).
+function buildPlainTagForms(opts = {}) {
+ const allow = new Set((Array.isArray(opts.allowWords) ? opts.allowWords : []).map(normalizeWord).filter(Boolean));
+ const formToBase = new Map();
+ for (const { base, forms } of PLAIN_SPEECH_TAG_GROUPS) {
+ if (allow.has(base)) continue;
+ for (const f of forms) {
+ const norm = normalizeWord(f);
+ if (norm && !allow.has(norm) && !formToBase.has(norm)) formToBase.set(norm, base);
+ }
+ }
+ return { formToBase };
+}
+
+/**
+ * Inventory the *speech* dialogue tags in `text` — every plain ("said", "asked")
+ * or ornate ("opined") tag verb sitting beside a double-quote span, mapped back
+ * to its base lemma so inflections collapse. Non-speech action "tags" ("she
+ * smiled") are deliberately excluded: they aren't speech-tag vocabulary and are
+ * the said-bookisms scan's concern. Reuses the same after/before quote matchers
+ * and the same punctuation/case gating as findSaidBookisms(), so a narrated verb
+ * ("the engine growled") or an action beat after a complete sentence is not
+ * counted as a tag.
+ *
+ * @param {string} text
+ * @param {{ allowWords?: string[], extraWords?: string[] }} [opts]
+ * allowWords — bases to mute; extraWords — extra ornate bases to count as tags.
+ * @returns {Array<{ verb: string, index: number, anchor: string }>} position-ordered.
+ */
+export function inventoryDialogueTags(text, opts = {}) {
+ if (typeof text !== 'string' || !text) return [];
+ const plain = buildPlainTagForms(opts);
+ const ornate = buildVerbForms(SAID_BOOKISMS, opts);
+ const formToBase = new Map();
+ for (const [f, b] of plain.formToBase) formToBase.set(f, b);
+ // Plain wins on overlap (none today), so only add ornate forms not already mapped.
+ for (const [f, b] of ornate.formToBase) if (!formToBase.has(f)) formToBase.set(f, b);
+
+ const matchers = buildTagMatchers([...formToBase.keys()]);
+ if (!matchers) return [];
+
+ const out = [];
+ const seen = new Set();
+ const passes = [
+ { re: matchers.after, verbGroup: 2, punctGroup: 1 },
+ { re: matchers.before, verbGroup: 1, punctGroup: null },
+ ];
+ for (const { re, verbGroup, punctGroup } of passes) {
+ re.lastIndex = 0;
+ let m;
+ while ((m = re.exec(text)) !== null) {
+ const matched = m[verbGroup];
+ const base = formToBase.get(matched.toLowerCase());
+ if (!base) continue;
+ // Both plain and ornate tags are speech verbs, so gate them like a bookism:
+ // a period-terminated quote starts a NEW sentence (not a tag), and a
+ // capitalized word after the quote is that sentence's subject (narration).
+ if (punctGroup !== null) {
+ if ((m[punctGroup] || '') === '.') continue;
+ if (matched[0] !== matched[0].toLowerCase()) continue;
+ }
+ const key = `${base}@${m.index}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push({ verb: base, index: m.index, anchor: m[0].trim() });
+ }
+ }
+ return out.sort((a, b) => a.index - b.index);
+}
+
+// A line is a scene divider when it is ONLY a centered break: a markdown heading
+// ("## Scene 2"), or a rule of repeated * - — – • · ~ marks ("***", "* * *",
+// "———"). Such a line ends the current scene and starts the next.
+function isSceneBreakLine(line) {
+ const t = line.trim();
+ if (!t) return false;
+ if (/^#{1,6}\s+\S/.test(t)) return true;
+ return /^(?:[*\-—–•·~][ \t]*){3,}$/.test(t);
+}
+
+/**
+ * Split `text` into scenes on common manuscript scene dividers (centered rules
+ * and markdown scene headings). The divider line itself belongs to neither
+ * adjacent scene. A text with no dividers yields a single scene spanning all of
+ * it — the correct fallback for a manuscript that doesn't mark scene breaks.
+ *
+ * @param {string} text
+ * @returns {Array<{ text: string, index: number, ordinal: number }>}
+ * ordinal is 1-based; index is the absolute offset of the scene's first line.
+ */
+export function splitScenes(text) {
+ if (typeof text !== 'string' || !text) return [];
+ const scenes = [];
+ let buf = [];
+ let start = -1;
+ const flush = () => {
+ if (start >= 0 && buf.join('').trim()) {
+ scenes.push({ text: buf.join(''), index: start, ordinal: scenes.length + 1 });
+ }
+ buf = [];
+ start = -1;
+ };
+ // Keep line terminators so absolute offsets stay exact across the split.
+ const re = /[^\n]*\n|[^\n]+$/g;
+ let m;
+ while ((m = re.exec(text)) !== null) {
+ const line = m[0];
+ if (isSceneBreakLine(line)) {
+ flush();
+ continue;
+ }
+ if (start < 0) start = m.index;
+ buf.push(line);
+ }
+ flush();
+ return scenes;
+}
+
+/**
+ * Flag dialogue-tag variety problems per scene: within-scene MONOTONY (one tag
+ * verb dominates a tag-dense scene) and OVER-VARIATION (almost every tagged line
+ * uses a different verb — thesaurus churn). Scenes with too few tags to judge
+ * are skipped. Pure: splits scenes deterministically, inventories tags, and
+ * applies count/ratio thresholds.
+ *
+ * @param {string} text
+ * @param {{ allowWords?: string[], extraWords?: string[], minTags?: number,
+ * monotonyCount?: number, monotonyRatio?: number,
+ * overVariationRatio?: number, minDistinct?: number }} [opts]
+ * minTags — speech tags a scene needs before variety is judged (default 6).
+ * monotonyCount / monotonyRatio — dominant verb must hit BOTH a raw count and
+ * a share-of-tags ratio to flag monotony (defaults 6 / 0.7).
+ * overVariationRatio / minDistinct — distinct-verbs ÷ tags must exceed the
+ * ratio with at least minDistinct verbs to flag churn (defaults 0.85 / 5).
+ * @returns {Array<{ type: 'monotony'|'over-variation', sceneOrdinal: number,
+ * verb: string|null, count: number, total: number, distinct: number,
+ * index: number, anchor: string }>}
+ */
+export function findDialogueTagVariety(text, opts = {}) {
+ if (typeof text !== 'string' || !text) return [];
+ const minTags = Math.max(3, Number.isInteger(opts.minTags) ? opts.minTags : 6);
+ const monotonyCount = Math.max(2, Number.isInteger(opts.monotonyCount) ? opts.monotonyCount : 6);
+ const monotonyRatio = Number.isFinite(opts.monotonyRatio) ? opts.monotonyRatio : 0.7;
+ const overVariationRatio = Number.isFinite(opts.overVariationRatio) ? opts.overVariationRatio : 0.85;
+ const minDistinct = Math.max(2, Number.isInteger(opts.minDistinct) ? opts.minDistinct : 5);
+
+ const out = [];
+ for (const scene of splitScenes(text)) {
+ const tags = inventoryDialogueTags(scene.text, opts);
+ const total = tags.length;
+ if (total < minTags) continue;
+
+ const freq = new Map();
+ const firstAt = new Map();
+ for (const t of tags) {
+ freq.set(t.verb, (freq.get(t.verb) || 0) + 1);
+ if (!firstAt.has(t.verb)) firstAt.set(t.verb, t);
+ }
+ const distinct = freq.size;
+
+ // Dominant verb — monotony when it BOTH repeats enough AND owns most tags.
+ let domVerb = null;
+ let domCount = 0;
+ for (const [verb, count] of freq) {
+ if (count > domCount) { domCount = count; domVerb = verb; }
+ }
+ if (domVerb && domCount >= monotonyCount && domCount / total >= monotonyRatio) {
+ const anchorHit = firstAt.get(domVerb);
+ out.push({
+ type: 'monotony',
+ sceneOrdinal: scene.ordinal,
+ verb: domVerb,
+ count: domCount,
+ total,
+ distinct,
+ index: scene.index + (anchorHit ? anchorHit.index : 0),
+ anchor: anchorHit ? anchorHit.anchor : '',
+ });
+ continue; // a monotone scene can't also be over-varied; don't double-report.
+ }
+
+ // Over-variation — a fresh verb on (nearly) every tagged line.
+ if (distinct >= minDistinct && distinct / total >= overVariationRatio) {
+ out.push({
+ type: 'over-variation',
+ sceneOrdinal: scene.ordinal,
+ verb: null,
+ count: distinct,
+ total,
+ distinct,
+ index: scene.index,
+ anchor: tags[0].anchor,
+ });
+ }
+ }
+ return out;
+}
diff --git a/server/lib/editorial/dialogue.test.js b/server/lib/editorial/dialogue.test.js
index ff1d2a8ba3..f641c5c02c 100644
--- a/server/lib/editorial/dialogue.test.js
+++ b/server/lib/editorial/dialogue.test.js
@@ -3,6 +3,9 @@ import {
findSaidBookisms,
findUnattributedDialogueRuns,
attributeDialogueByOwner,
+ inventoryDialogueTags,
+ splitScenes,
+ findDialogueTagVariety,
SAID_BOOKISMS,
NON_SPEECH_TAGS,
} from './dialogue.js';
@@ -268,3 +271,128 @@ describe('attributeDialogueByOwner', () => {
expect(unattributed).toBe(1);
});
});
+
+describe('inventoryDialogueTags', () => {
+ it('collapses inflections onto a base lemma (said/says → say)', () => {
+ const tags = inventoryDialogueTags('"A," she said.\n"B," he says.');
+ expect(tags.map((t) => t.verb)).toEqual(['say', 'say']);
+ });
+
+ it('inventories an ornate tag as its base alongside plain tags', () => {
+ const tags = inventoryDialogueTags('"A," she said.\n"B," he opined.');
+ expect(tags.map((t) => t.verb)).toEqual(['say', 'opine']);
+ });
+
+ it('excludes non-speech action "tags" (those are the said-bookisms scan\'s job)', () => {
+ const tags = inventoryDialogueTags('"Of course," she smiled.');
+ expect(tags).toHaveLength(0);
+ });
+
+ it('does not count a narrated verb with no adjacent quote', () => {
+ expect(inventoryDialogueTags('The engine said nothing as it idled.')).toHaveLength(0);
+ });
+
+ it('does not count an action beat after a complete (period-terminated) line', () => {
+ // "She added a log to the fire." is narration, not a tag — the quote ended on a period.
+ expect(inventoryDialogueTags('"Done." She added a log to the fire.')).toHaveLength(0);
+ });
+
+ it('honors allowWords to mute a tag verb', () => {
+ const tags = inventoryDialogueTags('"A," she said.\n"B," he asked.', { allowWords: ['say'] });
+ expect(tags.map((t) => t.verb)).toEqual(['ask']);
+ });
+});
+
+describe('splitScenes', () => {
+ it('returns a single scene when there are no dividers', () => {
+ const scenes = splitScenes('Line one.\nLine two.');
+ expect(scenes).toHaveLength(1);
+ expect(scenes[0].ordinal).toBe(1);
+ });
+
+ it('splits on a centered rule (***) and excludes the divider line', () => {
+ const scenes = splitScenes('"A," she said.\n***\n"B," he said.');
+ expect(scenes).toHaveLength(2);
+ expect(scenes[0].text).toContain('A');
+ expect(scenes[1].text).toContain('B');
+ expect(scenes[1].ordinal).toBe(2);
+ });
+
+ it('splits on a markdown scene heading', () => {
+ const scenes = splitScenes('First.\n## Scene 2\nSecond.');
+ expect(scenes).toHaveLength(2);
+ });
+
+ it('keeps absolute offsets so a scene index maps back into the text', () => {
+ const text = 'First.\n***\nSecond.';
+ const scenes = splitScenes(text);
+ expect(text.slice(scenes[1].index)).toContain('Second');
+ });
+
+ it('returns nothing for empty / non-string input', () => {
+ expect(splitScenes('')).toEqual([]);
+ expect(splitScenes(null)).toEqual([]);
+ });
+});
+
+describe('findDialogueTagVariety', () => {
+ const monotoneScene = Array.from({ length: 6 }, (_, i) => `"Line ${i}," she said.`).join('\n');
+
+ it('flags within-scene monotony when one tag verb dominates', () => {
+ const hits = findDialogueTagVariety(monotoneScene);
+ expect(hits).toHaveLength(1);
+ expect(hits[0]).toMatchObject({ type: 'monotony', verb: 'say', count: 6, total: 6, sceneOrdinal: 1 });
+ });
+
+ it('flags over-variation when nearly every tagged line uses a different verb', () => {
+ const churn = [
+ '"A," she said.',
+ '"B," he asked.',
+ '"C," she replied.',
+ '"D," he whispered.',
+ '"E," she murmured.',
+ '"F," he shouted.',
+ ].join('\n');
+ const hits = findDialogueTagVariety(churn);
+ expect(hits).toHaveLength(1);
+ expect(hits[0]).toMatchObject({ type: 'over-variation', distinct: 6, total: 6 });
+ });
+
+ it('does not flag a scene with too few tags to judge', () => {
+ expect(findDialogueTagVariety('"A," she said.\n"B," he said.')).toHaveLength(0);
+ });
+
+ it('does not flag a healthily varied, said-dominant scene', () => {
+ // Mostly invisible "said" with a little variation — the craft target.
+ const healthy = [
+ '"A," she said.',
+ '"B," he said.',
+ '"C," she asked.',
+ '"D," he said.',
+ '"E," she replied.',
+ '"F," he said.',
+ ].join('\n');
+ expect(findDialogueTagVariety(healthy)).toHaveLength(0);
+ });
+
+ it('judges each scene independently across a divider', () => {
+ const text = `${monotoneScene}\n***\n"X," she said.\n"Y," he said.`;
+ const hits = findDialogueTagVariety(text);
+ // Only the first scene is monotone; the trailing 2-tag scene is too small.
+ expect(hits).toHaveLength(1);
+ expect(hits[0].sceneOrdinal).toBe(1);
+ });
+
+ it('respects monotonyCount/minTags overrides', () => {
+ const text = Array.from({ length: 4 }, (_, i) => `"L${i}," she said.`).join('\n');
+ expect(findDialogueTagVariety(text)).toHaveLength(0); // 4 tags < default minTags 6
+ const hits = findDialogueTagVariety(text, { minTags: 4, monotonyCount: 4 });
+ expect(hits).toHaveLength(1);
+ expect(hits[0].type).toBe('monotony');
+ });
+
+ it('returns nothing for empty / non-string input', () => {
+ expect(findDialogueTagVariety('')).toEqual([]);
+ expect(findDialogueTagVariety(null)).toEqual([]);
+ });
+});