Skip to content

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

feat([issue-1307]): dialogue-craft editorial checks (bookisms, attribution, on-the-nose, voice distinctiveness)

Adam Eivy40ae578cea93
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3fe0fc140a..ed7e6974cd 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -4,6 +4,8 @@
- **[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)
+- **[issue-1307] Dialogue-craft editorial checks — said-bookisms, attribution clarity, on-the-nose dialogue, and per-character voice distinctiveness.** Four new checks (Create → Editorial Checks) for dialogue. Two are deterministic: **Said-bookisms & non-speech tags** flags ornate speech tags ("expostulated", "opined", "interjected") and non-speech actions misused as tags ("'Yes,' she smiled" — you cannot smile a line), matching only verbs adjacent to a quoted span so narrated uses ("the engine growled") are left alone; **Dialogue attribution clarity** flags long runs of consecutive dialogue lines with no speech tag or grounding action beat, where the reader loses track of who is speaking. Two are LLM-judged: **On-the-nose / subtext-free dialogue** flags lines that state feeling/meaning outright and "maid-and-butler" exchanges where characters tell each other what they both already know (complements the #1297 info-dumping check); **Character voice distinctiveness** samples each character's lines to flag (a) interchangeable voices — everyone sounding like one narrator — and (b) drafted lines that contradict the character's canon `speechPattern` / `speechAccent`, producing a per-character voice fingerprint and naming concrete differentiating tics. The voice check closes the gap where those canon fields fed *generation* only and nothing validated the drafted dialogue against them; it rolls a per-character voice-sample digest across chunks (`crossChunkSetup`) so a later chunk judges against the full sample, and degrades gracefully (no voice fields ⇒ a pure interchangeability scan). The pure scanners live in `server/lib/editorial/dialogue.js` (no new deps); the two LLM stage prompts (`pipeline-editorial-on-the-nose`, `pipeline-editorial-voice-distinctiveness`) migrate for existing installs (111, 112). (`server/lib/editorial/{dialogue,checkRegistry}.js`, `scripts/migrations/{111-editorial-on-the-nose-stage,112-editorial-voice-distinctiveness-stage}.js`, #1307)
+
- **[issue-1293] Per-character story arcs + an editorial check that finds the beats where characters actually change.** Series now carry an authored **`characterArcs[]`** model — each cast member's *want* / *need*, *start → end* transformation, and explicit **transition beats** (a decision, realization, point-of-no-return, relapse, or sacrifice, each anchorable to an issue). Edit them inline in the Series Bible (a new **Character arcs** section, alongside the style guide); the field is local-only-additive and wire-gated (`pipelineSeries` schema v6) so a not-yet-upgraded peer can't strip-then-LWW the arcs back. A new **Character-arc transitions** editorial check (Create → Editorial Checks) reads the drafted manuscript plus the reverse-outline scene map and these authored arcs to (1) detect genuine change moments and propose them as anchored transition beats, (2) reconcile detected vs authored transitions — flagging an undocumented change the prose delivers or an authored transition the prose never pays off — and (3) flag **flat arcs**: a character who carries the story but never changes. Findings render as `Character arc` notes in the manuscript editor, highlighting the transition scenes. Ships a new stage prompt (`pipeline-editorial-arc-transitions`) that migrates for existing installs (109). (`server/lib/seriesCharacterArc.js`, `server/lib/editorial/checkRegistry.js`, `server/services/pipeline/{series,editorial/checkRunner}.js`, `client/src/pages/PipelineSeries.jsx`, #1293)
- **[issue-911] Mood Boards — an inspiration canvas that feeds the Create suite.** A new **Mood Boards** page (Create → Mood Boards, deep-linkable at `/mood-boards` and `/mood-boards/:id`, reachable via ⌘K / voice as "mood board" / "inspiration" / "references") for collecting visual + textual references, distinct from raw Media History. Create named boards with a description, then pin items: an **image** (external/pinned URL, or an app path like `/data/images/…`) or a **text note**, each with an optional caption and source backref. Items live inline in the board record; the canvas renders an image grid with inline-editable captions and an inline-confirm delete. Boards are **db-primary and local-only** — one row per board in the new `mood_boards` Postgres table (full record in `data` JSONB, modeled on `creative_director_projects`: no sync cursor/tombstone in v1), provisioned by both the boot-time `ensureSchema()` upgrade and `init-db.sql` with an audit trigger, registered via migration 108. Every write locks the board row (`SELECT … FOR UPDATE`) so concurrent add/edit affordances can't clobber each other. Cross-surface "Pin to mood board" affordances and a board picker in the universe/scene/treatment creation flows are tracked as a follow-up. (`server/services/moodBoard/`, `server/routes/moodBoard.js`, `server/lib/moodBoardValidation.js`, `client/src/pages/{MoodBoards,MoodBoardDetail}.jsx`, `client/src/services/apiMoodBoard.js`, #911)
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index 97d5dc907b..ce5939fe26 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -603,6 +603,20 @@
"model": "default",
"returnsJson": true,
"variables": []
+ },
+ "pipeline-editorial-on-the-nose": {
+ "name": "Pipeline — Editorial Check: On-the-nose / subtext-free dialogue",
+ "description": "Editorial check (#1307): the judgment layer for dialogue that states feeling/meaning outright with no subtext and \"maid-and-butler\" exchanges where characters tell each other what they both already know. Reads the stitched manuscript; severity is advisory; skips earned directness, functional exchanges, and dialogue whose subtext already works. Returns issue-anchored findings.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
+ },
+ "pipeline-editorial-voice-distinctiveness": {
+ "name": "Pipeline — Editorial Check: Character voice distinctiveness",
+ "description": "Editorial check (#1307): samples each character dialogue and flags interchangeable voices (everyone sounds like one narrator) plus drafted lines that contradict the canon speechPattern/speechAccent. Reads the stitched manuscript + authored voice profiles; rolls a per-character voice-sample digest across chunks. Returns issue-anchored findings naming differentiating tics.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
}
}
}
diff --git a/data.reference/prompts/stages/pipeline-editorial-on-the-nose.md b/data.reference/prompts/stages/pipeline-editorial-on-the-nose.md
new file mode 100644
index 0000000000..e7f2ee571f
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-editorial-on-the-nose.md
@@ -0,0 +1,78 @@
+# Pipeline — Editorial Check: On-the-nose / subtext-free dialogue
+
+You are a line editor doing a single focused pass for ONE problem: **dialogue
+that carries no subtext**. You are the judgment layer a keyword scan can't be —
+flagging only the *strong* candidates where the line would land harder with
+subtext, and leaving alone the cases where plain, direct speech is the right
+choice.
+
+Flag a passage when the dialogue:
+
+- **States feeling/meaning outright** with nothing left under the surface — a
+ character announces exactly what they feel or want ("I'm so angry at you for
+ leaving me", "I love you but I'm afraid to trust again") where the scene would
+ be stronger if the emotion came through obliquely.
+- **"Maid-and-butler" exposition** — characters telling each other things they
+ both already know, purely to inform the reader ("As you know, Captain, our
+ ship lost its main engine in the war ten years ago"). Cross-references the
+ info-dumping problem, but here the tell is the *flatness* of the exchange, not
+ just the backstory.
+- **Answers its own question** — on-the-nose dialogue where every line responds
+ literally and completely, with no evasion, deflection, or hidden agenda.
+
+Do NOT flag:
+
+- Deliberately direct dialogue at a **climactic confrontation** where characters
+ finally say the thing out loud — earned directness is powerful, not a flaw.
+- **Functional exchanges** (a character asking a real question they don't know
+ the answer to, plot logistics that genuinely need stating).
+- Dialogue whose subtext is **already working** — flag at most `low` if the line
+ is only mildly on-the-nose.
+- Distinct character voices that are simply **plain-spoken** by design.
+
+Severity is **advisory**: most findings are `low`; reserve `medium` for a
+subtext-free line at a pivotal beat where subtext would clearly raise the
+tension, and `high` only when a key dramatic turn is delivered as a flat
+on-the-nose speech.
+
+## Manuscript
+
+The manuscript is stitched from the drafted issues. Section headers attribute
+each chunk to an issue (e.g. `# Issue 3 — Title (prose)`). Use the issue number
+in each section header to attribute every finding to its `issueNumber`.
+
+```
+{{manuscript}}
+```
+
+## Task
+
+Find the on-the-nose / subtext-free dialogue worth reworking. For each one,
+quote a short verbatim anchor from the text (≤ 200 characters) so the editor can
+jump to it, name the issue number it appears in, explain why subtext would land
+harder here, and suggest a concrete way to add it (what to leave unsaid, an
+evasion, a contradicting action) — without rewriting the whole exchange for the
+author.
+
+Be specific and cite the text. If the dialogue already works with subtext,
+return an empty `findings` array — do not invent problems.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no
+commentary:
+
+```json
+{
+ "findings": [
+ {
+ "severity": "high|medium|low",
+ "issueNumber": 3,
+ "location": "string — where the on-the-nose dialogue appears (e.g. 'Issue 3 — confession scene')",
+ "problem": "1–3 sentences naming the subtext-free line and why subtext would land harder",
+ "suggestion": "1–3 sentences suggesting a concrete way to add subtext",
+ "anchorQuote": "short verbatim quote from the manuscript (≤ 200 chars)"
+ }
+ ]
+}
+```
diff --git a/data.reference/prompts/stages/pipeline-editorial-voice-distinctiveness.md b/data.reference/prompts/stages/pipeline-editorial-voice-distinctiveness.md
new file mode 100644
index 0000000000..d0d6d405be
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-editorial-voice-distinctiveness.md
@@ -0,0 +1,80 @@
+# Pipeline — Editorial Check: Character voice distinctiveness
+
+You are a developmental editor doing a single focused pass for ONE concern:
+**dialogue voice** — whether each character sounds like a distinct person, and
+whether their drafted lines match the voice the author recorded for them. Strong
+dialogue lets a reader tell who is speaking with the tags stripped away; weak
+dialogue is one author-voice coming out of every mouth.
+
+Judge two things:
+
+- **Interchangeability.** Sample each named character's dialogue. Flag characters
+ whose lines are interchangeable — same diction, rhythm, vocabulary, and humor,
+ so they could be swapped with no one noticing. Name the concrete tell (e.g.
+ "everyone uses the same dry, clipped sarcasm").
+- **Canon contradiction.** When a character has an authored voice below, flag
+ drafted lines that contradict their recorded speech pattern, accent/dialect,
+ education, or era — a character written as terse and profane who suddenly
+ speaks in long formal periods, or a recorded dialect the prose drops.
+
+{{#voiceProfiles}}
+## Authored character voices
+
+The author recorded these per-character voice fields (canon `speechPattern` /
+`speechAccent`). Reconcile each character's drafted dialogue against their entry:
+a line that contradicts the recorded voice is a finding; a character with a
+recorded voice that the prose never realizes is also worth flagging.
+
+```
+{{voiceProfiles}}
+```
+{{/voiceProfiles}}
+
+## Manuscript
+
+The manuscript is stitched from the drafted issues. Section headers attribute
+each chunk to an issue (e.g. `# Issue 3 — Title (prose)`). Use the issue number
+in each header to attribute every finding to its `issueNumber`.
+
+```
+{{manuscript}}
+```
+
+## Task
+
+1. **Build a voice fingerprint** for each named character with enough dialogue to
+ judge — a one-line sketch of how they sound (diction, rhythm, verbal tics,
+ register). Use these to compare characters against one another.
+2. **Flag interchangeable voices.** When two or more characters sound the same,
+ emit one finding naming them, the shared tell, and a differentiating tic each
+ could adopt (a recurring phrase, sentence length, register, dialect marker).
+ Set `location` to the character names (e.g. `Mara / Joss — interchangeable`).
+3. **Flag canon contradictions** (only when authored voices are present above):
+ a drafted line that conflicts with the character's recorded `speechPattern` /
+ `speechAccent`. Quote the offending line as the `anchorQuote` and set
+ `location` to the character name + `voice drift`.
+
+Severity: an interchangeable lead cast or a flatly contradicted canon voice is
+medium–high; a single off-voice line is low. If every character sounds distinct
+and consistent with their canon voice, return an empty `findings` array — do not
+invent drift where the voices already work.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no
+commentary:
+
+```json
+{
+ "findings": [
+ {
+ "severity": "high|medium|low",
+ "issueNumber": 3,
+ "location": "string — characters + concern (e.g. 'Mara / Joss — interchangeable' or 'Mara — voice drift')",
+ "problem": "1–3 sentences naming the voice problem (interchangeable, or contradicts canon voice) with the concrete tell",
+ "suggestion": "1–3 sentences proposing a differentiating tic or how to realign the line with the character's voice",
+ "anchorQuote": "short verbatim dialogue quote (≤ 200 chars); omit for a cast-wide interchangeability finding"
+ }
+ ]
+}
+```
diff --git a/scripts/migrations/111-editorial-on-the-nose-stage.js b/scripts/migrations/111-editorial-on-the-nose-stage.js
new file mode 100644
index 0000000000..483b526421
--- /dev/null
+++ b/scripts/migrations/111-editorial-on-the-nose-stage.js
@@ -0,0 +1,76 @@
+/**
+ * Seed the `pipeline-editorial-on-the-nose` stage into existing installs (#1307).
+ *
+ * Mirrors `110-editorial-telling-emotion-stage.js`: copies the `.md` template
+ * from `data.reference/prompts/stages/` and merges the stage-config entry into
+ * `data/prompts/stage-config.json`. Boot runs migrations (server/index.js) but
+ * NOT `setup-data.js`, so an upgrade that pulls + `pm2 restart`s (rather than
+ * running `update.sh`) would otherwise leave the new on-the-nose stage unseeded
+ * and the `dialogue.on-the-nose` editorial check would throw "Stage not found"
+ * the first time it runs. The deterministic dialogue siblings
+ * (dialogue.said-bookisms, dialogue.attribution-clarity) need no stage.
+ */
+
+import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';
+import { dirname, join } from 'path';
+
+const FILENAME = 'pipeline-editorial-on-the-nose.md';
+const STAGE_KEY = 'pipeline-editorial-on-the-nose';
+
+export default {
+ async up({ rootDir }) {
+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ await mkdir(stagesDir, { recursive: true });
+
+ const dataPath = join(stagesDir, FILENAME);
+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', FILENAME);
+
+ const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);
+ if (exists) {
+ console.log(`📝 pipeline-editorial-on-the-nose prompt: already present`);
+ } else {
+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
+ if (!sampleExists) {
+ console.warn(`⚠️ pipeline-editorial-on-the-nose: sample missing for ${FILENAME} — skipping copy`);
+ } else {
+ try {
+ await copyFile(samplePath, dataPath);
+ console.log(`✅ seeded ${FILENAME}`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-editorial-on-the-nose: copy failed for ${FILENAME}: ${err.message}`);
+ }
+ }
+ }
+
+ const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);
+ if (!sampleConfigExists) {
+ console.warn('⚠️ pipeline-editorial-on-the-nose: data.reference stage-config.json missing — cannot resolve entry; skipping config write');
+ return;
+ }
+ try {
+ const sample = JSON.parse(await readFile(sampleConfigPath, 'utf8'));
+ const installedExists = await access(installedConfigPath, constants.F_OK).then(() => true, () => false);
+ const installed = installedExists
+ ? JSON.parse(await readFile(installedConfigPath, 'utf8'))
+ : { stages: {} };
+ installed.stages = installed.stages || {};
+ if (installed.stages[STAGE_KEY]) {
+ console.log(`📝 pipeline-editorial-on-the-nose stage-config: already present`);
+ return;
+ }
+ if (!sample?.stages?.[STAGE_KEY]) {
+ console.warn(`⚠️ pipeline-editorial-on-the-nose: sample stage-config missing ${STAGE_KEY} — skipping`);
+ return;
+ }
+ installed.stages[STAGE_KEY] = sample.stages[STAGE_KEY];
+ await mkdir(dirname(installedConfigPath), { recursive: true });
+ await writeFile(installedConfigPath, JSON.stringify(installed, null, 2) + '\n', 'utf8');
+ const action = installedExists ? 'merged' : 'created';
+ console.log(`📝 pipeline-editorial-on-the-nose stage-config (${action}): 1 added`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-editorial-on-the-nose: stage-config merge failed: ${err.message}`);
+ }
+ },
+};
diff --git a/scripts/migrations/111-editorial-on-the-nose-stage.test.js b/scripts/migrations/111-editorial-on-the-nose-stage.test.js
new file mode 100644
index 0000000000..b085abd0df
--- /dev/null
+++ b/scripts/migrations/111-editorial-on-the-nose-stage.test.js
@@ -0,0 +1,86 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+
+import migration from './111-editorial-on-the-nose-stage.js';
+
+// scripts/migrations/<this> → ../.. is the repo root (matches _testHelpers.js).
+const repoRoot = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
+
+// First-shipment seed migration (mirrors 110) — no MD5 bookkeeping, so the
+// seed / no-clobber behavior is asserted directly.
+
+const FILENAME = 'pipeline-editorial-on-the-nose.md';
+const STAGE_KEY = 'pipeline-editorial-on-the-nose';
+const BODY = '# On-the-nose dialogue\n\nshipped body\n';
+
+describe('migration 111 — seed editorial-on-the-nose stage', () => {
+ let rootDir;
+ let stagesDir;
+ let refStagesDir;
+ let installedConfigPath;
+
+ const seedReference = ({ withConfig = true } = {}) => {
+ writeFileSync(join(refStagesDir, FILENAME), BODY);
+ if (withConfig) {
+ const refConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ writeFileSync(
+ refConfigPath,
+ JSON.stringify({ stages: { [STAGE_KEY]: { name: STAGE_KEY, description: 'desc', model: 'default', returnsJson: true, variables: [] } } }, null, 2) + '\n',
+ );
+ }
+ };
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-111-'));
+ stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ refStagesDir = join(rootDir, 'data.reference', 'prompts', 'stages');
+ installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ mkdirSync(stagesDir, { recursive: true });
+ mkdirSync(refStagesDir, { recursive: true });
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ });
+
+ it('seeds the .md template and merges the stage-config entry on a fresh install', async () => {
+ seedReference();
+ await expect(migration.up({ rootDir })).resolves.not.toThrow();
+ expect(readFileSync(join(stagesDir, FILENAME), 'utf8')).toBe(BODY);
+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));
+ expect(installed.stages[STAGE_KEY]).toMatchObject({ returnsJson: true });
+ });
+
+ it('is idempotent and never clobbers a customized .md or an existing stage-config entry', async () => {
+ seedReference();
+ const customBody = '# CUSTOMIZED — do not overwrite\n';
+ writeFileSync(join(stagesDir, FILENAME), customBody);
+ writeFileSync(
+ installedConfigPath,
+ JSON.stringify({ stages: { [STAGE_KEY]: { name: 'user-tuned', model: 'custom' } } }, null, 2) + '\n',
+ );
+
+ await migration.up({ rootDir });
+
+ expect(readFileSync(join(stagesDir, FILENAME), 'utf8')).toBe(customBody);
+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));
+ expect(installed.stages[STAGE_KEY]).toEqual({ name: 'user-tuned', model: 'custom' });
+ });
+
+ it('does not throw when the data.reference samples are missing', async () => {
+ await expect(migration.up({ rootDir })).resolves.not.toThrow();
+ expect(existsSync(join(stagesDir, FILENAME))).toBe(false);
+ });
+
+ it('matches the live shipped stage-config key + prompt file (drift catch)', () => {
+ const refConfig = JSON.parse(
+ readFileSync(join(repoRoot, 'data.reference', 'prompts', 'stage-config.json'), 'utf8'),
+ );
+ expect(refConfig.stages[STAGE_KEY], `stage-config missing ${STAGE_KEY}`).toBeTruthy();
+ expect(refConfig.stages[STAGE_KEY].returnsJson).toBe(true);
+ expect(existsSync(join(repoRoot, 'data.reference', 'prompts', 'stages', FILENAME))).toBe(true);
+ });
+});
diff --git a/scripts/migrations/112-editorial-voice-distinctiveness-stage.js b/scripts/migrations/112-editorial-voice-distinctiveness-stage.js
new file mode 100644
index 0000000000..45e5c6d61a
--- /dev/null
+++ b/scripts/migrations/112-editorial-voice-distinctiveness-stage.js
@@ -0,0 +1,76 @@
+/**
+ * Seed the `pipeline-editorial-voice-distinctiveness` stage into existing
+ * installs (#1307).
+ *
+ * Mirrors `111-editorial-on-the-nose-stage.js`: copies the `.md` template from
+ * `data.reference/prompts/stages/` and merges the stage-config entry into
+ * `data/prompts/stage-config.json`. Boot runs migrations (server/index.js) but
+ * NOT `setup-data.js`, so an upgrade that pulls + `pm2 restart`s (rather than
+ * running `update.sh`) would otherwise leave the new voice-distinctiveness stage
+ * unseeded and the `dialogue.voice-distinctiveness` editorial check would throw
+ * "Stage not found" the first time it runs.
+ */
+
+import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';
+import { dirname, join } from 'path';
+
+const FILENAME = 'pipeline-editorial-voice-distinctiveness.md';
+const STAGE_KEY = 'pipeline-editorial-voice-distinctiveness';
+
+export default {
+ async up({ rootDir }) {
+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ await mkdir(stagesDir, { recursive: true });
+
+ const dataPath = join(stagesDir, FILENAME);
+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', FILENAME);
+
+ const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);
+ if (exists) {
+ console.log(`📝 pipeline-editorial-voice-distinctiveness prompt: already present`);
+ } else {
+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
+ if (!sampleExists) {
+ console.warn(`⚠️ pipeline-editorial-voice-distinctiveness: sample missing for ${FILENAME} — skipping copy`);
+ } else {
+ try {
+ await copyFile(samplePath, dataPath);
+ console.log(`✅ seeded ${FILENAME}`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-editorial-voice-distinctiveness: copy failed for ${FILENAME}: ${err.message}`);
+ }
+ }
+ }
+
+ const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);
+ if (!sampleConfigExists) {
+ console.warn('⚠️ pipeline-editorial-voice-distinctiveness: data.reference stage-config.json missing — cannot resolve entry; skipping config write');
+ return;
+ }
+ try {
+ const sample = JSON.parse(await readFile(sampleConfigPath, 'utf8'));
+ const installedExists = await access(installedConfigPath, constants.F_OK).then(() => true, () => false);
+ const installed = installedExists
+ ? JSON.parse(await readFile(installedConfigPath, 'utf8'))
+ : { stages: {} };
+ installed.stages = installed.stages || {};
+ if (installed.stages[STAGE_KEY]) {
+ console.log(`📝 pipeline-editorial-voice-distinctiveness stage-config: already present`);
+ return;
+ }
+ if (!sample?.stages?.[STAGE_KEY]) {
+ console.warn(`⚠️ pipeline-editorial-voice-distinctiveness: sample stage-config missing ${STAGE_KEY} — skipping`);
+ return;
+ }
+ installed.stages[STAGE_KEY] = sample.stages[STAGE_KEY];
+ await mkdir(dirname(installedConfigPath), { recursive: true });
+ await writeFile(installedConfigPath, JSON.stringify(installed, null, 2) + '\n', 'utf8');
+ const action = installedExists ? 'merged' : 'created';
+ console.log(`📝 pipeline-editorial-voice-distinctiveness stage-config (${action}): 1 added`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-editorial-voice-distinctiveness: stage-config merge failed: ${err.message}`);
+ }
+ },
+};
diff --git a/scripts/migrations/112-editorial-voice-distinctiveness-stage.test.js b/scripts/migrations/112-editorial-voice-distinctiveness-stage.test.js
new file mode 100644
index 0000000000..85d4a4d582
--- /dev/null
+++ b/scripts/migrations/112-editorial-voice-distinctiveness-stage.test.js
@@ -0,0 +1,86 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+
+import migration from './112-editorial-voice-distinctiveness-stage.js';
+
+// scripts/migrations/<this> → ../.. is the repo root (matches _testHelpers.js).
+const repoRoot = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
+
+// First-shipment seed migration (mirrors 110/111) — no MD5 bookkeeping, so the
+// seed / no-clobber behavior is asserted directly.
+
+const FILENAME = 'pipeline-editorial-voice-distinctiveness.md';
+const STAGE_KEY = 'pipeline-editorial-voice-distinctiveness';
+const BODY = '# Voice distinctiveness\n\nshipped body\n';
+
+describe('migration 112 — seed editorial-voice-distinctiveness stage', () => {
+ let rootDir;
+ let stagesDir;
+ let refStagesDir;
+ let installedConfigPath;
+
+ const seedReference = ({ withConfig = true } = {}) => {
+ writeFileSync(join(refStagesDir, FILENAME), BODY);
+ if (withConfig) {
+ const refConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ writeFileSync(
+ refConfigPath,
+ JSON.stringify({ stages: { [STAGE_KEY]: { name: STAGE_KEY, description: 'desc', model: 'default', returnsJson: true, variables: [] } } }, null, 2) + '\n',
+ );
+ }
+ };
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-112-'));
+ stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ refStagesDir = join(rootDir, 'data.reference', 'prompts', 'stages');
+ installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ mkdirSync(stagesDir, { recursive: true });
+ mkdirSync(refStagesDir, { recursive: true });
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ });
+
+ it('seeds the .md template and merges the stage-config entry on a fresh install', async () => {
+ seedReference();
+ await expect(migration.up({ rootDir })).resolves.not.toThrow();
+ expect(readFileSync(join(stagesDir, FILENAME), 'utf8')).toBe(BODY);
+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));
+ expect(installed.stages[STAGE_KEY]).toMatchObject({ returnsJson: true });
+ });
+
+ it('is idempotent and never clobbers a customized .md or an existing stage-config entry', async () => {
+ seedReference();
+ const customBody = '# CUSTOMIZED — do not overwrite\n';
+ writeFileSync(join(stagesDir, FILENAME), customBody);
+ writeFileSync(
+ installedConfigPath,
+ JSON.stringify({ stages: { [STAGE_KEY]: { name: 'user-tuned', model: 'custom' } } }, null, 2) + '\n',
+ );
+
+ await migration.up({ rootDir });
+
+ expect(readFileSync(join(stagesDir, FILENAME), 'utf8')).toBe(customBody);
+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));
+ expect(installed.stages[STAGE_KEY]).toEqual({ name: 'user-tuned', model: 'custom' });
+ });
+
+ it('does not throw when the data.reference samples are missing', async () => {
+ await expect(migration.up({ rootDir })).resolves.not.toThrow();
+ expect(existsSync(join(stagesDir, FILENAME))).toBe(false);
+ });
+
+ it('matches the live shipped stage-config key + prompt file (drift catch)', () => {
+ const refConfig = JSON.parse(
+ readFileSync(join(repoRoot, 'data.reference', 'prompts', 'stage-config.json'), 'utf8'),
+ );
+ expect(refConfig.stages[STAGE_KEY], `stage-config missing ${STAGE_KEY}`).toBeTruthy();
+ expect(refConfig.stages[STAGE_KEY].returnsJson).toBe(true);
+ expect(existsSync(join(repoRoot, 'data.reference', 'prompts', 'stages', FILENAME))).toBe(true);
+ });
+});
diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.md
index adfbe42b8c..92951f87d4 100644
--- a/server/lib/editorial/README.md
+++ b/server/lib/editorial/README.md
@@ -99,4 +99,5 @@ runner-injected `ctx.callInlineLLM` (an inline-prompt sibling of
| `italicThoughts.js` | Pure, dependency-free italic-thought primitive for `prose.italic-thoughts` (#1300): `findItalicThoughts` (multi-word markdown `*…*` / `_…_` italic runs, dedup + word-count threshold so single-word emphasis, bold, and `snake_case` are skipped). The LLM siblings (`opening.wrong-start`, `prose.mirror-description`, `dialogue.pleasantries`, `prose.kill-your-darlings`) handle the judgment cases in the #1300 anti-pattern bundle. |
| `proseTics.js` | Pure, dependency-free copy-edit prose-tic primitives for the #1306 line-edit group: `tokenizeWords` / `splitSentences` (shared tokenization), `findFilterWords` (`prose.filter-words`), `findCrutchWords` (`prose.crutch-words`), `findAdverbs` (`prose.adverbs` — `-ly` adverbs + dialogue-tag adverbs), `findPassiveVoice` (`prose.passive-voice` — be-verb + past-participle heuristic), `findGestures` (`prose.repeated-gestures` — gesture tally + body-part autonomy), plus the seed `FILTER_WORDS` / `CRUTCH_WORDS` / `GESTURE_WORDS` lists. The LLM sibling `prose.telling-emotion` handles the named-emotion judgment case. |
| `repetition.js` | Pure, dependency-free word-echo & rhythm primitives for #1306: `findWordEchoes` (`prose.word-echoes` — distinctive word repeated within a window), `findRepeatedOpeners` (runs of sentences sharing an opener, "He… He… He…"), and `measureSentenceRhythm` (`prose.sentence-rhythm` — sentence-length variation). Reuses `tokenizeWords` / `splitSentences` from `proseTics.js`. |
+| `dialogue.js` | Pure, dependency-free dialogue-tag primitives for the #1307 dialogue-craft group: `findSaidBookisms` (`dialogue.said-bookisms` — ornate speech tags like *expostulated*/*opined* and non-speech tags like "she smiled", matched only when adjacent to a double-quote span) and `findUnattributedDialogueRuns` (`dialogue.attribution-clarity` — runs of consecutive untagged/unbeated dialogue lines where the speaker can't be tracked), plus the seed `SAID_BOOKISMS` / `NON_SPEECH_TAGS` lists. The LLM siblings `dialogue.on-the-nose` (subtext-free / "as you know, Bob" dialogue) and `dialogue.voice-distinctiveness` (per-character voice against canon `speechPattern`/`speechAccent`) handle the judgment cases. |
| `index.js` | Barrel re-export of the above. |
diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.js
index 66cb4e19ca..eb5dae4ebd 100644
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@ -29,6 +29,7 @@ import { estimateTokens } from '../contextBudget.js';
import { renderCharacterArcsForPrompt } from '../seriesCharacterArc.js';
import { analyzeNamePair, findFirstLetterClusters, normalizeName } from './nameSimilarity.js';
import { findCliches, findModifierStacking } from './cliches.js';
+import { findSaidBookisms, findUnattributedDialogueRuns } from './dialogue.js';
import { findItalicThoughts } from './italicThoughts.js';
import {
findFilterWords,
@@ -217,6 +218,44 @@ export const ARC_TRANSITIONS_STAGE = 'pipeline-editorial-arc-transitions';
// prose.sentence-rhythm) need no stage.
export const TELLING_EMOTION_STAGE = 'pipeline-editorial-telling-emotion';
+// Stage names for the two dialogue-craft LLM checks (#1307): on-the-nose /
+// subtext-free dialogue, and per-character voice distinctiveness. Each prompt
+// ships in data.reference/prompts/stages/ + stage-config.json (fresh installs via
+// setup-data.js) and migrates to existing installs via migrations 111–112 (boot
+// runs migrations but NOT setup-data, so the migration is required). The
+// deterministic siblings (dialogue.said-bookisms, dialogue.attribution-clarity)
+// need no stage.
+export const ON_THE_NOSE_STAGE = 'pipeline-editorial-on-the-nose';
+export const VOICE_DISTINCTIVENESS_STAGE = 'pipeline-editorial-voice-distinctiveness';
+
+// Render each canon character's authored voice fields into a compact text block
+// the voice-distinctiveness LLM check passes alongside the manuscript, so the
+// model can flag lines that contradict a character's recorded speechPattern /
+// speechAccent (closing the "voice fields feed generation only" gap, #1307) and
+// reason about whether characters sound distinct from one another. Pure +
+// deterministic so it's unit-testable and its token cost can be counted into the
+// per-chunk overhead. Returns '' when no character carries a voice field (the
+// prompt's {{#voiceProfiles}} section then renders nothing and the check
+// degrades to a pure interchangeability scan).
+export function characterVoiceProfiles(canon) {
+ const chars = Array.isArray(canon?.characters) ? canon.characters : [];
+ const lines = [];
+ for (const c of chars) {
+ if (!c || typeof c !== 'object') continue;
+ const name = typeof c.name === 'string' ? c.name.trim() : '';
+ if (!name) continue;
+ const pattern = typeof c.speechPattern === 'string' ? c.speechPattern.trim() : '';
+ const accent = typeof c.speechAccent === 'string' ? c.speechAccent.trim() : '';
+ if (!pattern && !accent) continue;
+ const parts = [`- ${name}`];
+ if (pattern) parts.push(`speech pattern: ${pattern}`);
+ if (accent) parts.push(`accent/dialect: ${accent}`);
+ lines.push(parts.join(' — '));
+ }
+ if (!lines.length) return '';
+ return `Authored character voices (canon speechPattern / speechAccent):\n${lines.join('\n')}`;
+}
+
// Render the authored reader-map cliffhangers (#1298) into a compact text block
// the chapter-ending check passes alongside the manuscript so the model
// reconciles its DETECTED endings against the issue-boundary tugs the writer
@@ -2967,6 +3006,191 @@ export const EDITORIAL_CHECKS = [
buildVars: (manuscript) => ({ manuscript }),
}),
},
+ {
+ id: 'dialogue.said-bookisms',
+ sources: ['manuscript'],
+ label: 'Said-bookisms & non-speech dialogue tags',
+ description:
+ 'Flags ornate speech tags ("expostulated", "opined", "interjected") and non-speech actions misused as tags ("\'Yes,\' she smiled" — you cannot smile a line). Deterministic scan that only fires on verbs adjacent to a quoted line, so narrated uses of the same verb ("the engine growled") are left alone. Prefer "said"/"asked" plus an action beat.',
+ scope: 'issue',
+ kind: 'deterministic',
+ category: 'dialogue',
+ severityDefault: 'low',
+ defaultEnabled: true,
+ // Reads the stitched manuscript (per-issue sections) to anchor each tag.
+ needsManuscript: true,
+ configSchema: z.object({
+ // Cap findings per run so a tag-heavy draft can't flood the review.
+ maxFindings: z.number().int().min(1).max(50).default(20),
+ // House-style allowlist / extra bookism verbs (comma- or newline-separated).
+ allowWords: z.string().default(''),
+ extraWords: z.string().default(''),
+ }),
+ configFields: [
+ { key: 'maxFindings', label: 'Max findings per run', type: 'number', min: 1, max: 50, step: 1, help: 'Cap findings so a tag-heavy draft can not flood the review.' },
+ { key: 'allowWords', label: 'House-style allowlist', type: 'text', help: 'Speech-tag verbs to leave alone (comma-separated or one per line) — a genre voice may keep some.' },
+ { key: 'extraWords', label: 'Extra bookisms to flag', type: 'text', help: 'Series-specific ornate tags to add (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 sections = Array.isArray(ctx.sections) ? ctx.sections : [];
+ const findings = [];
+ for (const s of sections) {
+ if (findings.length >= max) break;
+ const hits = findSaidBookisms(s?.content || '', { allowWords, extraWords });
+ 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 problem = hit.kind === 'non-speech'
+ ? `"${hit.anchor}" uses a non-speech action ("${hit.verb}") as a dialogue tag — you cannot ${hit.verb} a line of dialogue.`
+ : `"${hit.anchor}" uses the said-bookism "${hit.verb}" as a dialogue tag — ornate tags pull readers out and call attention to the prose.`;
+ findings.push({
+ severity: ctx.severityDefault,
+ category: 'dialogue',
+ location,
+ problem,
+ suggestion: hit.kind === 'non-speech'
+ ? `Split it into a tag and a beat: "Of course." She smiled. — let the action stand on its own sentence.`
+ : `Use "said" or "asked" and let an action beat or the line itself carry the tone.`,
+ anchorQuote: hit.anchor,
+ issueNumber,
+ });
+ }
+ }
+ return findings;
+ },
+ },
+ {
+ id: 'dialogue.attribution-clarity',
+ sources: ['manuscript'],
+ label: 'Dialogue attribution clarity (untrackable speakers)',
+ description:
+ 'Flags long runs of consecutive dialogue lines with no speech tag or action beat to re-anchor who is speaking — past a few exchanges the reader loses track of which character has the line. Deterministic scan over the stitched manuscript; an attributed line (a tag or a grounding beat) resets the run.',
+ scope: 'issue',
+ kind: 'deterministic',
+ category: 'dialogue',
+ severityDefault: 'low',
+ defaultEnabled: true,
+ // Reads the stitched manuscript (per-issue sections) to anchor each run.
+ needsManuscript: true,
+ configSchema: z.object({
+ // Consecutive untagged/unbeated dialogue lines before a run is flagged.
+ minRun: z.number().int().min(2).max(20).default(6),
+ // Non-quoted chars in a dialogue paragraph that count as a grounding beat.
+ beatChars: z.number().int().min(0).max(80).default(16),
+ // Cap findings per run so a dialogue-heavy draft can't flood the review.
+ maxFindings: z.number().int().min(1).max(50).default(20),
+ }),
+ configFields: [
+ { key: 'minRun', label: 'Untagged lines in a row to flag', type: 'number', min: 2, max: 20, step: 1, help: 'How many consecutive dialogue lines with no tag or action beat before the speaker becomes hard to track. Two speakers alternating stay trackable for a few exchanges; a longer run is where it fails.' },
+ { key: 'beatChars', label: 'Action-beat threshold (characters)', type: 'number', min: 0, max: 80, step: 1, help: 'How many non-quoted characters a dialogue paragraph needs to count as carrying a grounding action beat (which re-anchors the speaker).' },
+ { 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.' },
+ ],
+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,
+ run: (ctx) => {
+ const cfg = ctx.config || {};
+ const max = cfg.maxFindings ?? 20;
+ const minRun = cfg.minRun ?? 6;
+ const beatChars = cfg.beatChars ?? 16;
+ const sections = Array.isArray(ctx.sections) ? ctx.sections : [];
+ const findings = [];
+ for (const s of sections) {
+ if (findings.length >= max) break;
+ const runs = findUnattributedDialogueRuns(s?.content || '', { minRun, beatChars });
+ for (const run of runs) {
+ if (findings.length >= max) break;
+ const issueNumber = Number.isInteger(s?.number) ? s.number : null;
+ findings.push({
+ severity: ctx.severityDefault,
+ category: 'dialogue',
+ location: issueNumber != null ? `Issue ${issueNumber}` : 'Manuscript',
+ problem: `${run.count} dialogue lines in a row with no speech tag or action beat (starting "${run.anchor}") — past a few exchanges the reader can't track who is speaking.`,
+ suggestion: 'Drop in an occasional "said"/"asked" or a short action beat to re-anchor the speaker — every few lines is enough to keep a long exchange clear.',
+ anchorQuote: run.anchor,
+ issueNumber,
+ });
+ }
+ }
+ return findings;
+ },
+ },
+ {
+ id: 'dialogue.on-the-nose',
+ sources: ['manuscript'],
+ label: 'On-the-nose / subtext-free dialogue (LLM)',
+ description:
+ 'LLM scan for dialogue that states exactly what a character feels or means with no subtext, and "maid-and-butler" exchanges where characters tell each other what they both already know. Complements the info-dumping check (#1297) — that targets backstory exposition, this targets emotionally flat, subtext-free lines.',
+ scope: 'issue',
+ kind: 'llm',
+ category: 'dialogue',
+ severityDefault: 'low',
+ defaultEnabled: true,
+ needsManuscript: true,
+ configSchema: z.object({
+ // Cap findings per run so a long manuscript can't flood the review.
+ maxFindings: z.number().int().min(1).max(50).default(12),
+ }),
+ configFields: [
+ { key: 'maxFindings', label: 'Max findings per run', type: 'number', min: 1, max: 50, step: 1, help: 'Cap findings so a long manuscript can not flood the review.' },
+ ],
+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,
+ // Localized prose-level findings (one on-the-nose line = one spot), so this
+ // stays a plain per-chunk run with no cross-chunk digest — mirrors prose.info-dumping.
+ run: (ctx) => runManuscriptLlmCheck(ctx, {
+ stage: ON_THE_NOSE_STAGE,
+ category: 'dialogue',
+ overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS,
+ buildVars: (manuscript) => ({ manuscript }),
+ }),
+ },
+ {
+ id: 'dialogue.voice-distinctiveness',
+ sources: ['manuscript', 'canon'],
+ label: 'Character voice distinctiveness (LLM)',
+ description:
+ "LLM scan that samples each character's dialogue and flags (a) characters whose lines are interchangeable — everyone sounds like one narrator — and (b) lines that contradict the character's canon speechPattern / speechAccent. Produces a per-character voice fingerprint and names concrete differentiating tics. Closes the gap where voice fields fed generation only and nothing validated the drafted dialogue against them.",
+ scope: 'series',
+ kind: 'llm',
+ category: 'dialogue',
+ severityDefault: 'medium',
+ defaultEnabled: true,
+ // Reads the stitched manuscript corpus AND the canon voice fields.
+ needsManuscript: true,
+ configSchema: z.object({
+ // Cap findings per run so a large cast can't flood the review.
+ maxFindings: z.number().int().min(1).max(50).default(12),
+ }),
+ configFields: [
+ { key: 'maxFindings', label: 'Max findings per run', type: 'number', min: 1, max: 50, step: 1, help: 'Cap findings so a large cast can not flood the review.' },
+ ],
+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,
+ run: (ctx) => {
+ // The authored voice profiles are fixed per-call overhead (re-sent on each
+ // chunk) and pure context: they let the model reconcile a character's drafted
+ // lines against their canon speechPattern/speechAccent. The check degrades
+ // gracefully — no voice fields ⇒ {{#voiceProfiles}} renders nothing and the
+ // check still scans for interchangeable voices across the cast.
+ const voiceProfiles = characterVoiceProfiles(ctx.canon);
+ return runManuscriptLlmCheck(ctx, {
+ stage: VOICE_DISTINCTIVENESS_STAGE,
+ category: 'dialogue',
+ overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS + estimateTokens(voiceProfiles),
+ buildVars: (manuscript) => ({ manuscript, voiceProfiles }),
+ // Voice distinctiveness is a whole-cast judgment: a character's lines are
+ // spread across chapters, so a per-chunk view can't tell "interchangeable"
+ // from "we only saw one speaker this chunk". Roll a per-character voice-
+ // sample digest forward so a later chunk judges against the full sample.
+ crossChunkSetup: true,
+ setupFocus:
+ 'For each named character, capture a few representative dialogue lines and a one-phrase sketch of their voice (diction, rhythm, verbal tics, accent markers). Carry these samples forward so a later chunk can judge whether characters sound distinct from one another and consistent with their established voice.',
+ });
+ },
+ },
{
id: 'prose.kill-your-darlings',
sources: ['manuscript'],
diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.js
index 2255945eb5..64292ccd76 100644
--- a/server/lib/editorial/checkRegistry.test.js
+++ b/server/lib/editorial/checkRegistry.test.js
@@ -30,6 +30,7 @@ import {
authoredSetupPayoffSummary,
authoredCliffhangerSummary,
sceneGroundingSummary,
+ characterVoiceProfiles,
} from './checkRegistry.js';
const NAMING = 'naming.dissimilar-names';
@@ -2541,3 +2542,188 @@ describe('prose anti-pattern bundle (#1300)', () => {
});
});
});
+
+describe('dialogue-craft bundle (#1307)', () => {
+ const SAID_BOOKISMS = 'dialogue.said-bookisms';
+ const ATTRIBUTION = 'dialogue.attribution-clarity';
+ const ON_THE_NOSE = 'dialogue.on-the-nose';
+ const VOICE = 'dialogue.voice-distinctiveness';
+
+ describe('dialogue.said-bookisms — deterministic check', () => {
+ const run = (sections, config = {}) =>
+ getCheck(SAID_BOOKISMS).run({ sections, config, severityDefault: 'low' });
+
+ it('declares the expected scope / kind / sources', () => {
+ const c = getCheck(SAID_BOOKISMS);
+ expect(c.kind).toBe('deterministic');
+ expect(c.scope).toBe('issue');
+ expect(c.category).toBe('dialogue');
+ expect(c.sources).toEqual(['manuscript']);
+ expect(c.needsManuscript).toBe(true);
+ });
+
+ it('flags an ornate tag and anchors it to its issue', () => {
+ const findings = run([{ number: 2, content: '"I object," expostulated the duke.' }]);
+ expect(findings).toHaveLength(1);
+ expect(findings[0].issueNumber).toBe(2);
+ expect(findings[0].category).toBe('dialogue');
+ expect(findings[0].problem).toMatch(/said-bookism/);
+ expect(findings[0].anchorQuote).toContain('expostulated');
+ });
+
+ it('flags a non-speech action used as a tag with distinct wording', () => {
+ const findings = run([{ number: 1, content: '"Of course," she smiled.' }]);
+ expect(findings).toHaveLength(1);
+ expect(findings[0].problem).toMatch(/non-speech action/);
+ expect(findings[0].suggestion).toMatch(/action/);
+ });
+
+ it('does not flag plain tags or narrated verbs', () => {
+ expect(run([{ number: 1, content: '"Hello," she said. The engine growled outside.' }])).toEqual([]);
+ });
+
+ it('honors allowWords and maxFindings', () => {
+ const sections = [{ number: 1, content: '"A," he opined. "B," she retorted. "C," they interjected.' }];
+ expect(run(sections, { allowWords: 'opine, retort, interject' })).toEqual([]);
+ expect(run(sections, { maxFindings: 1 })).toHaveLength(1);
+ });
+ });
+
+ describe('dialogue.attribution-clarity — deterministic check', () => {
+ const run = (sections, config = {}) =>
+ getCheck(ATTRIBUTION).run({ sections, config, severityDefault: 'low' });
+ const bareRun = [
+ '"You came back."',
+ '"I had to."',
+ '"After everything?"',
+ '"Especially after everything."',
+ '"And now?"',
+ '"Now we finish it."',
+ ].join('\n');
+
+ it('declares the expected scope / kind / sources', () => {
+ const c = getCheck(ATTRIBUTION);
+ expect(c.kind).toBe('deterministic');
+ expect(c.scope).toBe('issue');
+ expect(c.category).toBe('dialogue');
+ expect(c.sources).toEqual(['manuscript']);
+ expect(c.needsManuscript).toBe(true);
+ });
+
+ it('flags a long untagged run and anchors it to the run start', () => {
+ const findings = run([{ number: 4, content: bareRun }]);
+ expect(findings).toHaveLength(1);
+ expect(findings[0].issueNumber).toBe(4);
+ expect(findings[0].category).toBe('dialogue');
+ expect(findings[0].problem).toMatch(/no speech tag or action beat/);
+ expect(findings[0].anchorQuote).toBe('"You came back."');
+ });
+
+ it('does not flag a short exchange below the default threshold', () => {
+ expect(run([{ number: 1, content: '"Hi."\n"Hello."\n"Bye."' }])).toEqual([]);
+ });
+
+ it('honors a custom minRun', () => {
+ const findings = run([{ number: 1, content: '"A."\n"B."\n"C."' }], { minRun: 3 });
+ expect(findings).toHaveLength(1);
+ });
+ });
+
+ describe('dialogue.on-the-nose — LLM check', () => {
+ const wholeCtx = (overrides = {}) => ({
+ manuscript: '# Issue 1\n\n"I am angry at you for leaving me," she said.',
+ config: { maxFindings: 12 },
+ severityDefault: 'low',
+ planManuscriptChunks: async () => ['# Issue 1\n\n"I am angry at you for leaving me," she said.'],
+ callStagedLLM: async () => ({ content: { findings: [] } }),
+ ...overrides,
+ });
+
+ it('is registered as a manuscript LLM check with category dialogue', () => {
+ const c = getCheck(ON_THE_NOSE);
+ expect(c.kind).toBe('llm');
+ expect(c.scope).toBe('issue');
+ expect(c.category).toBe('dialogue');
+ expect(c.needsManuscript).toBe(true);
+ expect(c.sources).toEqual(['manuscript']);
+ });
+
+ it('passes the corpus to the model and normalizes findings to the dialogue category', async () => {
+ const ctx = wholeCtx({
+ callStagedLLM: async (_stage, vars) => {
+ expect(vars.manuscript).toContain('angry');
+ return { content: { findings: [{ severity: 'medium', issueNumber: 1, problem: 'on the nose', anchorQuote: 'I am angry' }] } };
+ },
+ });
+ const findings = await getCheck(ON_THE_NOSE).run(ctx);
+ expect(findings).toHaveLength(1);
+ expect(findings[0].category).toBe('dialogue');
+ expect(findings[0].issueNumber).toBe(1);
+ });
+ });
+
+ describe('dialogue.voice-distinctiveness — LLM check', () => {
+ const canon = { characters: [{ name: 'Mara', speechPattern: 'clipped, profane' }, { name: 'Joss', speechAccent: 'formal Edwardian' }] };
+ const wholeCtx = (overrides = {}) => ({
+ manuscript: '# Issue 1\n\n"We go now," said Mara. "Indeed we shall," said Joss.',
+ canon,
+ config: { maxFindings: 12 },
+ severityDefault: 'medium',
+ planManuscriptChunks: async () => ['# Issue 1\n\nlines'],
+ callStagedLLM: async () => ({ content: { findings: [] } }),
+ ...overrides,
+ });
+
+ it('is registered as a manuscript+canon LLM check with category dialogue', () => {
+ const c = getCheck(VOICE);
+ expect(c.kind).toBe('llm');
+ expect(c.scope).toBe('series');
+ expect(c.category).toBe('dialogue');
+ expect(c.needsManuscript).toBe(true);
+ expect(c.sources).toEqual(expect.arrayContaining(['manuscript', 'canon']));
+ expect(c.severityDefault).toBe('medium');
+ });
+
+ it('feeds the authored voice profiles alongside the manuscript', async () => {
+ let seenVars = null;
+ const ctx = wholeCtx({
+ callStagedLLM: async (_stage, vars) => {
+ seenVars = vars;
+ return { content: { findings: [{ severity: 'high', issueNumber: 1, problem: 'interchangeable', anchorQuote: 'We go now' }] } };
+ },
+ });
+ const findings = await getCheck(VOICE).run(ctx);
+ expect(seenVars.voiceProfiles).toContain('Mara');
+ expect(seenVars.voiceProfiles).toContain('clipped, profane');
+ expect(findings).toHaveLength(1);
+ expect(findings[0].category).toBe('dialogue');
+ });
+ });
+
+ describe('characterVoiceProfiles helper', () => {
+ it('renders only characters carrying a voice field', () => {
+ const out = characterVoiceProfiles({
+ characters: [
+ { name: 'Mara', speechPattern: 'clipped, profane' },
+ { name: 'Joss', speechAccent: 'formal Edwardian' },
+ { name: 'Extra' }, // no voice fields → omitted
+ ],
+ });
+ expect(out).toContain('Authored character voices');
+ expect(out).toContain('Mara — speech pattern: clipped, profane');
+ expect(out).toContain('Joss — accent/dialect: formal Edwardian');
+ expect(out).not.toContain('Extra');
+ });
+
+ it('returns "" when no character carries a voice field', () => {
+ expect(characterVoiceProfiles({ characters: [{ name: 'A' }, { name: 'B' }] })).toBe('');
+ expect(characterVoiceProfiles({})).toBe('');
+ expect(characterVoiceProfiles(null)).toBe('');
+ });
+
+ it('tolerates malformed characters without throwing', () => {
+ expect(() => characterVoiceProfiles({ characters: [null, { speechPattern: 42 }, 'x'] })).not.toThrow();
+ expect(characterVoiceProfiles({ characters: [null, { speechPattern: 42 }] })).toBe('');
+ });
+ });
+});
diff --git a/server/lib/editorial/dialogue.js b/server/lib/editorial/dialogue.js
new file mode 100644
index 0000000000..f0cdd6874b
--- /dev/null
+++ b/server/lib/editorial/dialogue.js
@@ -0,0 +1,260 @@
+/**
+ * Dialogue-craft deterministic primitives (#1307) for the editorial check
+ * registry. Pure and dependency-free (no side-effecting imports) so it stays
+ * unit-testable in isolation — mirrors ./proseTics.js and ./cliches.js.
+ *
+ * Two scanners back the two deterministic dialogue checks in checkRegistry.js:
+ * - findSaidBookisms() → `dialogue.said-bookisms` (ornate / non-speech tags)
+ * - findUnattributedDialogueRuns() → `dialogue.attribution-clarity` (untrackable speakers)
+ *
+ * Their LLM siblings (`dialogue.on-the-nose`, `dialogue.voice-distinctiveness`)
+ * handle the judgment cases these pure scanners can't: subtext-free / "as you
+ * know, Bob" dialogue, and per-character voice distinctiveness against canon.
+ *
+ * Quote handling: only DOUBLE quotes (straight " and curly “ ”) are treated as
+ * dialogue delimiters. Single quotes are deliberately excluded — they collide
+ * with apostrophes (it's, don't, ’em) and would wreck precision. Manuscripts in
+ * the pipeline use double-quote dialogue, so this is a safe simplification.
+ */
+
+// Straight + curly double quotes. Used both as a character class body (DQUOTE)
+// and to build "quoted span" / "non-quote run" regexes.
+const DQUOTE = '"“”';
+const DQUOTE_CLASS = `[${DQUOTE}]`;
+const NON_DQUOTE = `[^${DQUOTE}]`;
+
+// A "speaker" token that can sit beside a dialogue tag — a capitalized proper
+// name or a personal pronoun. Used to anchor a tag verb to a real attribution
+// (so "the dog growled" in narration doesn't read as a said-bookism).
+const SPEAKER = "(?:[A-Z][\\w'’\\-]+|he|she|they|him|her|them|I|we|you|it)";
+
+// Said-bookisms — ornate speech-tag verbs that should almost always collapse to
+// "said" / "asked". Curated, lowercase, base form; the matcher inflects each to
+// its -s / past-tense forms. A series can mute entries (allowWords) or extend
+// the list (extraWords) for genre voice.
+export const SAID_BOOKISMS = Object.freeze([
+ 'expostulate', 'ejaculate', 'opine', 'interject', 'enunciate', 'articulate',
+ 'proclaim', 'exclaim', 'vociferate', 'bellow', 'thunder', 'simper', 'chortle',
+ 'guffaw', 'snarl', 'growl', 'hiss', 'purr', 'quip', 'retort', 'riposte',
+ 'interpose', 'remonstrate', 'expound', 'asseverate', 'aver', 'posit',
+ 'postulate', 'elucidate', 'intone', 'drawl', 'bleat', 'splutter', 'sputter',
+ 'wheeze', 'rasp', 'croak', 'trill', 'warble', 'pontificate', 'declaim',
+ 'orate', 'soliloquize',
+]);
+
+// Non-speech actions misused as speech tags — you cannot smile / laugh / nod a
+// line of dialogue. ("'Yes,' she smiled.") Base form; inflected by the matcher.
+export const NON_SPEECH_TAGS = Object.freeze([
+ 'smile', 'grin', 'laugh', 'chuckle', 'nod', 'shrug', 'sigh', 'frown',
+ 'beam', 'wink', 'sob', 'snort', 'gesture', 'scowl', 'smirk', 'pout',
+ 'wince', 'gulp', 'shudder',
+]);
+
+// 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',
+]);
+
+function escapeRegExp(s) {
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function normalizeWord(p) {
+ return typeof p === 'string' ? p.trim().toLowerCase() : '';
+}
+
+// Regular inflections of a base verb for tag matching: base, +s, and the past
+// tense (+ed, drop-e +d, or doubled-final-consonant +ed). Returns lowercased,
+// de-duped surface forms. Mirrors the inflection rules in proseTics.inflect().
+function inflectVerb(base) {
+ const b = base.toLowerCase();
+ const forms = new Set([b, `${b}s`]);
+ if (b.endsWith('e')) {
+ forms.add(`${b}d`);
+ } else {
+ forms.add(`${b}ed`);
+ // Short CVC base doubles its final consonant: nod → nodded.
+ if (/[^aeiou][aeiou][^aeiouwxy]$/.test(b)) {
+ forms.add(`${b}${b.slice(-1)}ed`);
+ }
+ }
+ return [...forms];
+}
+
+// Map every inflected surface form of a verb list back to its base, honoring an
+// allow-list (muted bases) and extra additions. Returns { forms[], formToBase }.
+function buildVerbForms(seed, opts = {}) {
+ const allow = new Set((Array.isArray(opts.allowWords) ? opts.allowWords : []).map(normalizeWord).filter(Boolean));
+ const extra = (Array.isArray(opts.extraWords) ? opts.extraWords : []).map(normalizeWord).filter(Boolean);
+ const formToBase = new Map();
+ const seen = new Set();
+ for (const w of [...seed, ...extra]) {
+ const norm = normalizeWord(w);
+ if (!norm || seen.has(norm) || allow.has(norm)) continue;
+ seen.add(norm);
+ for (const f of inflectVerb(norm)) if (!formToBase.has(f)) formToBase.set(f, norm);
+ }
+ return { forms: [...formToBase.keys()], formToBase };
+}
+
+// Build the two dialogue-tag regexes for a set of inflected verb forms:
+// after-quote: "…" she opined / "…" opined Marlon
+// before-quote: She opined, "…"
+// The verb must sit immediately beside a double-quote span and a speaker, so a
+// bare narrated verb ("the dog growled") never matches. Returns null when the
+// effective form list is empty.
+function buildTagMatchers(forms) {
+ if (!forms.length) return null;
+ // Longest-first so "expostulated" wins over a shorter prefix under alternation.
+ const alt = forms.slice().sort((a, b) => b.length - a.length).map(escapeRegExp).join('|');
+ const VERB = `(${alt})`;
+ // After a closing quote: optional comma/period already lives inside the quote,
+ // so we expect quote → space → (optional speaker) → verb OR verb → speaker.
+ const after = new RegExp(`${DQUOTE_CLASS}[\\s]+(?:${SPEAKER}\\s+)?${VERB}\\b`, 'gi');
+ // Before an opening quote: speaker → verb → optional comma/colon → quote.
+ const before = new RegExp(`\\b${SPEAKER}\\s+${VERB}\\s*[,:]?\\s*${DQUOTE_CLASS}`, 'gi');
+ return { after, before };
+}
+
+/**
+ * Find said-bookism and non-speech dialogue tags in `text`. Only verbs sitting
+ * immediately beside a double-quote span (a real dialogue tag) are returned, so
+ * narrated uses of the same verb ("the engine growled") are not flagged.
+ *
+ * @param {string} text
+ * @param {{ allowWords?: string[], extraWords?: string[] }} [opts]
+ * allowWords — bases to mute (house-style / genre voice).
+ * extraWords — extra bookism bases to flag (treated as 'bookism' kind).
+ * @returns {Array<{ verb: string, kind: 'bookism'|'non-speech', index: number, anchor: string }>}
+ * in position order, deduped by (verb-base @ index) so the two regexes don't
+ * double-report the same tag.
+ */
+export function findSaidBookisms(text, opts = {}) {
+ if (typeof text !== 'string' || !text) return [];
+ const bookisms = buildVerbForms(SAID_BOOKISMS, opts);
+ // Non-speech tags share the allow-list but ignore extraWords (those extend the
+ // bookism list, semantically), so build them with only the allow-list applied.
+ const nonSpeech = buildVerbForms(NON_SPEECH_TAGS, { allowWords: opts.allowWords });
+ const kindByForm = new Map();
+ for (const [form, base] of bookisms.formToBase) kindByForm.set(form, { base, kind: 'bookism' });
+ // Non-speech wins only where a form isn't already a bookism (no overlap today).
+ for (const [form, base] of nonSpeech.formToBase) if (!kindByForm.has(form)) kindByForm.set(form, { base, kind: 'non-speech' });
+
+ const allForms = [...kindByForm.keys()];
+ const matchers = buildTagMatchers(allForms);
+ if (!matchers) return [];
+
+ const out = [];
+ const seen = new Set();
+ for (const re of [matchers.after, matchers.before]) {
+ re.lastIndex = 0;
+ let m;
+ while ((m = re.exec(text)) !== null) {
+ const form = m[1].toLowerCase();
+ const info = kindByForm.get(form);
+ if (!info) continue;
+ const key = `${info.base}@${m.index}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push({ verb: info.base, kind: info.kind, index: m.index, anchor: m[0].trim() });
+ }
+ }
+ return out.sort((a, b) => a.index - b.index);
+}
+
+// A single regex matching any plain-speech-tag word (whole-word, case-insens.),
+// used to decide whether a dialogue paragraph carries attribution.
+const PLAIN_TAG_RE = new RegExp(`\\b(?:${PLAIN_SPEECH_TAGS.join('|')})\\b`, 'i');
+// All bookism + non-speech inflected forms also count as attribution (an ornate
+// tag is still a tag — it's the said-bookism check's job to flag it, not the
+// attribution check's job to call it unattributed). Built once at module load.
+const ORNATE_TAG_RE = (() => {
+ const { forms } = buildVerbForms([...SAID_BOOKISMS, ...NON_SPEECH_TAGS]);
+ return forms.length ? new RegExp(`\\b(?:${forms.map(escapeRegExp).join('|')})\\b`, 'i') : null;
+})();
+const QUOTED_SPAN_RE = new RegExp(`${DQUOTE_CLASS}${NON_DQUOTE}*${DQUOTE_CLASS}`, 'g');
+
+// A paragraph is a "dialogue line" when it contains a complete quoted span.
+const hasQuotedSpan = (para) => {
+ QUOTED_SPAN_RE.lastIndex = 0;
+ return QUOTED_SPAN_RE.test(para);
+};
+
+// A dialogue paragraph is "attributed" when it carries a speech tag (plain or
+// ornate) OR an action beat — substantial non-quoted prose that grounds who is
+// speaking. The beat threshold is on the non-quoted character count.
+function isAttributed(para, beatChars) {
+ if (PLAIN_TAG_RE.test(para) || (ORNATE_TAG_RE && ORNATE_TAG_RE.test(para))) return true;
+ const beat = para.replace(QUOTED_SPAN_RE, ' ').replace(/\s+/g, ' ').trim();
+ return beat.length >= beatChars;
+}
+
+/**
+ * Find runs of consecutive unattributed dialogue paragraphs — a stretch of
+ * back-and-forth where no tag or action beat re-anchors the speaker, so the
+ * reader loses track of who is talking. Paragraphs are split on blank/newline
+ * boundaries; only dialogue paragraphs (those with a quoted span) participate,
+ * and a non-dialogue paragraph (pure narration) breaks a run.
+ *
+ * @param {string} text
+ * @param {{ minRun?: number, beatChars?: number }} [opts]
+ * minRun — consecutive unattributed dialogue lines before a run is flagged
+ * (default 6 — two speakers alternating stay trackable for a few
+ * exchanges; a longer untagged run is where tracking genuinely fails).
+ * beatChars — non-quoted chars that count a paragraph as carrying an action
+ * beat (default 16).
+ * @returns {Array<{ count: number, index: number, anchor: string }>}
+ * one entry per run; `index` is the offset of the run's first line, `anchor`
+ * is that first line (trimmed, capped) so the editor can jump to the run start.
+ */
+export function findUnattributedDialogueRuns(text, opts = {}) {
+ if (typeof text !== 'string' || !text) return [];
+ const minRun = Math.max(2, Number.isInteger(opts.minRun) ? opts.minRun : 6);
+ const beatChars = Number.isInteger(opts.beatChars) ? opts.beatChars : 16;
+
+ // Split into paragraphs, tracking each paragraph's absolute start offset.
+ const paras = [];
+ const re = /[^\n]+/g;
+ let m;
+ while ((m = re.exec(text)) !== null) {
+ if (m[0].trim()) paras.push({ text: m[0], index: m.index });
+ }
+
+ const out = [];
+ let runStart = -1; // offset of the first line in the current unattributed run
+ let runFirst = ''; // that first line's text
+ let runCount = 0;
+ const flush = () => {
+ if (runCount >= minRun && runStart >= 0) {
+ out.push({ count: runCount, index: runStart, anchor: runFirst.trim().slice(0, 200) });
+ }
+ runStart = -1;
+ runFirst = '';
+ runCount = 0;
+ };
+ for (const p of paras) {
+ if (!hasQuotedSpan(p.text)) {
+ // Pure narration breaks any in-progress dialogue run.
+ flush();
+ continue;
+ }
+ if (isAttributed(p.text, beatChars)) {
+ // An attributed dialogue line re-anchors the speaker — the run resets, but
+ // this line itself is fine (not part of an UNattributed run).
+ flush();
+ continue;
+ }
+ // Unattributed dialogue line — extend (or start) the current run.
+ if (runCount === 0) { runStart = p.index; runFirst = p.text; }
+ runCount += 1;
+ }
+ flush();
+ return out;
+}
diff --git a/server/lib/editorial/dialogue.test.js b/server/lib/editorial/dialogue.test.js
new file mode 100644
index 0000000000..d2deb458ac
--- /dev/null
+++ b/server/lib/editorial/dialogue.test.js
@@ -0,0 +1,147 @@
+import { describe, it, expect } from 'vitest';
+import {
+ findSaidBookisms,
+ findUnattributedDialogueRuns,
+ SAID_BOOKISMS,
+ NON_SPEECH_TAGS,
+} from './dialogue.js';
+
+describe('findSaidBookisms', () => {
+ it('flags an ornate speech tag after a quote (verb before speaker)', () => {
+ const hits = findSaidBookisms('"I disagree," expostulated Marlon.');
+ expect(hits).toHaveLength(1);
+ expect(hits[0]).toMatchObject({ verb: 'expostulate', kind: 'bookism' });
+ });
+
+ it('flags an ornate tag after a quote (speaker before verb)', () => {
+ const hits = findSaidBookisms('"Indeed," she opined, leaning back.');
+ expect(hits.map((h) => h.verb)).toContain('opine');
+ expect(hits.find((h) => h.verb === 'opine').kind).toBe('bookism');
+ });
+
+ it('flags an ornate tag before an opening quote', () => {
+ const hits = findSaidBookisms('Marlon interjected, "Wait."');
+ expect(hits.map((h) => h.verb)).toContain('interject');
+ });
+
+ it('flags non-speech actions misused as tags ("she smiled")', () => {
+ const hits = findSaidBookisms('"Of course," she smiled.');
+ expect(hits).toHaveLength(1);
+ expect(hits[0]).toMatchObject({ verb: 'smile', kind: 'non-speech' });
+ });
+
+ it('does NOT flag a narrated verb that is not a dialogue tag', () => {
+ // No quote adjacent — "growled" here is narration about an engine.
+ expect(findSaidBookisms('The engine growled as it turned over.')).toEqual([]);
+ });
+
+ it('does NOT flag plain "said" / "asked" tags', () => {
+ expect(findSaidBookisms('"Hello," she said. "How are you?" he asked.')).toEqual([]);
+ });
+
+ it('matches inflected forms (base, -s, -ed)', () => {
+ expect(findSaidBookisms('"No," he snarls.').map((h) => h.verb)).toContain('snarl');
+ expect(findSaidBookisms('"No," he snarled.').map((h) => h.verb)).toContain('snarl');
+ });
+
+ it('honors allowWords (mutes a base) and extraWords (adds a base)', () => {
+ expect(findSaidBookisms('"Yes," she purred.', { allowWords: ['purr'] })).toEqual([]);
+ const hits = findSaidBookisms('"Yes," she gushed.', { extraWords: ['gush'] });
+ expect(hits.map((h) => h.verb)).toContain('gush');
+ });
+
+ it('dedupes a tag matched by both regexes and returns position order', () => {
+ const hits = findSaidBookisms('"A," he opined. "B," she retorted.');
+ const verbs = hits.map((h) => h.verb);
+ expect(verbs).toEqual(['opine', 'retort']);
+ // Each tag reported once even though two patterns can match it.
+ expect(new Set(hits.map((h) => h.index)).size).toBe(hits.length);
+ });
+
+ it('returns [] for non-strings and empty input', () => {
+ expect(findSaidBookisms('')).toEqual([]);
+ expect(findSaidBookisms(null)).toEqual([]);
+ });
+
+ it('seed lists are non-empty and lowercase base forms', () => {
+ expect(SAID_BOOKISMS.length).toBeGreaterThan(10);
+ expect(NON_SPEECH_TAGS.length).toBeGreaterThan(5);
+ for (const w of [...SAID_BOOKISMS, ...NON_SPEECH_TAGS]) expect(w).toBe(w.toLowerCase());
+ });
+});
+
+describe('findUnattributedDialogueRuns', () => {
+ // Six consecutive bare dialogue lines, no tags or beats → one run.
+ const bareRun = [
+ '"You came back."',
+ '"I had to."',
+ '"After everything?"',
+ '"Especially after everything."',
+ '"And now?"',
+ '"Now we finish it."',
+ ].join('\n');
+
+ it('flags a long run of untagged dialogue', () => {
+ const runs = findUnattributedDialogueRuns(bareRun);
+ expect(runs).toHaveLength(1);
+ expect(runs[0].count).toBe(6);
+ expect(runs[0].anchor).toBe('"You came back."');
+ });
+
+ it('does NOT flag a short exchange below the threshold', () => {
+ const short = '"Hi."\n"Hello."\n"Bye."';
+ expect(findUnattributedDialogueRuns(short)).toEqual([]);
+ });
+
+ it('a speech tag re-anchors and breaks the run', () => {
+ const tagged = [
+ '"You came back."',
+ '"I had to," she said.',
+ '"After everything?"',
+ '"Especially after everything."',
+ '"And now?"',
+ '"Now we finish it."',
+ ].join('\n');
+ // The longest unattributed sub-run is 4 (< default 6) → no finding.
+ expect(findUnattributedDialogueRuns(tagged)).toEqual([]);
+ });
+
+ it('an action beat counts as attribution', () => {
+ const beat = [
+ '"You came back."',
+ 'She set the lantern down on the cold stone floor and waited.',
+ '"After everything?"',
+ '"Especially after everything."',
+ '"And now?"',
+ '"Now we finish it."',
+ ].join('\n');
+ // The narration paragraph breaks the run; neither side reaches 6.
+ expect(findUnattributedDialogueRuns(beat)).toEqual([]);
+ });
+
+ it('respects a custom minRun', () => {
+ const three = '"A."\n"B."\n"C."';
+ expect(findUnattributedDialogueRuns(three, { minRun: 3 })).toHaveLength(1);
+ });
+
+ it('pure narration with no quotes yields no runs', () => {
+ expect(findUnattributedDialogueRuns('He walked. She followed. The road was long.')).toEqual([]);
+ });
+
+ it('returns [] for non-strings and empty input', () => {
+ expect(findUnattributedDialogueRuns('')).toEqual([]);
+ expect(findUnattributedDialogueRuns(null)).toEqual([]);
+ });
+
+ it('handles curly double quotes', () => {
+ const curly = [
+ '“You came back.”',
+ '“I had to.”',
+ '“After everything?”',
+ '“Especially after everything.”',
+ '“And now?”',
+ '“Now we finish it.”',
+ ].join('\n');
+ expect(findUnattributedDialogueRuns(curly)).toHaveLength(1);
+ });
+});
diff --git a/server/lib/editorial/index.js b/server/lib/editorial/index.js
index c252013850..85466f6f37 100644
--- a/server/lib/editorial/index.js
+++ b/server/lib/editorial/index.js
@@ -2,6 +2,7 @@
// (#1284). See README.md for the catalog. Re-export every public module here.
export * from './checkRegistry.js';
export * from './cliches.js';
+export * from './dialogue.js';
export * from './italicThoughts.js';
export * from './nameSimilarity.js';
export * from './proseTics.js';