Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: line-edit/copy-edit editorial checks (filter/crutch/adverb/passive/gesture/echo/rhythm + telling-emotion) (#1306)
Adam Eivy488b8bdbffd6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 413f4c5afb..3fe0fc140a 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **[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-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.jsonindex cf6d82ab2e..97d5dc907b 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -596,6 +596,13 @@"model": "heavy","returnsJson": true,"variables": []+ },+ "pipeline-editorial-telling-emotion": {+ "name": "Pipeline — Editorial Check: Telling-not-showing emotion",+ "description": "Editorial check (#1306): the judgment layer for named-emotion statements (\"she was sad\", \"he felt nervous\") worth dramatizing through action/sensation/subtext. Reads the stitched manuscript; severity is advisory; skips dialogue, deliberate pacing, and already-shown emotion. Returns issue-anchored findings.",+ "model": "default",+ "returnsJson": true,+ "variables": []}}}diff --git a/data.reference/prompts/stages/pipeline-editorial-telling-emotion.md b/data.reference/prompts/stages/pipeline-editorial-telling-emotion.mdnew file mode 100644index 0000000000..71dccaf0af--- /dev/null+++ b/data.reference/prompts/stages/pipeline-editorial-telling-emotion.md@@ -0,0 +1,73 @@+# Pipeline — Editorial Check: Telling-not-showing emotion++You are a line editor doing a single focused pass for ONE problem: **emotion+that is named/told rather than dramatized**. You are the judgment layer that a+keyword scan can't be — flagging only the *strong* candidates worth converting+to showing, and leaving alone the cases where telling is the right, efficient+choice.++Flag a passage when it **states a character's emotion outright** in a way that+would land harder if dramatized through action, sensation, body language, or+subtext:++- Named-emotion statements: "she was sad", "he felt nervous", "they were+ afraid", "anger filled her", "a wave of grief washed over him".+- Emotion explained to the reader instead of shown: "he was so angry he could+ barely speak" (then nothing in the prose shows it).++Do NOT flag:++- Telling used deliberately for **pace or transition** — summarizing a minor+ feeling to get to the scene that matters ("she was annoyed, but she let it+ go"). Showing every emotion would bloat the prose.+- Emotion words inside **dialogue** ("I'm scared") — characters naming feelings+ is natural speech, not narration.+- A named emotion that is **already shown** alongside the telling (the prose+ earns it; redundant naming is a lighter touch, flag at most `low`).+- Strong, deliberate stylistic choices in a consistent narrative voice.++Severity is **advisory**: most findings are `low`; reserve `medium` for a told+emotion at a pivotal beat where showing would clearly raise the stakes, and+`high` only when a key emotional turn is flatly narrated with no dramatization+at all.++## 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 told emotions worth dramatizing. 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 showing would land harder here, and+suggest a concrete way to dramatize it (an action, a physical sensation, a beat+of subtext) — without rewriting the whole passage for the author.++Be specific and cite the text. If the prose already shows its emotions, 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 told emotion appears (e.g. 'Issue 3 — told fear')",+ "problem": "1–3 sentences naming the told emotion and why showing would land harder",+ "suggestion": "1–3 sentences suggesting a concrete way to dramatize it",+ "anchorQuote": "short verbatim quote from the manuscript (≤ 200 chars)"+ }+ ]+}+```diff --git a/scripts/migrations/110-editorial-telling-emotion-stage.js b/scripts/migrations/110-editorial-telling-emotion-stage.jsnew file mode 100644index 0000000000..3d0169f0eb--- /dev/null+++ b/scripts/migrations/110-editorial-telling-emotion-stage.js@@ -0,0 +1,77 @@+/**+ * Seed the `pipeline-editorial-telling-emotion` stage into existing installs (#1306).+ *+ * Mirrors `109-editorial-arc-transitions-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 telling-emotion stage+ * unseeded and the `prose.telling-emotion` editorial check would throw+ * "Stage not found" the first time it runs. The deterministic copy-edit siblings+ * (prose.filter-words, prose.crutch-words, prose.adverbs, prose.passive-voice,+ * prose.repeated-gestures, prose.word-echoes, prose.sentence-rhythm) need no stage.+ */++import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';+import { dirname, join } from 'path';++const FILENAME = 'pipeline-editorial-telling-emotion.md';+const STAGE_KEY = 'pipeline-editorial-telling-emotion';++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-telling-emotion prompt: already present`);+ } else {+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);+ if (!sampleExists) {+ console.warn(`⚠️ pipeline-editorial-telling-emotion: sample missing for ${FILENAME} — skipping copy`);+ } else {+ try {+ await copyFile(samplePath, dataPath);+ console.log(`✅ seeded ${FILENAME}`);+ } catch (err) {+ console.warn(`⚠️ pipeline-editorial-telling-emotion: 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-telling-emotion: 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-telling-emotion stage-config: already present`);+ return;+ }+ if (!sample?.stages?.[STAGE_KEY]) {+ console.warn(`⚠️ pipeline-editorial-telling-emotion: 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-telling-emotion stage-config (${action}): 1 added`);+ } catch (err) {+ console.warn(`⚠️ pipeline-editorial-telling-emotion: stage-config merge failed: ${err.message}`);+ }+ },+};diff --git a/scripts/migrations/110-editorial-telling-emotion-stage.test.js b/scripts/migrations/110-editorial-telling-emotion-stage.test.jsnew file mode 100644index 0000000000..34e653fed4--- /dev/null+++ b/scripts/migrations/110-editorial-telling-emotion-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 './110-editorial-telling-emotion-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 109) — no MD5 bookkeeping, so the+// seed / no-clobber behavior is asserted directly.++const FILENAME = 'pipeline-editorial-telling-emotion.md';+const STAGE_KEY = 'pipeline-editorial-telling-emotion';+const BODY = '# Telling-not-showing emotion\n\nshipped body\n';++describe('migration 110 — seed editorial-telling-emotion 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-110-'));+ 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.mdindex 4398787e0c..adfbe42b8c 100644--- a/server/lib/editorial/README.md+++ b/server/lib/editorial/README.md@@ -97,4 +97,6 @@ runner-injected `ctx.callInlineLLM` (an inline-prompt sibling of| `nameSimilarity.js` | Pure, dependency-free name-confusability primitives for `naming.dissimilar-names` (#1291): `normalizeName`, `vowelSkeleton`, `soundex` (phonetic key), `levenshtein` (edit distance), `nameSimilaritySignals` (the per-pair signal list, with option toggles), and `firstLetterHistogram` / `findFirstLetterClusters` (cast first-letter crowding). || `cliches.js` | Pure, dependency-free cliché + overwriting primitives for `prose.cliches` and `prose.modifier-stacking` (#1308): `CLICHE_PHRASES` (seed stock-simile/idiom list), `findCliches` (whole-word phrase scan with house-style allow/extra lists), and `findModifierStacking` (cumulative no-comma runs of 3+ stacked adjectives/adverbs). The LLM sibling `prose.dead-metaphor` handles the judgment cases (mixed/dead metaphor, novel clichés, purple prose). || `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`. || `index.js` | Barrel re-export of the above. |diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.jsindex fc74eb42ea..66cb4e19ca 100644--- a/server/lib/editorial/checkRegistry.js+++ b/server/lib/editorial/checkRegistry.js@@ -30,6 +30,18 @@ import { renderCharacterArcsForPrompt } from '../seriesCharacterArc.js';import { analyzeNamePair, findFirstLetterClusters, normalizeName } from './nameSimilarity.js';import { findCliches, findModifierStacking } from './cliches.js';import { findItalicThoughts } from './italicThoughts.js';+import {+ findFilterWords,+ findCrutchWords,+ findAdverbs,+ findPassiveVoice,+ findGestures,+} from './proseTics.js';+import {+ findWordEchoes,+ findRepeatedOpeners,+ measureSentenceRhythm,+} from './repetition.js';export const CHECK_SCOPES = Object.freeze(['series', 'issue', 'scene', 'noun']);export const CHECK_KINDS = Object.freeze(['deterministic', 'llm']);@@ -196,6 +208,15 @@ export const WHITE_ROOM_STAGE = 'pipeline-editorial-white-room';// per-character arcs to surface genuine change moments + flat-arc warnings.export const ARC_TRANSITIONS_STAGE = 'pipeline-editorial-arc-transitions';+// Stage name for the telling-not-showing-emotion LLM check (#1306). Ships in+// data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 110 (boot runs+// migrations but NOT setup-data, so the migration is required). The deterministic+// copy-edit siblings (prose.filter-words, prose.crutch-words, prose.adverbs,+// prose.passive-voice, prose.repeated-gestures, prose.word-echoes,+// prose.sentence-rhythm) need no stage.+export const TELLING_EMOTION_STAGE = 'pipeline-editorial-telling-emotion';+// 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@@ -982,6 +1003,62 @@ function splitPhraseList(value) {return value.split(/[,\n]/).map((p) => p.trim()).filter(Boolean);}+// ---------------------------------------------------------------------------+// Copy-edit prose-tic checks (#1306). The deterministic word-level scanners live+// in proseTics.js / repetition.js; these helpers turn raw occurrences into the+// density-scaled findings the registry emits. Density matters: one "just" is+// fine, forty is a tic — so each check measures per-1000-word frequency against+// a configurable threshold and only flags when the rate (not the raw count) is+// high. Findings anchor on the FIRST offending occurrence in each section.+// ---------------------------------------------------------------------------++// Word count of a section's prose (for per-1000-word density). Cheap word+// tokenization — apostrophes kept inside words so contractions count once.+function countWords(text) {+ return (String(text || '').match(/[A-Za-z][A-Za-z']*/g) || []).length;+}++// Map a section to its issue label/number once (used by every prose-tic check).+function sectionIssue(s) {+ const number = Number.isInteger(s?.number) ? s.number : null;+ return { number, location: number != null ? `Issue ${number}` : 'Manuscript' };+}++// Shared driver for the per-1000-word density checks (filter words, crutch+// words, passive voice). For each section it runs the supplied `scan`, computes+// the per-1000-word rate, and emits one finding per section whose rate is at or+// above the configured `densityPer1000` — anchored to the first occurrence.+// `opts` declares the section scan, a noun for messages, and problem/suggestion+// builders. `scan(text, cfg)` returns `[{ index, anchor }, …]` occurrences.+function runDensityCheck(ctx, opts) {+ const cfg = ctx.config || {};+ const max = cfg.maxFindings ?? 20;+ const density = cfg.densityPer1000 ?? 0;+ const sections = Array.isArray(ctx.sections) ? ctx.sections : [];+ const findings = [];+ for (const s of sections) {+ if (findings.length >= max) break;+ const text = s?.content || '';+ const words = countWords(text);+ if (words === 0) continue;+ const hits = opts.scan(text, cfg);+ if (!hits.length) continue;+ const rate = Math.round((hits.length / words) * 1000 * 10) / 10;+ if (rate < density) continue;+ const { number, location } = sectionIssue(s);+ findings.push({+ severity: ctx.severityDefault,+ category: 'style',+ location,+ problem: opts.problem(hits.length, rate, hits[0].anchor),+ suggestion: opts.suggestion,+ anchorQuote: hits[0].anchor,+ issueNumber: number,+ });+ }+ return findings;+}+export const EDITORIAL_CHECKS = [{id: 'naming.dissimilar-names',@@ -2352,6 +2429,398 @@ export const EDITORIAL_CHECKS = [return findings;},},+ {+ id: 'prose.filter-words',+ sources: ['manuscript'],+ label: 'Filter words (distancing verbs)',+ description:+ 'Flags distancing verbs that narrate experience instead of dramatizing it — "she saw the door open", "he felt the cold", "they noticed a shadow". Density-scaled: a high per-1000-word rate of saw/watched/noticed/realized/felt/heard/seemed/wondered/began-to is the tic. Collapse to direct experience ("the door opened").',+ scope: 'issue',+ kind: 'deterministic',+ category: 'style',+ severityDefault: 'low',+ defaultEnabled: true,+ needsManuscript: true,+ configSchema: z.object({+ // Per-1000-word rate at/above which a section is flagged.+ densityPer1000: z.number().min(0).max(50).default(6),+ // Cap findings per run so a heavy draft can't flood the review.+ maxFindings: z.number().int().min(1).max(50).default(20),+ // House-style allowlist / extra filter words (comma- or newline-separated).+ allowWords: z.string().default(''),+ extraWords: z.string().default(''),+ }),+ configFields: [+ { key: 'densityPer1000', label: 'Filter-word rate to flag (per 1000 words)', type: 'number', min: 0, max: 50, step: 1, help: 'Flag a section whose filter-word frequency per 1000 words is at or above this. One "saw" is fine; a steady drumbeat is the tic.' },+ { key: 'maxFindings', label: 'Max findings per run', type: 'number', min: 1, max: 50, step: 1, help: 'Cap findings so a heavy draft can not flood the review.' },+ { key: 'allowWords', label: 'House-style allowlist', type: 'text', help: 'Filter words to leave alone (comma-separated or one per line).' },+ { key: 'extraWords', label: 'Extra filter words to flag', type: 'text', help: 'Series-specific distancing verbs to add (comma-separated or one per line).' },+ ],+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,+ run: (ctx) => runDensityCheck(ctx, {+ scan: (text, cfg) => findFilterWords(text, { allowWords: splitPhraseList(cfg.allowWords), extraWords: splitPhraseList(cfg.extraWords) }),+ noun: 'filter words',+ problem: (count, rate, anchor) => `${count} filter word${count === 1 ? '' : 's'} (e.g. "${anchor}") — about ${rate}/1000 words. Distancing verbs put a layer of narration between the reader and the experience.`,+ suggestion: 'Collapse to direct experience — "she saw the door open" → "the door opened" — or add intentional uses to the allowlist.',+ }),+ },+ {+ id: 'prose.crutch-words',+ sources: ['manuscript'],+ label: 'Crutch / filler words',+ description:+ 'Flags intensifier/hedge crutch words that almost always delete cleanly — just, really, very, quite, somewhat, suddenly, actually, basically, "in order to". Density-scaled per-1000-word frequency. Bare "that" (usually deletable) is included only when the toggle is on, since grammatical "that" would swamp the count.',+ scope: 'issue',+ kind: 'deterministic',+ category: 'style',+ severityDefault: 'low',+ defaultEnabled: true,+ needsManuscript: true,+ configSchema: z.object({+ densityPer1000: z.number().min(0).max(50).default(8),+ maxFindings: z.number().int().min(1).max(50).default(20),+ // Include bare "that" (the deletable relative-clause "that"). Off by default+ // — grammatical "that" is common enough to swamp the density signal.+ includeThat: z.boolean().default(false),+ allowWords: z.string().default(''),+ extraWords: z.string().default(''),+ }),+ configFields: [+ { key: 'densityPer1000', label: 'Crutch-word rate to flag (per 1000 words)', type: 'number', min: 0, max: 50, step: 1, help: 'Flag a section whose crutch-word frequency per 1000 words is at or above this.' },+ { key: 'maxFindings', label: 'Max findings per run', type: 'number', min: 1, max: 50, step: 1, help: 'Cap findings so a heavy draft can not flood the review.' },+ { key: 'includeThat', label: 'Include deletable "that"', type: 'boolean', help: 'Count bare "that" as a crutch word. Off by default — grammatical "that" is common and would swamp the signal.' },+ { key: 'allowWords', label: 'House-style allowlist', type: 'text', help: 'Crutch words to leave alone (comma-separated or one per line).' },+ { key: 'extraWords', label: 'Extra crutch words to flag', type: 'text', help: 'Series-specific fillers to add (comma-separated or one per line).' },+ ],+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,+ run: (ctx) => runDensityCheck(ctx, {+ scan: (text, cfg) => findCrutchWords(text, { includeThat: cfg.includeThat === true, allowWords: splitPhraseList(cfg.allowWords), extraWords: splitPhraseList(cfg.extraWords) }),+ noun: 'crutch words',+ problem: (count, rate, anchor) => `${count} crutch/filler word${count === 1 ? '' : 's'} (e.g. "${anchor}") — about ${rate}/1000 words. Intensifiers and hedges like these usually delete cleanly and tighten the prose.`,+ suggestion: 'Delete the filler or replace the propped-up word with a stronger one ("really big" → "enormous").',+ }),+ },+ {+ id: 'prose.adverbs',+ sources: ['manuscript'],+ label: 'Adverb overuse (-ly + dialogue tags)',+ description:+ 'Flags overuse of -ly adverbs, especially those propping up weak verbs ("ran quickly" → "sprinted") and adverb-laden dialogue tags ("she said angrily"). Density-scaled; dialogue-tag adverbs ("said X-ly") are reported as the higher-severity sub-signal because the tag should carry its weight through the dialogue itself.',+ scope: 'issue',+ kind: 'deterministic',+ category: 'style',+ severityDefault: 'low',+ defaultEnabled: true,+ needsManuscript: true,+ configSchema: z.object({+ densityPer1000: z.number().min(0).max(80).default(15),+ maxFindings: z.number().int().min(1).max(50).default(20),+ allowWords: z.string().default(''),+ }),+ configFields: [+ { key: 'densityPer1000', label: 'Adverb rate to flag (per 1000 words)', type: 'number', min: 0, max: 80, step: 1, help: 'Flag a section whose -ly adverb frequency per 1000 words is at or above this.' },+ { key: 'maxFindings', label: 'Max findings per run', type: 'number', min: 1, max: 50, step: 1, help: 'Cap findings so a heavy draft can not flood the review.' },+ { key: 'allowWords', label: 'House-style allowlist', type: 'text', help: 'Adverbs to leave alone (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 density = cfg.densityPer1000 ?? 15;+ const allowWords = splitPhraseList(cfg.allowWords);+ const sections = Array.isArray(ctx.sections) ? ctx.sections : [];+ const findings = [];+ for (const s of sections) {+ if (findings.length >= max) break;+ const text = s?.content || '';+ const words = countWords(text);+ if (words === 0) continue;+ const hits = findAdverbs(text, { allowWords });+ if (!hits.length) continue;+ const rate = Math.round((hits.length / words) * 1000 * 10) / 10;+ const tagHits = hits.filter((h) => h.dialogueTag);+ const { number, location } = sectionIssue(s);+ // Dialogue-tag adverbs are flagged regardless of overall density (one+ // "said angrily" is already a tell); the bulk -ly density is gated on rate.+ if (tagHits.length) {+ findings.push({+ severity: escalateSeverity(ctx.severityDefault, 1),+ category: 'style',+ location,+ problem: `${tagHits.length} adverb-laden dialogue tag${tagHits.length === 1 ? '' : 's'} (e.g. "${tagHits[0].anchor}") — a dialogue tag propped up by an adverb usually means the line itself should carry the tone.`,+ suggestion: 'Cut the adverb and let the dialogue + action beat convey the tone ("she said angrily" → "she slammed the cup down. “Fine.”").',+ anchorQuote: tagHits[0].anchor,+ issueNumber: number,+ });+ if (findings.length >= max) break;+ }+ if (rate >= density) {+ findings.push({+ severity: ctx.severityDefault,+ category: 'style',+ location,+ problem: `${hits.length} -ly adverbs (about ${rate}/1000 words) — adverb overuse, especially propping up weak verbs ("ran quickly").`,+ suggestion: 'Replace verb+adverb pairs with one strong verb ("ran quickly" → "sprinted"); keep only the adverbs that change the meaning.',+ anchorQuote: hits[0].anchor,+ issueNumber: number,+ });+ }+ }+ return findings;+ },+ },+ {+ id: 'prose.passive-voice',+ sources: ['manuscript'],+ label: 'Passive voice (overuse)',+ description:+ 'Advisory flag for passive-voice overuse — a be-verb + past participle heuristic ("the door was opened", "mistakes were made"). Density-scaled per-1000-word frequency; passive voice is a legitimate choice, so this only flags when the rate is high.',+ scope: 'issue',+ kind: 'deterministic',+ category: 'style',+ severityDefault: 'low',+ defaultEnabled: true,+ needsManuscript: true,+ configSchema: z.object({+ densityPer1000: z.number().min(0).max(50).default(10),+ maxFindings: z.number().int().min(1).max(50).default(20),+ }),+ configFields: [+ { key: 'densityPer1000', label: 'Passive-voice rate to flag (per 1000 words)', type: 'number', min: 0, max: 50, step: 1, help: 'Flag a section whose passive-construction frequency per 1000 words is at or above this. Advisory — passive voice is sometimes the right choice.' },+ { key: 'maxFindings', label: 'Max findings per run', type: 'number', min: 1, max: 50, step: 1, help: 'Cap findings so a heavy draft can not flood the review.' },+ ],+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,+ run: (ctx) => runDensityCheck(ctx, {+ scan: (text) => findPassiveVoice(text),+ noun: 'passive constructions',+ problem: (count, rate, anchor) => `${count} passive construction${count === 1 ? '' : 's'} (e.g. "${anchor}") — about ${rate}/1000 words. Heavy passive voice distances the reader from who is acting.`,+ suggestion: 'Rephrase to active voice where it sharpens the prose ("the door was opened by Sam" → "Sam opened the door"). Keep passive where the actor is unknown or beside the point.',+ }),+ },+ {+ id: 'prose.repeated-gestures',+ sources: ['manuscript'],+ label: 'Repeated gestures / body-part autonomy',+ description:+ 'Flags overused body-language gestures (nodded, smiled, shrugged, sighed, frowned) tallied across the manuscript, plus "body-part autonomy" — detached body parts that act on their own ("her eyes followed him across the room", "his hand shot out"). A reader-pet-peeve goldmine.',+ scope: 'series',+ kind: 'deterministic',+ category: 'style',+ severityDefault: 'low',+ defaultEnabled: true,+ needsManuscript: true,+ configSchema: z.object({+ // A gesture tallied this many times across the manuscript is flagged.+ maxPerGesture: z.number().int().min(2).max(50).default(8),+ maxFindings: z.number().int().min(1).max(50).default(20),+ allowWords: z.string().default(''),+ extraWords: z.string().default(''),+ }),+ configFields: [+ { key: 'maxPerGesture', label: 'Gesture count to flag', type: 'number', min: 2, max: 50, step: 1, help: 'Flag a gesture verb (nodded, smiled, shrugged…) once its total count across the manuscript reaches this.' },+ { key: 'maxFindings', label: 'Max findings per run', type: 'number', min: 1, max: 50, step: 1, help: 'Cap findings so a heavy draft can not flood the review.' },+ { key: 'allowWords', label: 'House-style allowlist', type: 'text', help: 'Gesture verbs to leave alone (comma-separated or one per line).' },+ { key: 'extraWords', label: 'Extra gestures to track', type: 'text', help: 'Series-specific gestures 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 maxPerGesture = cfg.maxPerGesture ?? 8;+ const allowWords = splitPhraseList(cfg.allowWords);+ const extraWords = splitPhraseList(cfg.extraWords);+ const sections = Array.isArray(ctx.sections) ? ctx.sections : [];+ const findings = [];+ // Manuscript-wide gesture tally (an overused gesture is a whole-corpus tic,+ // not a per-issue one); track the first anchor + issue for each gesture.+ const tally = new Map(); // base → { count, anchor, issueNumber }+ const bodyParts = [];+ for (const s of sections) {+ const { gestures, bodyParts: bp } = findGestures(s?.content || '', { allowWords, extraWords });+ const { number } = sectionIssue(s);+ for (const g of gestures) {+ const cur = tally.get(g.base) || { count: 0, anchor: g.anchor, issueNumber: number };+ cur.count += 1;+ tally.set(g.base, cur);+ }+ for (const b of bp) bodyParts.push({ ...b, issueNumber: number });+ }+ // Overused-gesture findings (sorted by count, worst first).+ const overused = [...tally.entries()]+ .filter(([, v]) => v.count >= maxPerGesture)+ .sort((a, b) => b[1].count - a[1].count);+ for (const [base, info] of overused) {+ if (findings.length >= max) break;+ findings.push({+ severity: escalateSeverity(ctx.severityDefault, info.count >= maxPerGesture * 2 ? 1 : 0),+ category: 'style',+ location: info.issueNumber != null ? `Issue ${info.issueNumber}` : 'Manuscript',+ problem: `The gesture "${base}" appears about ${info.count} times across the manuscript — a repeated body-language tic readers notice.`,+ suggestion: 'Vary the beat or cut some entirely — let dialogue and context carry the emotion instead of a recurring nod/smile/shrug.',+ anchorQuote: info.anchor,+ issueNumber: info.issueNumber,+ });+ }+ // Body-part-autonomy findings (one per occurrence, capped).+ for (const b of bodyParts) {+ if (findings.length >= max) break;+ findings.push({+ severity: ctx.severityDefault,+ category: 'style',+ location: b.issueNumber != null ? `Issue ${b.issueNumber}` : 'Manuscript',+ problem: `Detached body part acting on its own ("${b.anchor}") — "body-part autonomy" reads oddly literal and is a common reader pet peeve.`,+ suggestion: 'Re-anchor the action to the character ("her eyes followed him" → "she watched him cross the room").',+ anchorQuote: b.anchor,+ issueNumber: b.issueNumber,+ });+ }+ return findings;+ },+ },+ {+ id: 'prose.word-echoes',+ sources: ['manuscript'],+ label: 'Word repetition / echoes',+ description:+ 'Flags a distinctive word repeated within a short window ("obsidian… obsidian" three sentences apart) and runs of sentences that open with the same word ("He… He… He…"). Common words are ignored; only conspicuous echoes are flagged.',+ scope: 'issue',+ kind: 'deterministic',+ category: 'style',+ severityDefault: 'low',+ defaultEnabled: true,+ needsManuscript: true,+ configSchema: z.object({+ // How close (in words) two occurrences must be to count as an echo.+ windowWords: z.number().int().min(5).max(200).default(50),+ // Sentences in a row sharing an opener before it's flagged.+ minOpenerRun: z.number().int().min(2).max(8).default(3),+ maxFindings: z.number().int().min(1).max(50).default(20),+ }),+ configFields: [+ { key: 'windowWords', label: 'Echo window (words)', type: 'number', min: 5, max: 200, step: 5, help: 'A distinctive word repeated within this many words counts as an echo.' },+ { key: 'minOpenerRun', label: 'Repeated-opener run to flag', type: 'number', min: 2, max: 8, step: 1, help: 'How many sentences in a row starting with the same word trips the repeated-opener flag.' },+ { key: 'maxFindings', label: 'Max findings per run', type: 'number', min: 1, max: 50, step: 1, help: 'Cap findings so a 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 windowWords = cfg.windowWords ?? 50;+ const minRun = cfg.minOpenerRun ?? 3;+ const sections = Array.isArray(ctx.sections) ? ctx.sections : [];+ const findings = [];+ for (const s of sections) {+ if (findings.length >= max) break;+ const text = s?.content || '';+ const { number, location } = sectionIssue(s);+ for (const echo of findWordEchoes(text, { windowWords })) {+ if (findings.length >= max) break;+ findings.push({+ severity: ctx.severityDefault,+ category: 'style',+ location,+ problem: `The distinctive word "${echo.word}" repeats within ${echo.gap} words — a close echo readers notice.`,+ suggestion: 'Vary the wording or move one instance further away (close repetition of an ordinary word is invisible; a distinctive one echoes).',+ anchorQuote: echo.anchor,+ issueNumber: number,+ });+ }+ for (const run of findRepeatedOpeners(text, { minRun })) {+ if (findings.length >= max) break;+ findings.push({+ severity: ctx.severityDefault,+ category: 'style',+ location,+ problem: `${run.count} sentences in a row open with "${run.word}" — monotonous sentence-start rhythm ("${run.word}… ${run.word}… ${run.word}…").`,+ suggestion: 'Recast some openers — lead with a different subject, a subordinate clause, or merge sentences to break the pattern.',+ anchorQuote: run.anchor,+ issueNumber: number,+ });+ }+ }+ return findings;+ },+ },+ {+ id: 'prose.sentence-rhythm',+ sources: ['manuscript'],+ label: 'Sentence rhythm & variety',+ description:+ 'Advisory flag for monotonous sentence rhythm — when nearly every sentence in an issue is the same length (low variation in word count). Varied sentence length is what gives prose its music; a uniform cadence reads flat.',+ scope: 'issue',+ kind: 'deterministic',+ category: 'style',+ severityDefault: 'low',+ defaultEnabled: true,+ needsManuscript: true,+ configSchema: z.object({+ // Coefficient of variation (stddev/mean of sentence lengths) at/below which+ // the rhythm is "monotonous". Lower = stricter (only the flattest passages).+ minVariation: z.number().min(0).max(1).default(0.35),+ // Don't judge rhythm on a passage shorter than this many sentences.+ minSentences: z.number().int().min(3).max(50).default(8),+ maxFindings: z.number().int().min(1).max(50).default(20),+ }),+ configFields: [+ { key: 'minVariation', label: 'Variation threshold', type: 'number', min: 0, max: 1, step: 0.05, help: 'Flag an issue whose sentence-length variation (stddev / mean) is at or below this. Lower = only the flattest, most uniform passages.' },+ { key: 'minSentences', label: 'Minimum sentences to judge', type: 'number', min: 3, max: 50, step: 1, help: 'Skip passages shorter than this many sentences (too few to judge rhythm).' },+ { key: 'maxFindings', label: 'Max findings per run', type: 'number', min: 1, max: 50, step: 1, help: 'Cap findings so a 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 minVariation = cfg.minVariation ?? 0.35;+ const minSentences = cfg.minSentences ?? 8;+ const sections = Array.isArray(ctx.sections) ? ctx.sections : [];+ const findings = [];+ for (const s of sections) {+ if (findings.length >= max) break;+ const r = measureSentenceRhythm(s?.content || '', { minSentences });+ if (!r || r.cv > minVariation) continue;+ const { number, location } = sectionIssue(s);+ const meanRounded = Math.round(r.mean);+ findings.push({+ severity: ctx.severityDefault,+ category: 'style',+ location,+ problem: `Monotonous sentence rhythm — ${r.count} sentences averaging ${meanRounded} words with little length variation (variation ${Math.round(r.cv * 100) / 100}). A uniform cadence reads flat.`,+ suggestion: 'Vary sentence length deliberately — cut a long sentence with a short punchy one, or combine choppy sentences to build momentum.',+ anchorQuote: '',+ issueNumber: number,+ });+ }+ return findings;+ },+ },+ {+ id: 'prose.telling-emotion',+ sources: ['manuscript'],+ label: 'Telling-not-showing emotion (LLM)',+ description:+ 'LLM scan for named-emotion statements ("she was sad", "he felt nervous", "they were afraid") that the prose tells rather than dramatizes. Flags strong candidates to convert to showing (action, sensation, subtext) — LLM-judged to avoid the false positives a bare keyword scan would produce.',+ scope: 'issue',+ kind: 'llm',+ category: 'style',+ severityDefault: 'low',+ defaultEnabled: true,+ needsManuscript: true,+ configSchema: z.object({+ 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 told emotion = one spot), so this stays+ // a plain per-chunk run with no cross-chunk digest — mirrors prose.dead-metaphor.+ run: (ctx) => runManuscriptLlmCheck(ctx, {+ stage: TELLING_EMOTION_STAGE,+ category: 'style',+ overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS,+ buildVars: (manuscript) => ({ manuscript }),+ }),+ },{id: 'prose.dead-metaphor',sources: ['manuscript'],diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.jsindex 838c80ea32..2255945eb5 100644--- a/server/lib/editorial/checkRegistry.test.js+++ b/server/lib/editorial/checkRegistry.test.js@@ -2325,6 +2325,122 @@ describe('prose.cliches / prose.modifier-stacking / prose.dead-metaphor (#1308)'});});+describe('copy-edit prose-tic bundle (#1306)', () => {+ const FILTER = 'prose.filter-words';+ const CRUTCH = 'prose.crutch-words';+ const ADVERBS = 'prose.adverbs';+ const PASSIVE = 'prose.passive-voice';+ const GESTURES = 'prose.repeated-gestures';+ const ECHOES = 'prose.word-echoes';+ const RHYTHM = 'prose.sentence-rhythm';+ const TELLING = 'prose.telling-emotion';+ const DETERMINISTIC = [FILTER, CRUTCH, ADVERBS, PASSIVE, GESTURES, ECHOES, RHYTHM];++ it('registers all eight as manuscript style checks of the right kind', () => {+ for (const id of DETERMINISTIC) {+ const c = getCheck(id);+ expect(c.kind, id).toBe('deterministic');+ expect(c.category, id).toBe('style');+ expect(c.sources, id).toEqual(['manuscript']);+ expect(c.needsManuscript, id).toBe(true);+ expect(c.gate({ manuscript: '' }), id).toBe(false);+ expect(c.gate({ manuscript: '# Issue 1\n\nprose' }), id).toBeTruthy();+ }+ expect(getCheck(TELLING).kind).toBe('llm');+ expect(getCheck(TELLING).category).toBe('style');+ });++ it('prose.filter-words flags above the density threshold and anchors to the issue', () => {+ // 5 filter words in ~10 words → ~500/1000, well above default 6.+ const sections = [{ number: 2, content: 'She saw it. He felt it. They heard it. I noticed. We watched.' }];+ const findings = getCheck(FILTER).run({ sections, config: {}, severityDefault: 'low' });+ expect(findings).toHaveLength(1);+ expect(findings[0].issueNumber).toBe(2);+ expect(findings[0].category).toBe('style');+ expect(findings[0].anchorQuote.toLowerCase()).toBe('saw');+ });++ it('prose.filter-words stays silent below the density threshold', () => {+ const filler = Array.from({ length: 200 }, (_, i) => `w${i}`).join(' ');+ const sections = [{ number: 1, content: `She saw it. ${filler}` }];+ expect(getCheck(FILTER).run({ sections, config: { densityPer1000: 6 }, severityDefault: 'low' })).toEqual([]);+ });++ it('prose.crutch-words excludes "that" unless includeThat is set', () => {+ const sections = [{ number: 1, content: 'It was just really very that thing that he saw.' }];+ const off = getCheck(CRUTCH).run({ sections, config: { densityPer1000: 0 }, severityDefault: 'low' });+ expect(off).toHaveLength(1);+ const on = getCheck(CRUTCH).run({ sections, config: { densityPer1000: 0, includeThat: true }, severityDefault: 'low' });+ // "that" now counted → both findings present, but it's one section so still one finding;+ // assert the anchor is the first crutch word regardless.+ expect(on[0].anchorQuote.toLowerCase()).toBe('just');+ });++ it('prose.adverbs flags dialogue-tag adverbs at higher severity regardless of density', () => {+ const sections = [{ number: 3, content: '"Fine," she said angrily as the room slept.' }];+ const findings = getCheck(ADVERBS).run({ sections, config: { densityPer1000: 999 }, severityDefault: 'low' });+ const tag = findings.find((f) => /dialogue tag/i.test(f.problem));+ expect(tag).toBeTruthy();+ expect(tag.severity).toBe('medium'); // escalated one step above low+ expect(tag.anchorQuote.toLowerCase()).toBe('angrily');+ });++ it('prose.passive-voice flags above the rate threshold', () => {+ const sections = [{ number: 1, content: 'The door was opened. The vase was broken. It was forgotten.' }];+ const findings = getCheck(PASSIVE).run({ sections, config: { densityPer1000: 0 }, severityDefault: 'low' });+ expect(findings).toHaveLength(1);+ expect(/passive/i.test(findings[0].problem)).toBe(true);+ });++ it('prose.repeated-gestures tallies a gesture across the manuscript and flags body-part autonomy', () => {+ const sections = [+ { number: 1, content: Array(5).fill('He nodded.').join(' ') + ' Her eyes followed him across the room.' },+ { number: 2, content: Array(4).fill('She nodded.').join(' ') },+ ];+ const findings = getCheck(GESTURES).run({ sections, config: { maxPerGesture: 8 }, severityDefault: 'low' });+ const gesture = findings.find((f) => /gesture "nod"/i.test(f.problem));+ expect(gesture).toBeTruthy(); // 9 total ≥ 8+ const body = findings.find((f) => /body part/i.test(f.problem));+ expect(body).toBeTruthy();+ expect(body.anchorQuote.toLowerCase()).toContain('eyes followed');+ });++ it('prose.word-echoes flags a distinctive close repeat and a repeated-opener run', () => {+ const sections = [{ number: 4, content: 'The obsidian gleamed. She raised the obsidian. He ran. He fell. He stood.' }];+ const findings = getCheck(ECHOES).run({ sections, config: {}, severityDefault: 'low' });+ expect(findings.some((f) => /obsidian/i.test(f.problem))).toBe(true);+ expect(findings.some((f) => /open with "He"/i.test(f.problem))).toBe(true);+ });++ it('prose.sentence-rhythm flags a uniform passage and stays silent on a varied one', () => {+ const uniform = [{ number: 1, content: Array(10).fill('one two three four five.').join(' ') }];+ const flat = getCheck(RHYTHM).run({ sections: uniform, config: {}, severityDefault: 'low' });+ expect(flat).toHaveLength(1);+ expect(/monotonous/i.test(flat[0].problem)).toBe(true);+ });++ it('prose.telling-emotion passes the planned chunk to the model and forces the style category', async () => {+ let seen = null;+ const findings = await getCheck(TELLING).run({+ manuscript: '# Issue 5\n\nShe was sad.',+ config: { maxFindings: 12 },+ severityDefault: 'low',+ planManuscriptChunks: async (_stage, opts) => {+ expect(opts.overheadTokens).toBeGreaterThan(0);+ return ['# Issue 5\n\nShe was sad.'];+ },+ callStagedLLM: async (_stage, vars) => {+ seen = vars.manuscript;+ return { content: { findings: [{ severity: 'low', issueNumber: 5, location: 'Issue 5 — told sadness', problem: 'told emotion', anchorQuote: 'She was sad' }] } };+ },+ });+ expect(seen).toBe('# Issue 5\n\nShe was sad.');+ expect(findings).toHaveLength(1);+ expect(findings[0].category).toBe('style');+ expect(findings[0].issueNumber).toBe(5);+ });+});+describe('prose anti-pattern bundle (#1300)', () => {const OPENING = 'opening.wrong-start';const MIRROR = 'prose.mirror-description';diff --git a/server/lib/editorial/index.js b/server/lib/editorial/index.jsindex 3663cc6992..c252013850 100644--- a/server/lib/editorial/index.js+++ b/server/lib/editorial/index.js@@ -4,3 +4,5 @@ export * from './checkRegistry.js';export * from './cliches.js';export * from './italicThoughts.js';export * from './nameSimilarity.js';+export * from './proseTics.js';+export * from './repetition.js';diff --git a/server/lib/editorial/proseTics.js b/server/lib/editorial/proseTics.jsnew file mode 100644index 0000000000..43b0619d67--- /dev/null+++ b/server/lib/editorial/proseTics.js@@ -0,0 +1,360 @@+/**+ * Copy-edit prose-tic deterministic primitives (#1306) for the editorial check+ * registry. Pure and dependency-free (no side-effecting imports) so it stays+ * unit-testable in isolation — mirrors ./cliches.js and ./nameSimilarity.js.+ *+ * Word-level scanners backing the deterministic "copy-edit" check group in+ * checkRegistry.js:+ * - findFilterWords() → `prose.filter-words` (distancing verbs)+ * - findCrutchWords() → `prose.crutch-words` (intensifiers / fillers)+ * - 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)+ *+ * Sentence/window-level repetition scanners live in ./repetition.js, which reuses+ * the `tokenizeWords` / `splitSentences` primitives exported here.+ *+ * The LLM sibling `prose.telling-emotion` (named-emotion → dramatize) handles the+ * judgment case these pure scanners deliberately avoid (false-positive-prone).+ */++// ---------------------------------------------------------------------------+// Seed word/phrase lists. Each is curated, not exhaustive; a series can extend+// (extraWords) or mute (allowWords) entries per house style. Entries are+// lowercase, free of leading/trailing punctuation. Multi-word entries ("began+// to") are matched as whole-word phrases with flexible internal whitespace.+// ---------------------------------------------------------------------------++// Filter words — distancing verbs that put a layer of narration between the+// reader and the experience ("she saw the door open" → "the door opened").+export const FILTER_WORDS = Object.freeze([+ 'saw', 'watched', 'noticed', 'realized', 'realised', 'felt', 'heard',+ 'seemed', 'looked', 'wondered', 'thought', 'knew', 'decided', 'sensed',+ 'observed', 'spotted', 'glimpsed', 'began to', 'started to',+]);++// Crutch / filler words — intensifiers and hedges that almost always delete+// cleanly. Bare "that" is deliberately OMITTED from the default: grammatical+// "that" (relative clauses) dominates its count and would swamp the density+// signal, so it ships behind the per-check `includeThat` toggle instead.+export const CRUTCH_WORDS = Object.freeze([+ 'just', 'really', 'very', 'quite', 'somewhat', 'suddenly', 'actually',+ 'basically', 'literally', 'simply', 'totally', 'definitely', 'certainly',+ 'in order to',+]);++// Common gesture verbs — the body-language tics that, repeated, read as a+// nervous narrator twitch. Counted across the manuscript; an overused gesture+// is flagged. Stored as base verbs; the matcher also catches the -s/-ing forms.+export const GESTURE_WORDS = Object.freeze([+ 'nod', 'smile', 'shrug', 'sigh', 'frown', 'grin', 'smirk', 'wince',+ 'blink', 'gasp', 'chuckle', 'glance', 'gulp', 'gawk', 'scowl', 'grimace',+]);++// Dialogue-tag verbs — when one of these is immediately followed by an -ly+// adverb ("she said angrily"), the adverb is propping up a tag that should+// carry its weight through the dialogue itself. Higher-severity sub-signal.+const DIALOGUE_TAGS = Object.freeze([+ 'said', 'asked', 'replied', 'whispered', 'shouted', 'muttered', 'murmured',+ 'answered', 'called', 'cried', 'yelled', 'snapped', 'hissed', 'breathed',+ 'added', 'continued', 'stated', 'remarked', 'demanded', 'growled',+]);++// Be-verbs for the passive-voice heuristic.+const BE_VERBS = Object.freeze([+ 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'am',+]);++// Irregular past participles the -ed suffix rule misses. Not exhaustive — the+// passive check is advisory, so a missed participle just under-flags (safe).+const IRREGULAR_PARTICIPLES = new Set([+ 'broken', 'taken', 'given', 'seen', 'done', 'gone', 'written', 'spoken',+ 'chosen', 'frozen', 'stolen', 'driven', 'known', 'grown', 'thrown', 'blown',+ 'drawn', 'worn', 'born', 'borne', 'torn', 'sworn', 'shown', 'hidden',+ 'beaten', 'eaten', 'fallen', 'forgotten', 'gotten', 'held', 'kept', 'left',+ 'lost', 'made', 'met', 'paid', 'put', 'said', 'sent', 'set', 'sold', 'told',+ 'built', 'bought', 'brought', 'caught', 'taught', 'felt', 'found', 'hung',+ 'led', 'meant', 'read', 'struck', 'swept', 'swung', 'understood', 'wound',+ 'bound', 'ground', 'cut', 'hit', 'hurt', 'shut', 'split', 'spread', 'cast',+ 'forbidden', 'forgiven', 'mistaken', 'shaken', 'woken', 'risen', 'ridden',+ 'bitten', 'beaten', 'hidden', 'laid', 'lain',+]);++// Common -ly words that are NOT adverbs (nouns/adjectives) — the suffix rule+// would otherwise flag them. Lowercase. Bare "only" is excluded here so it+// stays the crutch-word check's concern, not the adverb check's.+const NON_ADVERB_LY = new Set([+ 'only', 'family', 'reply', 'supply', 'apply', 'ally', 'rally', 'bully',+ 'jelly', 'belly', 'lily', 'holy', 'ugly', 'italy', 'july', 'fly', 'ply',+ 'sly', 'rely', 'comply', 'imply', 'multiply', 'assembly', 'anomaly',+ 'monopoly', 'panoply', 'melancholy', 'early', 'lonely', 'lovely', 'silly',+ 'chilly', 'jolly', 'folly', 'dolly', 'gully', 'sully', 'tally', 'wally',+ 'belly', 'telly', 'wholly', 'duly', 'truly', 'unduly', 'curly', 'burly',+ 'surly', 'gnarly', 'pearly', 'hourly', 'daily', 'doily', 'gaily',+]);++function escapeRegExp(s) {+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}++function normalizeWord(p) {+ return typeof p === 'string' ? p.trim().toLowerCase() : '';+}++/**+ * Tokenize prose into words with their absolute character offsets. Apostrophes+ * are kept inside a word ("couldn't") so contractions stay whole. Exported so+ * ./repetition.js shares one tokenization with the word-level scanners.+ *+ * @param {string} text+ * @returns {Array<{ word: string, lower: string, index: number }>}+ */+export function tokenizeWords(text) {+ if (typeof text !== 'string' || !text) return [];+ const re = /[A-Za-z][A-Za-z']*/g;+ const out = [];+ let m;+ while ((m = re.exec(text)) !== null) {+ out.push({ word: m[0], lower: m[0].toLowerCase(), index: m.index });+ }+ return out;+}++/**+ * Split prose into sentences with their absolute start offsets. A naive split+ * on sentence-ending punctuation (. ! ?) — good enough for rhythm/opening+ * scans; the editorial checks built on it are advisory. Exported for reuse.+ *+ * @param {string} text+ * @returns {Array<{ text: string, index: number }>}+ */+export function splitSentences(text) {+ if (typeof text !== 'string' || !text) return [];+ const out = [];+ const re = /[^.!?]+[.!?]*/g;+ let m;+ while ((m = re.exec(text)) !== null) {+ const raw = m[0];+ if (!raw.trim()) continue;+ // Anchor the index at the first non-space char of the sentence.+ const lead = raw.length - raw.trimStart().length;+ out.push({ text: raw.trim(), index: m.index + lead });+ }+ return out;+}++// Build a case-insensitive matcher for a list of single-word and/or multi-word+// phrase entries. Single words get word boundaries; phrases match whole-word+// with flexible internal whitespace (like ./cliches.js). Returns null when the+// effective list (seed + extra − allow) is empty.+function buildListMatcher(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 seen = new Set();+ const entries = [];+ for (const w of [...seed, ...extra]) {+ const norm = normalizeWord(w);+ if (!norm || seen.has(norm) || allow.has(norm)) continue;+ seen.add(norm);+ entries.push(norm);+ }+ if (!entries.length) return null;+ // Longest-first so a phrase ("began to") wins over its leading word ("began").+ const alt = entries+ .sort((a, b) => b.length - a.length)+ .map((e) => escapeRegExp(e).replace(/\s+/g, '\\s+'))+ .join('|');+ return new RegExp(`(?<!\\w)(?:${alt})(?!\\w)`, 'gi');+}++// Generic occurrence scan over a word/phrase list. Returns every match with its+// offset + the canonical lowercased entry, in position order.+function scanList(text, seed, opts) {+ if (typeof text !== 'string' || !text) return [];+ const matcher = buildListMatcher(seed, opts);+ if (!matcher) return [];+ const out = [];+ let m;+ while ((m = matcher.exec(text)) !== null) {+ out.push({ entry: m[0].toLowerCase().replace(/\s+/g, ' '), index: m.index, anchor: m[0] });+ }+ return out;+}++/**+ * Filter-word occurrences (distancing verbs). One entry per match.+ * @param {string} text+ * @param {{ allowWords?: string[], extraWords?: string[] }} [opts]+ * @returns {Array<{ entry: string, index: number, anchor: string }>}+ */+export function findFilterWords(text, opts = {}) {+ return scanList(text, FILTER_WORDS, opts);+}++/**+ * Crutch/filler-word occurrences. Bare "that" is included only when+ * `opts.includeThat` is true (off by default — grammatical "that" is noisy).+ * @param {string} text+ * @param {{ allowWords?: string[], extraWords?: string[], includeThat?: boolean }} [opts]+ * @returns {Array<{ entry: string, index: number, anchor: string }>}+ */+export function findCrutchWords(text, opts = {}) {+ const seed = opts.includeThat ? [...CRUTCH_WORDS, 'that'] : CRUTCH_WORDS;+ return scanList(text, seed, opts);+}++// Is `lower` an -ly adverb? (ends in "ly", length ≥ 4, not in the non-adverb set)+function isLyAdverb(lower) {+ return lower.length >= 4 && lower.endsWith('ly') && !NON_ADVERB_LY.has(lower);+}++/**+ * Adverb occurrences. Returns every -ly adverb with a `dialogueTag` flag set+ * when it immediately follows a dialogue tag ("said angrily") — those are the+ * higher-severity ones (the tag should carry its weight through the dialogue).+ *+ * @param {string} text+ * @param {{ allowWords?: string[] }} [opts] allowWords mutes specific adverbs.+ * @returns {Array<{ word: string, index: number, anchor: string, dialogueTag: boolean }>}+ */+export function findAdverbs(text, opts = {}) {+ const tokens = tokenizeWords(text);+ if (!tokens.length) return [];+ const allow = new Set((Array.isArray(opts.allowWords) ? opts.allowWords : []).map(normalizeWord).filter(Boolean));+ const tagSet = new Set(DIALOGUE_TAGS);+ const out = [];+ for (let i = 0; i < tokens.length; i += 1) {+ const t = tokens[i];+ if (!isLyAdverb(t.lower) || allow.has(t.lower)) continue;+ const prev = i > 0 ? tokens[i - 1].lower : '';+ out.push({ word: t.word, index: t.index, anchor: t.word, dialogueTag: tagSet.has(prev) });+ }+ return out;+}++// Is `lower` a likely past participle? (-ed suffix or a known irregular)+function isPastParticiple(lower) {+ if (IRREGULAR_PARTICIPLES.has(lower)) return true;+ return lower.length >= 4 && lower.endsWith('ed');+}++/**+ * Passive-voice candidates: a be-verb followed (allowing up to two intervening+ * adverbs) by a past participle — "was broken", "is quietly forgotten". A+ * heuristic, advisory only; returns the be-verb…participle span anchored.+ *+ * @param {string} text+ * @returns {Array<{ index: number, anchor: string, be: string, participle: string }>}+ */+export function findPassiveVoice(text) {+ const tokens = tokenizeWords(text);+ if (!tokens.length) return [];+ const beSet = new Set(BE_VERBS);+ const out = [];+ for (let i = 0; i < tokens.length; i += 1) {+ if (!beSet.has(tokens[i].lower)) continue;+ // Look ahead past up to two -ly adverbs for the participle.+ let j = i + 1;+ let skipped = 0;+ while (j < tokens.length && skipped < 2 && isLyAdverb(tokens[j].lower)) { j += 1; skipped += 1; }+ if (j < tokens.length && isPastParticiple(tokens[j].lower) && !beSet.has(tokens[j].lower)) {+ const start = tokens[i].index;+ const end = tokens[j].index + tokens[j].word.length;+ out.push({ index: start, anchor: text.slice(start, end), be: tokens[i].lower, participle: tokens[j].lower });+ i = j; // don't re-anchor the same participle+ }+ }+ return out;+}++// Generate the regular inflections of a base verb: the base, +s, +ed/+d,+// +ing, plus doubled-final-consonant (nod → nodded/nodding) and dropped-e+// (smile → smiled/smiling) forms. Returns lowercased, de-duped surface forms.+function inflect(base) {+ const b = base.toLowerCase();+ const forms = new Set([b, `${b}s`]);+ if (b.endsWith('e')) {+ // smile → smiles, smiled, smiling+ const stem = b.slice(0, -1);+ forms.add(`${b}d`);+ forms.add(`${stem}ing`);+ } else {+ forms.add(`${b}ed`);+ forms.add(`${b}ing`);+ // Single short CVC base doubles its final consonant: nod → nodded/nodding.+ if (/[^aeiou][aeiou][^aeiouwxy]$/.test(b)) {+ const dbl = b + b.slice(-1);+ forms.add(`${dbl}ed`);+ forms.add(`${dbl}ing`);+ }+ // -y → -ies / -ied handled loosely; gesture bases rarely end in -y, skip.+ }+ return [...forms];+}++// Gesture matcher: each base verb plus its regular inflections (see inflect()).+function gestureMatcher(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 seen = new Set();+ const forms = [];+ 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 inflect(norm)) forms.push(f);+ }+ if (!forms.length) return null;+ // Longest-first so "nodding" wins over "nod" under leftmost-match alternation.+ const alt = [...new Set(forms)].sort((a, b) => b.length - a.length).map(escapeRegExp).join('|');+ return new RegExp(`\\b(?:${alt})\\b`, 'gi');+}++// Body-part-autonomy regex: a possessive + body part + an action verb, the+// "her eyes followed him across the room" / "his hand shot out" tic where a+// body part acts on its own. High-precision, advisory.+const BODY_PART_AUTONOMY_RE = new RegExp(+ '\\b(?:his|her|their|its|my|your)\\s+'+ + '(?:eyes?|gaze|hands?|fingers?|feet|foot|legs?|arms?|head|brows?|eyebrows?|lips?|mouth)\\s+'+ + '(?:\\w+ed|shot|flew|darted|wandered|roamed|traveled|travelled|followed|drifted|swept|raked|'+ + 'slid|crawled|danced|leapt|leaped|jumped|moved|trailed|locked|met|found|sought)\\b',+ 'gi',+);++/**+ * Gesture tally + body-part-autonomy occurrences.+ * @param {string} text+ * @param {{ allowWords?: string[], extraWords?: string[] }} [opts]+ * @returns {{+ * gestures: Array<{ base: string, index: number, anchor: string }>,+ * bodyParts: Array<{ index: number, anchor: string }>+ * }}+ */+export function findGestures(text, opts = {}) {+ if (typeof text !== 'string' || !text) return { gestures: [], bodyParts: [] };+ const matcher = gestureMatcher(GESTURE_WORDS, opts);+ const gestures = [];+ if (matcher) {+ // Map each inflected surface form back to its base for tally grouping.+ 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();+ for (const b of [...GESTURE_WORDS, ...extra]) {+ const norm = normalizeWord(b);+ if (!norm || allow.has(norm)) continue;+ for (const f of inflect(norm)) if (!formToBase.has(f)) formToBase.set(f, norm);+ }+ let m;+ while ((m = matcher.exec(text)) !== null) {+ const lower = m[0].toLowerCase();+ gestures.push({ base: formToBase.get(lower) || lower, index: m.index, anchor: m[0] });+ }+ }+ const bodyParts = [];+ let bm;+ BODY_PART_AUTONOMY_RE.lastIndex = 0;+ while ((bm = BODY_PART_AUTONOMY_RE.exec(text)) !== null) {+ bodyParts.push({ index: bm.index, anchor: bm[0] });+ }+ return { gestures, bodyParts };+}diff --git a/server/lib/editorial/proseTics.test.js b/server/lib/editorial/proseTics.test.jsnew file mode 100644index 0000000000..d722dd8bdb--- /dev/null+++ b/server/lib/editorial/proseTics.test.js@@ -0,0 +1,167 @@+import { describe, it, expect } from 'vitest';+import {+ tokenizeWords,+ splitSentences,+ findFilterWords,+ findCrutchWords,+ findAdverbs,+ findPassiveVoice,+ findGestures,+ FILTER_WORDS,+ CRUTCH_WORDS,+} from './proseTics.js';++describe('tokenizeWords', () => {+ it('keeps apostrophes inside contractions and records offsets', () => {+ const toks = tokenizeWords("She couldn't go.");+ expect(toks.map((t) => t.word)).toEqual(['She', "couldn't", 'go']);+ expect(toks[0].index).toBe(0);+ expect(toks[1].lower).toBe("couldn't");+ });++ it('returns [] for non-strings and empties', () => {+ expect(tokenizeWords('')).toEqual([]);+ expect(tokenizeWords(null)).toEqual([]);+ expect(tokenizeWords(42)).toEqual([]);+ });+});++describe('splitSentences', () => {+ it('splits on sentence-ending punctuation and anchors at the first non-space char', () => {+ const text = 'One. Two! Three?';+ const s = splitSentences(text);+ expect(s.map((x) => x.text)).toEqual(['One.', 'Two!', 'Three?']);+ expect(text.slice(s[1].index, s[1].index + 4)).toBe('Two!');+ });++ it('ignores whitespace-only spans', () => {+ expect(splitSentences(' ')).toEqual([]);+ });+});++describe('findFilterWords', () => {+ it('flags distancing verbs and phrase entries', () => {+ const hits = findFilterWords('She saw the door and began to run.');+ const entries = hits.map((h) => h.entry);+ expect(entries).toContain('saw');+ expect(entries).toContain('began to');+ });++ it('matches "began to" as a whole phrase (longest-first), not bare "began"', () => {+ const hits = findFilterWords('He began to move.');+ expect(hits.map((h) => h.anchor.toLowerCase())).toContain('began to');+ });++ it('respects allowWords and extraWords', () => {+ expect(findFilterWords('She saw it.', { allowWords: ['saw'] })).toEqual([]);+ const extra = findFilterWords('She gazed at it.', { extraWords: ['gazed'] });+ expect(extra.map((h) => h.entry)).toContain('gazed');+ });++ it('does not match substrings (sawmill ≠ saw)', () => {+ expect(findFilterWords('The sawmill was loud.')).toEqual([]);+ });++ it('seed list is frozen and lowercase', () => {+ expect(Object.isFrozen(FILTER_WORDS)).toBe(true);+ for (const w of FILTER_WORDS) expect(w).toBe(w.toLowerCase());+ });+});++describe('findCrutchWords', () => {+ it('flags intensifiers but excludes bare "that" by default', () => {+ const hits = findCrutchWords('It was just really very that thing.');+ const entries = hits.map((h) => h.entry);+ expect(entries).toEqual(expect.arrayContaining(['just', 'really', 'very']));+ expect(entries).not.toContain('that');+ });++ it('includes "that" only when includeThat is set', () => {+ const hits = findCrutchWords('the book that he read', { includeThat: true });+ expect(hits.map((h) => h.entry)).toContain('that');+ });++ it('matches "in order to" as a phrase', () => {+ const hits = findCrutchWords('He left in order to escape.');+ expect(hits.map((h) => h.entry)).toContain('in order to');+ });++ it('CRUTCH_WORDS omits bare "that"', () => {+ expect(CRUTCH_WORDS).not.toContain('that');+ });+});++describe('findAdverbs', () => {+ it('flags -ly adverbs and skips non-adverb -ly words', () => {+ const hits = findAdverbs('She quickly entered the family home only briefly.');+ const words = hits.map((h) => h.word.toLowerCase());+ expect(words).toContain('quickly');+ expect(words).toContain('briefly');+ expect(words).not.toContain('family'); // not an adverb+ expect(words).not.toContain('only'); // excluded+ });++ it('marks dialogue-tag adverbs', () => {+ const hits = findAdverbs('"Fine," she said angrily.');+ const tag = hits.find((h) => h.word.toLowerCase() === 'angrily');+ expect(tag).toBeTruthy();+ expect(tag.dialogueTag).toBe(true);+ });++ it('does not mark a non-tag-preceded adverb as a dialogue tag', () => {+ const hits = findAdverbs('She walked slowly.');+ expect(hits[0].dialogueTag).toBe(false);+ });++ it('respects allowWords', () => {+ const hits = findAdverbs('She ran quickly.', { allowWords: ['quickly'] });+ expect(hits).toEqual([]);+ });+});++describe('findPassiveVoice', () => {+ it('flags be-verb + past participle', () => {+ const hits = findPassiveVoice('The door was opened by Sam.');+ expect(hits.length).toBe(1);+ expect(hits[0].be).toBe('was');+ expect(hits[0].participle).toBe('opened');+ });++ it('flags irregular participles', () => {+ const hits = findPassiveVoice('The vase was broken.');+ expect(hits.map((h) => h.participle)).toContain('broken');+ });++ it('allows an intervening adverb', () => {+ const hits = findPassiveVoice('It was quietly forgotten.');+ expect(hits.length).toBe(1);+ expect(hits[0].participle).toBe('forgotten');+ });++ it('does not flag a be-verb with no participle', () => {+ expect(findPassiveVoice('She was happy.')).toEqual([]);+ });+});++describe('findGestures', () => {+ it('tallies gesture verbs across inflections', () => {+ const { gestures } = findGestures('He nodded. She nods. They were nodding.');+ expect(gestures.every((g) => g.base === 'nod')).toBe(true);+ expect(gestures.length).toBe(3);+ });++ it('flags body-part autonomy', () => {+ const { bodyParts } = findGestures('Her eyes followed him across the room.');+ expect(bodyParts.length).toBe(1);+ expect(bodyParts[0].anchor.toLowerCase()).toContain('eyes followed');+ });++ it('respects allowWords for gestures', () => {+ const { gestures } = findGestures('He smiled.', { allowWords: ['smile'] });+ expect(gestures).toEqual([]);+ });++ it('returns empty shape for empty text', () => {+ expect(findGestures('')).toEqual({ gestures: [], bodyParts: [] });+ });+});diff --git a/server/lib/editorial/repetition.js b/server/lib/editorial/repetition.jsnew file mode 100644index 0000000000..d1fcd1042f--- /dev/null+++ b/server/lib/editorial/repetition.js@@ -0,0 +1,125 @@+/**+ * Word-echo & sentence-rhythm deterministic primitives (#1306) for the editorial+ * check registry. Pure and dependency-free — mirrors ./proseTics.js, whose+ * `tokenizeWords` / `splitSentences` it reuses.+ *+ * Scanners backing the deterministic copy-edit checks:+ * - findWordEchoes() → `prose.word-echoes` (distinctive word repeated in a window)+ * - findRepeatedOpeners() → `prose.repeated-openers` (sentences starting the same word)+ * - measureSentenceRhythm() → `prose.sentence-rhythm` (monotonous sentence length)+ */++import { tokenizeWords, splitSentences } from './proseTics.js';++// The most common English words — never an "echo" worth flagging when repeated.+// A repeated "the"/"and" is invisible; a repeated "obsidian" three sentences+// apart is the tic. Lowercase.+const STOPWORDS = new Set([+ 'the', 'a', 'an', 'and', 'or', 'but', 'nor', 'for', 'so', 'yet', 'of', 'to',+ 'in', 'on', 'at', 'by', 'as', 'is', 'are', 'was', 'were', 'be', 'been',+ 'being', 'am', 'it', 'its', 'he', 'she', 'they', 'them', 'his', 'her',+ 'their', 'him', 'i', 'me', 'my', 'we', 'us', 'our', 'you', 'your', 'this',+ 'that', 'these', 'those', 'there', 'here', 'with', 'from', 'into', 'onto',+ 'out', 'up', 'down', 'off', 'over', 'then', 'than', 'not', 'no', 'do',+ 'does', 'did', 'has', 'have', 'had', 'will', 'would', 'can', 'could',+ 'should', 'shall', 'may', 'might', 'must', 'if', 'when', 'while', 'all',+ 'one', 'who', 'what', 'which', 'how', 'why', 'where', 'about', 'just', 'very',+ 'some', 'any', 'each', 'both', 'more', 'most', 'such', 'only', 'own', 'too',+ 'now', 'said', 'like', 'back', 'get', 'got',+]);++const isEchoCandidate = (lower) => lower.length >= 5 && !STOPWORDS.has(lower);++/**+ * Distinctive words repeated within a window of `windowWords` tokens. Returns+ * one finding per repeated word (the SECOND occurrence — the echo — anchored),+ * deduped per word so a word echoed five times reports once. Position-ordered.+ *+ * @param {string} text+ * @param {{ windowWords?: number, minLen?: number }} [opts]+ * windowWords — how close two occurrences must be to count as an echo (default 50).+ * minLen — minimum word length to consider (default 5).+ * @returns {Array<{ word: string, index: number, anchor: string, gap: number }>}+ */+export function findWordEchoes(text, opts = {}) {+ const tokens = tokenizeWords(text);+ if (!tokens.length) return [];+ const windowWords = Number.isInteger(opts.windowWords) && opts.windowWords > 0 ? opts.windowWords : 50;+ const minLen = Number.isInteger(opts.minLen) && opts.minLen > 0 ? opts.minLen : 5;+ const lastSeen = new Map(); // lower → token-position index+ const reported = new Set();+ const out = [];+ for (let i = 0; i < tokens.length; i += 1) {+ const { lower } = tokens[i];+ if (lower.length < minLen || STOPWORDS.has(lower)) { lastSeen.set(lower, i); continue; }+ if (lastSeen.has(lower)) {+ const gap = i - lastSeen.get(lower);+ if (gap <= windowWords && !reported.has(lower)) {+ reported.add(lower);+ out.push({ word: tokens[i].word, index: tokens[i].index, anchor: tokens[i].word, gap });+ }+ }+ lastSeen.set(lower, i);+ }+ return out.sort((a, b) => a.index - b.index);+}++/**+ * Runs of consecutive sentences that open with the same word ("He… He… He…").+ * Returns one finding per run of `minRun`+ sentences sharing an opener.+ *+ * @param {string} text+ * @param {{ minRun?: number }} [opts] minRun — sentences in a row to flag (default 3, min 2).+ * @returns {Array<{ word: string, index: number, anchor: string, count: number }>}+ */+export function findRepeatedOpeners(text, opts = {}) {+ const sentences = splitSentences(text);+ if (sentences.length < 2) return [];+ const minRun = Math.max(2, Number.isInteger(opts.minRun) ? opts.minRun : 3);+ // The opening word of each sentence (lowercased) + its offset.+ const openers = sentences.map((s) => {+ const m = /[A-Za-z][A-Za-z']*/.exec(s.text);+ return { word: m ? m[0] : '', lower: m ? m[0].toLowerCase() : '', index: s.index };+ });+ const out = [];+ let runStart = 0;+ for (let i = 1; i <= openers.length; i += 1) {+ const same = i < openers.length && openers[i].lower && openers[i].lower === openers[runStart].lower;+ if (!same) {+ const count = i - runStart;+ if (count >= minRun && openers[runStart].lower) {+ out.push({+ word: openers[runStart].word,+ index: openers[runStart].index,+ anchor: openers[runStart].word,+ count,+ });+ }+ runStart = i;+ }+ }+ return out;+}++/**+ * Sentence-rhythm measure over a passage. Computes per-sentence word counts and+ * their coefficient of variation (stddev / mean). A LOW coefficient means the+ * sentences are all about the same length — monotonous rhythm. Returns null when+ * there aren't enough sentences to judge.+ *+ * @param {string} text+ * @param {{ minSentences?: number }} [opts] minSentences — floor before judging (default 5).+ * @returns {{ count: number, mean: number, stddev: number, cv: number, lengths: number[] } | null}+ */+export function measureSentenceRhythm(text, opts = {}) {+ const sentences = splitSentences(text);+ const minSentences = Number.isInteger(opts.minSentences) && opts.minSentences > 1 ? opts.minSentences : 5;+ if (sentences.length < minSentences) return null;+ const lengths = sentences.map((s) => (s.text.match(/[A-Za-z][A-Za-z']*/g) || []).length);+ const count = lengths.length;+ const mean = lengths.reduce((a, b) => a + b, 0) / count;+ if (mean <= 0) return null;+ const variance = lengths.reduce((a, b) => a + (b - mean) ** 2, 0) / count;+ const stddev = Math.sqrt(variance);+ return { count, mean, stddev, cv: stddev / mean, lengths };+}diff --git a/server/lib/editorial/repetition.test.js b/server/lib/editorial/repetition.test.jsnew file mode 100644index 0000000000..0f02358f89--- /dev/null+++ b/server/lib/editorial/repetition.test.js@@ -0,0 +1,71 @@+import { describe, it, expect } from 'vitest';+import {+ findWordEchoes,+ findRepeatedOpeners,+ measureSentenceRhythm,+} from './repetition.js';++describe('findWordEchoes', () => {+ it('flags a distinctive word repeated within the window', () => {+ const hits = findWordEchoes('The obsidian blade gleamed. She raised the obsidian high.');+ expect(hits.map((h) => h.word.toLowerCase())).toContain('obsidian');+ });++ it('ignores common stopwords and short words', () => {+ const hits = findWordEchoes('The cat sat on the mat and the dog ran.');+ expect(hits).toEqual([]); // "the" is a stopword, "cat"/"mat" too short / distinct+ });++ it('does not flag a repeat beyond the window', () => {+ const filler = Array.from({ length: 60 }, (_, i) => `word${i}`).join(' ');+ const text = `obsidian ${filler} obsidian`;+ expect(findWordEchoes(text, { windowWords: 50 })).toEqual([]);+ });++ it('dedups: a word echoed many times reports once', () => {+ const hits = findWordEchoes('crimson crimson crimson crimson');+ expect(hits.filter((h) => h.word.toLowerCase() === 'crimson').length).toBe(1);+ });+});++describe('findRepeatedOpeners', () => {+ it('flags a run of sentences opening with the same word', () => {+ const hits = findRepeatedOpeners('He ran. He jumped. He fell.');+ expect(hits.length).toBe(1);+ expect(hits[0].word.toLowerCase()).toBe('he');+ expect(hits[0].count).toBe(3);+ });++ it('does not flag a run shorter than minRun', () => {+ expect(findRepeatedOpeners('He ran. She jumped. He fell.', { minRun: 3 })).toEqual([]);+ });++ it('honors a lower minRun', () => {+ const hits = findRepeatedOpeners('She ran. She fell.', { minRun: 2 });+ expect(hits.length).toBe(1);+ expect(hits[0].count).toBe(2);+ });+});++describe('measureSentenceRhythm', () => {+ it('reports low variation for uniform sentence lengths', () => {+ // Every sentence is five words → variation should be ~0.+ const sentence = 'one two three four five.';+ const r = measureSentenceRhythm(Array(10).fill(sentence).join(' '), { minSentences: 5 });+ expect(r).not.toBeNull();+ expect(r.count).toBe(10);+ expect(r.cv).toBeLessThan(0.05);+ });++ it('reports higher variation for mixed lengths', () => {+ const text = 'Go. The quick brown fox jumped over the lazy sleeping dog near the river. Stop. '+ + 'A much longer sentence with many more words than the others around it here now. Yes.';+ const r = measureSentenceRhythm(text, { minSentences: 3 });+ expect(r).not.toBeNull();+ expect(r.cv).toBeGreaterThan(0.3);+ });++ it('returns null below the sentence floor', () => {+ expect(measureSentenceRhythm('One. Two.', { minSentences: 5 })).toBeNull();+ });+});