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-2166]): deterministic style.voice-drift statistical voice fingerprint

Adam Eivya6e30293fefa
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c6b651fdf3..4752f39fb6 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -11,6 +11,7 @@
## Creative Writing Quality Engine
- **[issue-2165] Editorial review now catches recognizable "AI slop" writing tells automatically.** Four new deterministic editorial checks join the existing 68: a tiered banned-word scan (hard-bans like "delve"/"myriad"/"utilize"; suspicious words like "robust"/"seamless" only flagged when 3+ cluster in one paragraph), fiction-specific AI-tell idioms ("a sense of dread", "couldn't help but", "eyes widened", "a wave of relief washed over him"), rhetorical structural tics ("not just X, but Y", runs of "did not [verb]", punchy three-sentence-in-a-row bursts like "Fast. Precise. Deadly."), and structural burstiness (em-dash overuse, essay-style transition-word openers, mechanically uniform paragraph lengths). Each surfaces as an editorial finding with the exact offending quote, same as the existing prose checks — configurable thresholds and house-style allowlists included.
+- **[issue-2166] Editorial review now flags an issue whose narrative voice statistically drifts from the rest of the series.** A new deterministic `style.voice-drift` check measures each issue's prose fingerprint — sentence-length rhythm (mean, spread, variation), fragment and long-sentence rates, paragraph shape, dialogue ratio, em-dash rate, abstract-noun and simile density, and how often sentences open the same way — then compares every issue against the series average and flags the outliers (e.g. "Issue 7's sentence-length variation is 0.18 vs the series 0.41 — prose has gone metronomic"). It's the cheap, deterministic complement to the existing LLM voice-consistency check: no model cost, and it names the exact issue and metric that drifted. You can tune the sensitivity (σ threshold), and optionally declare vocabulary "wells" — register categories like `trade: forge, anvil; body: pulse, sinew` — so it also flags an issue that drops a register the series leans on. It stays off until at least 3 issues are drafted (statistics need a series to compare against).
## Human Activity Tracking
diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.md
index 5a1dfa6181..7102b9a254 100644
--- a/server/lib/editorial/README.md
+++ b/server/lib/editorial/README.md
@@ -202,6 +202,7 @@ runner-injected `ctx.callInlineLLM` (an inline-prompt sibling of
| `proseTics.js` | Pure, dependency-free copy-edit prose-tic primitives for the #1306 line-edit group: `tokenizeWords` / `splitSentences` (shared tokenization), `findFilterWords` (`prose.filter-words`), `findHedgeWords` (`prose.hedge-words` — hedge/weasel distance markers: metaphorical distance, dialogue hedges, cognitive weasel words), `findCrutchWords` (`prose.crutch-words`), `findAdverbs` (`prose.adverbs` — `-ly` adverbs + dialogue-tag adverbs), `findPassiveVoice` (`prose.passive-voice` — be-verb + past-participle heuristic; classifies each hit `weak`/`stative`/`mood` + `byAgent` so #1593 context tuning can suppress intentional passive) and its `filterPassiveVoice` companion (drops `stative` predicate-adjectives + `mood` setting images unless `suppressIntentional` is off), `findGestures` (`prose.repeated-gestures` — gesture tally + body-part autonomy), plus the seed `FILTER_WORDS` / `HEDGE_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`. |
| `slopScore.js` | Pure, dependency-free deterministic "AI slop" scoring primitives for #2165 (CWQE Phase 1) — EXTENDS proseTics.js/cliches.js/repetition.js rather than duplicating them: tiered banned-word scanners (`findBannedWordsTier1` hard-ban, `findSuspiciousWordClusters` Tier 2 cluster-of-3+) backing `prose.slop-banned-words`; fiction AI-tell idiom regexes (`findAiTells`) backing `prose.ai-tells`; rhetorical structural-tic detectors (`findNotJustButPatterns`, `findNotSayingPatterns`, `findNegativeAssertions`, `findTheWaySimiles`, `findTriadicShortSentences`, combined by `findStructuralTics`) backing `prose.structural-tics`; and quantitative burstiness signals (`emDashDensityPer1000`, `transitionOpenerRatio`, `paragraphLengthUniformity`, `countSectionBreaks`) backing `prose.burstiness`. `computeSlopPenalty()` composites all of the above — plus `repetition.js`'s sentence-length CV, read but never re-reported as its own finding — into a documented-weight 0–10 penalty for Phase 3's `qualityScore = judgeOverall − slopPenalty`. |
+| `voiceFingerprint.js` | Pure, dependency-free statistical voice-fingerprint primitives for the deterministic `style.voice-drift` check (#2166 — CWQE Phase 2), the cheap sibling of the LLM `style.voice-consistency`. Reuses `tokenizeWords`/`splitSentences` (proseTics.js) + `splitParagraphs`/`emDashDensityPer1000` (slopScore.js) rather than re-implementing them. `computeFingerprint(text)` measures one issue's metric vector (sentence mean/σ/CV, fragment %, long-sentence %, paragraph mean/σ, dialogue ratio, em-dash rate, abstract-noun & simile density per 1k, dominant sentence-opener %, plus optional `well:*` vocabulary coverage); `splitManuscriptByIssue` / `voiceFingerprintMatrix` fingerprint every `# Issue N` section; `computeVoiceDrift` computes series mean/σ per metric and flags issues > threshold·σ out (small-N gated below `minIssues`); `parseVoiceWells` parses the `name: word, word; …` config spec; `describeDrift` renders a finding sentence; `renderFingerprintTable` renders the issues×metrics matrix (outliers marked). `VOICE_METRICS` is the static metric descriptor list. |
| `comicPacing.js` | Pure, dependency-free comic-pacing primitives for the #1314 comic-pacing group: `isSplashPage`, `comicSpreadLayout` (recto/verso + spread + `beginsSpread` page-turn map), `summarizeComicPages`, `analyzePanelRhythm` (`comic.panel-rhythm` — splash overuse / back-to-back splashes / overcrowded pages / grid monotony), `comicPageTurnSummary` + `authoredRevealSummary` (LLM-context renderers for `comic.page-turn-beats`). Operates on already-parsed comic pages (the runner parses each issue's stored comic script and injects them as the `comicScript` source) so the editorial dir stays import-pure. |
| `shotContinuity.js` | Pure, dependency-free storyboard shot-continuity primitives for the deterministic `visual.shot-continuity` check (#1315): `findAxisReversals` (180°-rule axis flips across a continuity-linked shot pair using `screenDirection`) and `findShotTypeMonotony` (a scene whose classified shots all share one `shotType`). Also `summarizeStoryboardShots` (#1466) — renders the collected `{ issueNumber, scene }` storyboard list into a compact per-scene shot block shared by the LLM siblings `visual.eyeline-match` (gaze reciprocity / eyeline-vs-screen-direction) and `visual.appearance-continuity` (#1467 — diffs the same entity's wardrobe/prop/setting descriptions across shots for contradictions). Reads the shot-grammar fields from `server/lib/shotGrammar.js`. |
| `dialogue.js` | Pure, dependency-free dialogue-tag primitives for the #1307 dialogue-craft group: `findSaidBookisms` (`dialogue.said-bookisms` — ornate speech tags like *expostulated*/*opined* and non-speech tags like "she smiled", matched only when adjacent to a double-quote span) and `findUnattributedDialogueRuns` (`dialogue.attribution-clarity` — runs of consecutive untagged/unbeated dialogue lines where the speaker can't be tracked), plus `attributeDialogueByOwner` (the coarse per-character dialogue-line tally behind `cast.representation-balance`'s dialogue-share signal, #1312 — credits each quoted paragraph to the first owner named in its beat) and the seed `SAID_BOOKISMS` / `NON_SPEECH_TAGS` lists. Also `inventoryDialogueTags` + `splitScenes` + `findDialogueTagVariety` (`dialogue.tag-variety`, #1587 — per-scene tag inventory flagging within-scene **monotony** (one verb dominates) and **over-variation** (a fresh verb on nearly every line); collapses inflections onto a base lemma via `PLAIN_SPEECH_TAG_GROUPS`). The LLM siblings `dialogue.on-the-nose` (subtext-free / "as you know, Bob" dialogue) and `dialogue.voice-distinctiveness` (per-character voice against canon `speechPattern`/`speechAccent`) handle the judgment cases. |
diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.js
index 3cf641b7aa..6fe438a1f0 100644
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@ -217,6 +217,7 @@ const CHECK_ORDER = Object.freeze([
'dialogue.on-the-nose',
'dialogue.voice-distinctiveness',
'style.voice-consistency',
+ 'style.voice-drift',
'prose.kill-your-darlings',
'prose.italic-thoughts',
'endings.cliffhanger',
diff --git a/server/lib/editorial/checks/proseStyle.js b/server/lib/editorial/checks/proseStyle.js
index 8ab3392d53..4cb401e2f5 100644
--- a/server/lib/editorial/checks/proseStyle.js
+++ b/server/lib/editorial/checks/proseStyle.js
@@ -36,6 +36,7 @@ import {
styleGuideExpectations,
z,
} from '../checkInfra.js';
+import { computeVoiceDrift, describeDrift, parseVoiceWells } from '../voiceFingerprint.js';
export const proseStyleChecks = [
{
@@ -1000,6 +1001,95 @@ export const proseStyleChecks = [
});
},
},
+ {
+ id: 'style.voice-drift',
+ sources: ['manuscript'],
+ label: 'Statistical voice drift (deterministic)',
+ description:
+ "Deterministic sibling of style.voice-consistency — where that LLM check judges tone subjectively, this MEASURES each issue's prose fingerprint (sentence rhythm, fragment/long-sentence rates, paragraph shape, dialogue ratio, em-dash rate, abstract-noun/simile density, dominant sentence-opener, plus any configured vocabulary wells), computes the series mean/σ per metric, and flags an issue that sits more than a threshold's σ from the series voice — naming the metric, the issue value vs the series mean, and the direction (\"issue 7 sentence-length CV 0.18 vs series 0.41 — prose has gone metronomic\"). It VERIFIES that the asserted voice is statistically true per issue. Gates off with fewer than 3 issues drafted (σ is meaningless). No LLM cost.",
+ scope: 'series',
+ kind: 'deterministic',
+ category: 'style',
+ // A drift is a texture concern like its LLM sibling; a moderate wobble floors
+ // at 'low' and a strong (≥2.5σ) outlier escalates one rank in run().
+ severityDefault: 'low',
+ defaultEnabled: true,
+ // Reads the stitched manuscript (its per-issue `# Issue N` sections) — so the
+ // runner only pays the section-collection I/O when a manuscript check is on.
+ needsManuscript: true,
+ configSchema: z.object({
+ // How many σ from the series mean before an issue's metric is flagged.
+ sigmaThreshold: z.number().min(0.5).max(4).default(1.5),
+ // Minimum issues drafted before the check runs (σ is meaningless below 3).
+ minIssues: z.number().int().min(3).max(30).default(3),
+ // Cap findings per run so a wildly-uneven series can't flood the review.
+ maxFindings: z.number().int().min(1).max(50).default(12),
+ // Optional vocabulary "wells" — register categories to track coverage of,
+ // as `name: word, word; name2: word` (series-configurable per-check).
+ vocabularyWells: z.string().max(2000).default(''),
+ }),
+ configFields: [
+ {
+ key: 'sigmaThreshold',
+ label: 'Drift threshold (σ)',
+ type: 'number',
+ min: 0.5,
+ max: 4,
+ step: 0.1,
+ help: 'How far from the series mean (in standard deviations) an issue must sit on a metric before it is flagged. Lower = more sensitive.',
+ },
+ {
+ key: 'minIssues',
+ label: 'Minimum issues to run',
+ type: 'number',
+ min: 3,
+ max: 30,
+ step: 1,
+ help: 'The check stays off until at least this many issues are drafted — below 3 the standard deviation is meaningless and every issue reads as an outlier.',
+ },
+ {
+ key: 'maxFindings',
+ label: 'Max findings per run',
+ type: 'number',
+ min: 1,
+ max: 50,
+ step: 1,
+ help: 'Cap findings (most significant drift first) so a wildly uneven series can not flood the review.',
+ },
+ {
+ key: 'vocabularyWells',
+ label: 'Vocabulary wells (optional)',
+ type: 'text',
+ help: 'Register categories to track per issue, as "name: word, word; name2: word". Each becomes a tracked metric (coverage per 1k words) so a series can flag an issue that drops its trade/body/musical register.',
+ },
+ ],
+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,
+ run: (ctx) => {
+ const cfg = ctx.config || {};
+ const wells = parseVoiceWells(cfg.vocabularyWells || '');
+ const drift = computeVoiceDrift(ctx.manuscript, {
+ threshold: cfg.sigmaThreshold ?? 1.5,
+ minIssues: cfg.minIssues ?? 3,
+ wells,
+ });
+ if (drift.gatedOff) return [];
+ const cap = cfg.maxFindings ?? 12;
+ return drift.outliers.slice(0, cap).map((o) => ({
+ // A strong outlier (≥2.5σ) reads as real drift, not noise — escalate it a
+ // rank above the low floor; a marginal one stays low.
+ severity: escalateSeverity(ctx.severityDefault, Math.abs(o.z) >= 2.5 ? 1 : 0),
+ category: 'style',
+ location: `Issue ${o.issue} — narrative voice`,
+ problem: describeDrift(o),
+ suggestion:
+ `Reread Issue ${o.issue} for its ${o.label} against the rest of the series. `
+ + 'If the shift is a scene the story earns (a grimmer, terser chapter), leave it; '
+ + 'if it is unintentional drift, revise toward the series voice.',
+ anchorQuote: null,
+ issueNumber: o.issue,
+ }));
+ },
+ },
{
id: 'prose.kill-your-darlings',
sources: ['manuscript'],
diff --git a/server/lib/editorial/index.js b/server/lib/editorial/index.js
index db54bcffde..0f0ed21eb7 100644
--- a/server/lib/editorial/index.js
+++ b/server/lib/editorial/index.js
@@ -13,3 +13,4 @@ export * from './proseTics.js';
export * from './repetition.js';
export * from './shotContinuity.js';
export * from './slopScore.js';
+export * from './voiceFingerprint.js';
diff --git a/server/lib/editorial/voiceFingerprint.js b/server/lib/editorial/voiceFingerprint.js
new file mode 100644
index 0000000000..8230e8cd1d
--- /dev/null
+++ b/server/lib/editorial/voiceFingerprint.js
@@ -0,0 +1,415 @@
+/**
+ * Statistical voice fingerprint (#2166 — CWQE Phase 2) for the editorial check
+ * registry. Pure and dependency-free (no side-effecting imports — only the
+ * sibling editorial primitives) so it stays unit-testable in isolation, mirroring
+ * ./slopScore.js / ./repetition.js / ./proseTics.js.
+ *
+ * This is the cheap DETERMINISTIC complement to the LLM `style.voice-consistency`
+ * check (checks/proseStyle.js — subjective narrator tone). Where that check ASKS a
+ * model whether the tone wobbled, this one MEASURES a fixed metric vector per issue
+ * (sentence rhythm, fragment/long-sentence rates, paragraph shape, dialogue ratio,
+ * em-dash rate, abstract-noun/simile density, dominant opener, optional vocabulary
+ * "wells"), computes the series-wide mean/σ per metric, and names exactly which
+ * issue drifted, on which metric, and in which direction. autonovel used this to
+ * catch chapters whose sentence rhythm or vocabulary register silently diverged
+ * from the established series voice.
+ *
+ * Reuses (never re-implements) the shared tokenizers: `tokenizeWords` /
+ * `splitSentences` from ./proseTics.js and `splitParagraphs` /
+ * `emDashDensityPer1000` from ./slopScore.js — so a fingerprint counts words and
+ * segments sentences/paragraphs exactly the way every other deterministic check
+ * does.
+ */
+
+import { tokenizeWords, splitSentences } from './proseTics.js';
+import { splitParagraphs, emDashDensityPer1000 } from './slopScore.js';
+
+// Word suffixes that mark an abstract / nominalized noun. Overusing them ("the
+// realization of the situation") is the register signal a drifting issue shifts
+// on. A coarse suffix heuristic (no POS tagger) — advisory, like every editorial
+// deterministic check. Guarded by a minimum stem length below so short words
+// (e.g. "ship", "dom", "ity") don't false-match.
+const ABSTRACT_NOUN_SUFFIXES = Object.freeze([
+ 'tion', 'sion', 'ment', 'ness', 'ity', 'ance', 'ence', 'ism',
+ 'ship', 'hood', 'dom', 'acy', 'ude', 'ology',
+]);
+// A stem must have at least this many letters BEFORE the suffix, so "action" and
+// "nation" count (real abstract nouns) but "dom"/"ship"/"tion" as whole short
+// words don't.
+const ABSTRACT_MIN_STEM = 2;
+
+// Simile markers: an explicit "like a/an/the …" comparison, or an "as ADJ as …"
+// frame. Deliberately narrow — bare "like" (a filler/verb) and bare "as" (a
+// conjunction) are NOT counted, only these two comparison frames — so the density
+// tracks figurative reach, not filler.
+const SIMILE_LIKE_RE = /\blike\s+(?:a|an|the)\b/gi;
+const SIMILE_AS_AS_RE = /\bas\s+[A-Za-z]+\s+as\b/gi;
+// Any run of characters inside straight or curly double-quotes — the dialogue
+// span. Non-greedy so adjacent quoted lines stay separate.
+const DIALOGUE_SPAN_RE = /[“"]([^“”"]*)[”"]/g;
+
+const round2 = (n) => Math.round(n * 100) / 100;
+const round1 = (n) => Math.round(n * 10) / 10;
+
+// Population mean / std (divide by N, not N−1): the issues ARE the whole series
+// population, not a sample of a larger one, so σ is the population deviation.
+function meanOf(values) {
+ if (!values.length) return 0;
+ return values.reduce((a, b) => a + b, 0) / values.length;
+}
+function stdOf(values, mean) {
+ if (values.length < 2) return 0;
+ const m = typeof mean === 'number' ? mean : meanOf(values);
+ const variance = values.reduce((a, b) => a + (b - m) ** 2, 0) / values.length;
+ return Math.sqrt(variance);
+}
+
+/**
+ * The fixed metric vector every issue is fingerprinted on. Order here IS the
+ * column order of `voiceFingerprintMatrix`. Each descriptor carries a `label`
+ * (human name), a `unit` suffix for rendered values, and a `higher` phrase
+ * describing what a high value MEANS (its opposite is auto-derived), so a drift
+ * finding can read "prose has gone metronomic" instead of "cv is low".
+ *
+ * `wells` metrics are appended dynamically at compute time (one `well:<name>` per
+ * configured vocabulary well) — they are not part of this static list.
+ */
+export const VOICE_METRICS = Object.freeze([
+ { key: 'sentenceLenMean', label: 'sentence-length mean', unit: ' words', higher: 'longer sentences', lower: 'shorter sentences' },
+ { key: 'sentenceLenStd', label: 'sentence-length spread (σ)', unit: ' words', higher: 'more varied sentence lengths', lower: 'more uniform sentence lengths' },
+ { key: 'sentenceLenCV', label: 'sentence-length variation (CV)', unit: '', higher: 'more rhythmic variety', lower: 'metronomic, same-length prose' },
+ { key: 'fragmentPct', label: 'fragment rate (< 5 words)', unit: '%', higher: 'more sentence fragments', lower: 'fewer sentence fragments' },
+ { key: 'longSentencePct', label: 'long-sentence rate (> 30 words)', unit: '%', higher: 'more long, winding sentences', lower: 'fewer long sentences' },
+ { key: 'paragraphLenMean', label: 'paragraph-length mean', unit: ' words', higher: 'longer paragraphs', lower: 'shorter paragraphs' },
+ { key: 'paragraphLenStd', label: 'paragraph-length spread (σ)', unit: ' words', higher: 'more varied paragraph lengths', lower: 'more uniform paragraph lengths' },
+ { key: 'dialogueRatio', label: 'dialogue ratio', unit: '%', higher: 'more dialogue-driven prose', lower: 'more narration-driven prose' },
+ { key: 'emDashRate', label: 'em-dash rate (per 1k words)', unit: '', higher: 'heavier em-dash use', lower: 'lighter em-dash use' },
+ { key: 'abstractNounDensity', label: 'abstract-noun density (per 1k words)', unit: '', higher: 'a more abstract, nominal register', lower: 'a more concrete register' },
+ { key: 'simileDensity', label: 'simile density (per 1k words)', unit: '', higher: 'more figurative comparison', lower: 'less figurative comparison' },
+ { key: 'dominantOpenerPct', label: 'dominant sentence-opener share', unit: '%', higher: 'sentences that mostly open the same way', lower: 'more varied sentence openings' },
+]);
+
+const STATIC_METRIC_KEYS = Object.freeze(VOICE_METRICS.map((m) => m.key));
+
+/**
+ * Parse a vocabulary-wells spec into `[{ name, words: Set<string> }]`. The spec
+ * is a per-check-config string (series-configurable via the per-series check
+ * override) declaring register categories a series wants coverage tracked for:
+ *
+ * `trade: forge, anvil, temper; body: pulse, sinew, marrow`
+ *
+ * Categories are `;`-separated, `name: words` split on the first `:`, words
+ * `,`-separated (whitespace tolerated). Empty/malformed fragments are skipped
+ * (never throws) so a hand-typed spec can't break the check. Returns [] for a
+ * blank/absent spec.
+ *
+ * @param {string} spec
+ * @returns {Array<{ name: string, words: Set<string> }>}
+ */
+export function parseVoiceWells(spec) {
+ if (typeof spec !== 'string' || !spec.trim()) return [];
+ const out = [];
+ const seen = new Set();
+ for (const chunk of spec.split(';')) {
+ const colon = chunk.indexOf(':');
+ if (colon === -1) continue;
+ const name = chunk.slice(0, colon).trim().toLowerCase();
+ if (!name || seen.has(name)) continue;
+ const words = chunk
+ .slice(colon + 1)
+ .split(',')
+ .map((w) => w.trim().toLowerCase())
+ .filter(Boolean);
+ if (!words.length) continue;
+ seen.add(name);
+ out.push({ name, words: new Set(words) });
+ }
+ return out;
+}
+
+// Count of tokens (word objects from tokenizeWords) whose lowercase form is in
+// the well's set — the raw hit count, turned into a per-1k density below.
+function wellHits(tokens, well) {
+ let n = 0;
+ for (const t of tokens) if (well.words.has(t.lower)) n += 1;
+ return n;
+}
+
+/**
+ * The prose fingerprint of a single block of text — the metric vector for one
+ * issue. Pure. Returns `{ words, sentences, paragraphs, metrics: { key: number } }`
+ * where `metrics` carries every `VOICE_METRICS` key plus one `well:<name>` per
+ * configured well. An empty/near-empty block yields a fingerprint whose metrics
+ * are all 0 (never NaN), so a matrix row is always numeric.
+ *
+ * @param {string} text
+ * @param {{ wells?: Array<{ name: string, words: Set<string> }> }} [opts]
+ */
+export function computeFingerprint(text, opts = {}) {
+ const src = typeof text === 'string' ? text : '';
+ const wells = Array.isArray(opts.wells) ? opts.wells : [];
+ const tokens = tokenizeWords(src);
+ const totalWords = tokens.length;
+ const sentences = splitSentences(src);
+ const paragraphs = splitParagraphs(src);
+
+ // Sentence-length metrics (words per sentence via the shared word tokenizer, so
+ // "the cat's" counts identically to every other check).
+ const sentenceLengths = sentences.map((s) => tokenizeWords(s.text).length);
+ const sMean = meanOf(sentenceLengths);
+ const sStd = stdOf(sentenceLengths, sMean);
+ const sCount = sentenceLengths.length;
+ const fragmentPct = sCount ? (sentenceLengths.filter((n) => n > 0 && n < 5).length / sCount) * 100 : 0;
+ const longPct = sCount ? (sentenceLengths.filter((n) => n > 30).length / sCount) * 100 : 0;
+
+ // Paragraph-length metrics (words per paragraph).
+ const paragraphLengths = paragraphs.map((p) => tokenizeWords(p.text).length);
+ const pMean = meanOf(paragraphLengths);
+ const pStd = stdOf(paragraphLengths, pMean);
+
+ // Dialogue ratio: fraction of words that fall inside double-quoted spans.
+ let dialogueWords = 0;
+ let m;
+ DIALOGUE_SPAN_RE.lastIndex = 0;
+ while ((m = DIALOGUE_SPAN_RE.exec(src)) !== null) {
+ dialogueWords += tokenizeWords(m[1]).length;
+ }
+ const dialogueRatio = totalWords ? (dialogueWords / totalWords) * 100 : 0;
+
+ const emDashRate = emDashDensityPer1000(src).rate;
+
+ // Abstract-noun density per 1k words (suffix heuristic + min-stem guard).
+ let abstractHits = 0;
+ for (const t of tokens) {
+ const w = t.lower;
+ for (const suf of ABSTRACT_NOUN_SUFFIXES) {
+ if (w.length >= suf.length + ABSTRACT_MIN_STEM && w.endsWith(suf)) { abstractHits += 1; break; }
+ }
+ }
+ const abstractNounDensity = totalWords ? round1((abstractHits / totalWords) * 1000) : 0;
+
+ // Simile density per 1k words (the two comparison frames).
+ const simileHits = (src.match(SIMILE_LIKE_RE) || []).length + (src.match(SIMILE_AS_AS_RE) || []).length;
+ const simileDensity = totalWords ? round1((simileHits / totalWords) * 1000) : 0;
+
+ // Dominant sentence-opener share: the most common sentence-initial word, as a
+ // fraction of sentences. High = every sentence opens the same way ("He … He …").
+ const openerCounts = new Map();
+ for (const s of sentences) {
+ const first = tokenizeWords(s.text)[0];
+ if (!first) continue;
+ const key = first.lower;
+ openerCounts.set(key, (openerCounts.get(key) || 0) + 1);
+ }
+ let dominantOpener = 0;
+ for (const c of openerCounts.values()) if (c > dominantOpener) dominantOpener = c;
+ const dominantOpenerPct = sCount ? (dominantOpener / sCount) * 100 : 0;
+
+ const metrics = {
+ sentenceLenMean: round2(sMean),
+ sentenceLenStd: round2(sStd),
+ sentenceLenCV: sMean > 0 ? round2(sStd / sMean) : 0,
+ fragmentPct: round1(fragmentPct),
+ longSentencePct: round1(longPct),
+ paragraphLenMean: round2(pMean),
+ paragraphLenStd: round2(pStd),
+ dialogueRatio: round1(dialogueRatio),
+ emDashRate,
+ abstractNounDensity,
+ simileDensity,
+ dominantOpenerPct: round1(dominantOpenerPct),
+ };
+
+ // Optional vocabulary wells — coverage per 1k words per configured category.
+ for (const well of wells) {
+ metrics[`well:${well.name}`] = totalWords ? round1((wellHits(tokens, well) / totalWords) * 1000) : 0;
+ }
+
+ return { words: totalWords, sentences: sCount, paragraphs: paragraphLengths.length, metrics };
+}
+
+// Split the stitched manuscript into per-issue text blocks on the `# Issue N`
+// headers the manuscript stitcher emits (the same header shape
+// `conflictIntensityTally` in checkInfra.js keys on). Duplicate issue numbers (a
+// chunk boundary that repeats a header) accumulate into ONE block so an issue
+// isn't split into two thin, noisy fingerprints. Returns [] when there are no
+// headers (the drift check then gates off — a single unlabelled blob can't drift
+// against itself).
+const ISSUE_HEADER_RE = /^#+\s*Issue\s+(\d+)\b[^\n]*$/gim;
+export function splitManuscriptByIssue(manuscript) {
+ const text = typeof manuscript === 'string' ? manuscript : '';
+ if (!text.trim()) return [];
+ const marks = [];
+ let match;
+ ISSUE_HEADER_RE.lastIndex = 0;
+ while ((match = ISSUE_HEADER_RE.exec(text)) !== null) {
+ // `headerStart` = where the `# Issue N` line begins (so the PREVIOUS issue's
+ // body ends before it); `bodyStart` = just after the header line.
+ marks.push({ issue: Number(match[1]), headerStart: match.index, bodyStart: ISSUE_HEADER_RE.lastIndex });
+ }
+ if (!marks.length) return [];
+ const byIssue = new Map();
+ for (let i = 0; i < marks.length; i += 1) {
+ const bodyEnd = i + 1 < marks.length ? marks[i + 1].headerStart : text.length;
+ const body = text.slice(marks[i].bodyStart, bodyEnd);
+ byIssue.set(marks[i].issue, (byIssue.get(marks[i].issue) || '') + body);
+ }
+ return [...byIssue.entries()]
+ .sort((a, b) => a[0] - b[0])
+ .map(([issue, body]) => ({ issue, text: body }));
+}
+
+/**
+ * Fingerprint every issue in a stitched manuscript. Returns
+ * `{ issues: [{ issue, words, sentences, metrics }], metricKeys, wells }` sorted
+ * by issue number. `metricKeys` is the full ordered key list (static metrics then
+ * `well:*`), so the UI/table renders a stable column order. Pure.
+ *
+ * @param {string} manuscript
+ * @param {{ wells?: Array<{ name: string, words: Set<string> }> }} [opts]
+ */
+export function voiceFingerprintMatrix(manuscript, opts = {}) {
+ const wells = Array.isArray(opts.wells) ? opts.wells : [];
+ const blocks = splitManuscriptByIssue(manuscript);
+ const issues = blocks.map(({ issue, text }) => {
+ const fp = computeFingerprint(text, { wells });
+ return { issue, words: fp.words, sentences: fp.sentences, metrics: fp.metrics };
+ });
+ const metricKeys = [...STATIC_METRIC_KEYS, ...wells.map((w) => `well:${w.name}`)];
+ return { issues, metricKeys, wells: wells.map((w) => w.name) };
+}
+
+// Human label for a metric key (static descriptor label, or the well name).
+export function metricLabel(key) {
+ if (typeof key === 'string' && key.startsWith('well:')) {
+ return `"${key.slice(5)}" vocabulary (per 1k words)`;
+ }
+ const desc = VOICE_METRICS.find((mm) => mm.key === key);
+ return desc ? desc.label : key;
+}
+
+// Directional phrase for a drift: what a value ABOVE / BELOW the series mean means
+// for this metric. Wells share a generic phrasing (no static descriptor).
+function directionPhrase(key, direction) {
+ if (typeof key === 'string' && key.startsWith('well:')) {
+ return direction === 'high'
+ ? `leans harder on the "${key.slice(5)}" register`
+ : `uses the "${key.slice(5)}" register less`;
+ }
+ const desc = VOICE_METRICS.find((mm) => mm.key === key);
+ if (!desc) return direction === 'high' ? 'runs high' : 'runs low';
+ return direction === 'high' ? desc.higher : desc.lower;
+}
+
+// One-sentence finding text for a drift outlier — names the issue, the metric,
+// the issue value vs the series mean, the σ distance, and the plain-language
+// direction ("prose has gone metronomic").
+export function describeDrift(o) {
+ const label = metricLabel(o.metricKey);
+ const dir = directionPhrase(o.metricKey, o.direction);
+ const val = `${o.value}${o.unit || ''}`;
+ const mean = `${round2(o.mean)}${o.unit || ''}`;
+ return `Issue ${o.issue}'s ${label} is ${val} vs the series mean of ${mean} `
+ + `(${o.z.toFixed(1)}σ ${o.direction === 'high' ? 'above' : 'below'}) — ${dir}. `
+ + 'A statistical outlier against the series voice; confirm it is an earned modulation, not drift.';
+}
+
+/**
+ * Compute the voice-drift outliers for a stitched manuscript. Pure — returns
+ * structured results the `style.voice-drift` check maps to editorial findings (so
+ * the severity/config policy lives in the check, not here).
+ *
+ * Small-N gate: with fewer than `minIssues` issues drafted, σ is meaningless
+ * (a two-point "series" always shows each point as ±1σ), so the check gates OFF
+ * and emits nothing — `{ gatedOff: true, issueCount, outliers: [] }`.
+ *
+ * For each metric, a series mean/σ is computed across issues; a metric whose σ is
+ * ~0 (every issue identical) is skipped — no drift is possible. An issue is an
+ * outlier on a metric when its value is more than `threshold`·σ from the mean.
+ * Outliers are sorted by |z| descending so the most significant drift survives a
+ * downstream `maxFindings` cap.
+ *
+ * @param {string} manuscript
+ * @param {{ threshold?: number, minIssues?: number, wells?: Array<{ name: string, words: Set<string> }> }} [opts]
+ * @returns {{ gatedOff: boolean, issueCount: number, threshold: number,
+ * matrix: object, series: Record<string, {mean:number, std:number}>,
+ * outliers: Array<{ issue:number, metricKey:string, label:string, value:number,
+ * mean:number, std:number, z:number, direction:'high'|'low', unit:string }> }}
+ */
+export function computeVoiceDrift(manuscript, opts = {}) {
+ const threshold = Number.isFinite(opts.threshold) && opts.threshold > 0 ? opts.threshold : 1.5;
+ const minIssues = Number.isInteger(opts.minIssues) && opts.minIssues >= 3 ? opts.minIssues : 3;
+ const matrix = voiceFingerprintMatrix(manuscript, { wells: opts.wells });
+ const { issues, metricKeys } = matrix;
+
+ if (issues.length < minIssues) {
+ return { gatedOff: true, issueCount: issues.length, threshold, matrix, series: {}, outliers: [] };
+ }
+
+ const series = {};
+ const outliers = [];
+ const unitOf = (key) => {
+ if (typeof key === 'string' && key.startsWith('well:')) return '';
+ const d = VOICE_METRICS.find((mm) => mm.key === key);
+ return d ? d.unit : '';
+ };
+
+ for (const key of metricKeys) {
+ const values = issues.map((it) => it.metrics[key] ?? 0);
+ const mean = meanOf(values);
+ const std = stdOf(values, mean);
+ series[key] = { mean: round2(mean), std: round2(std) };
+ // A metric with no spread can't have an outlier — and dividing by ~0 σ would
+ // manufacture infinite z-scores. Skip it.
+ if (std < 1e-9) continue;
+ for (const it of issues) {
+ const value = it.metrics[key] ?? 0;
+ const z = (value - mean) / std;
+ if (Math.abs(z) <= threshold) continue;
+ outliers.push({
+ issue: it.issue,
+ metricKey: key,
+ label: metricLabel(key),
+ value,
+ mean,
+ std,
+ z,
+ direction: z > 0 ? 'high' : 'low',
+ unit: unitOf(key),
+ });
+ }
+ }
+
+ outliers.sort((a, b) => Math.abs(b.z) - Math.abs(a.z));
+ return { gatedOff: false, issueCount: issues.length, threshold, matrix, series, outliers };
+}
+
+/**
+ * Render a fingerprint matrix as a plain-text aligned table (issues as rows,
+ * metrics as columns, outlier cells marked with `*`). Used for debug/logging and
+ * covered by tests; the interactive UI table is a separate surface. Returns '' for
+ * an empty matrix.
+ *
+ * @param {ReturnType<typeof computeVoiceDrift>} drift
+ */
+export function renderFingerprintTable(drift) {
+ if (!drift || !drift.matrix || !drift.matrix.issues.length) return '';
+ const { matrix, series } = drift;
+ const keys = matrix.metricKeys;
+ const outlierSet = new Set((drift.outliers || []).map((o) => `${o.issue}:${o.metricKey}`));
+ const header = ['issue', ...keys.map(metricLabel)];
+ const rows = matrix.issues.map((it) => [
+ `#${it.issue}`,
+ ...keys.map((k) => {
+ const v = it.metrics[k] ?? 0;
+ return outlierSet.has(`${it.issue}:${k}`) ? `${v}*` : `${v}`;
+ }),
+ ]);
+ if (series && Object.keys(series).length) {
+ rows.push(['mean', ...keys.map((k) => `${series[k]?.mean ?? 0}`)]);
+ rows.push(['σ', ...keys.map((k) => `${series[k]?.std ?? 0}`)]);
+ }
+ const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => String(r[i]).length)));
+ const fmt = (cells) => cells.map((c, i) => String(c).padEnd(widths[i])).join(' ').trimEnd();
+ return [fmt(header), ...rows.map(fmt)].join('\n');
+}
diff --git a/server/lib/editorial/voiceFingerprint.test.js b/server/lib/editorial/voiceFingerprint.test.js
new file mode 100644
index 0000000000..bf0497c6f7
--- /dev/null
+++ b/server/lib/editorial/voiceFingerprint.test.js
@@ -0,0 +1,273 @@
+import { describe, it, expect } from 'vitest';
+import {
+ VOICE_METRICS,
+ parseVoiceWells,
+ computeFingerprint,
+ splitManuscriptByIssue,
+ voiceFingerprintMatrix,
+ computeVoiceDrift,
+ describeDrift,
+ renderFingerprintTable,
+ metricLabel,
+} from './voiceFingerprint.js';
+import { getCheck } from './checkRegistry.js';
+
+// A sentence of exactly `w` distinct words ending in a period. Words are numeric
+// tokens so they carry no abstract suffix / simile marker and every sentence
+// opens with the same word ("w0…") — keeping the non-tested metrics flat (σ 0)
+// so a fixture's drift is isolated to sentence/paragraph length.
+const sentence = (w) => `${Array.from({ length: w }, (_, i) => `w${i}`).join(' ')}.`;
+// One issue block = `n` sentences of `w` words, on a single line (one paragraph).
+const issueBlock = (n, w) => Array.from({ length: n }, () => sentence(w)).join(' ');
+// Stitch per-issue blocks under `# Issue N` headers the way the manuscript
+// stitcher does.
+const manuscriptOf = (blocks) =>
+ blocks.map((b, i) => `# Issue ${i + 1}\n\n${b}`).join('\n\n');
+
+describe('parseVoiceWells', () => {
+ it('parses categories, words, and lowercases + dedupes', () => {
+ const wells = parseVoiceWells('Trade: Forge, Anvil, temper ; body: pulse, sinew');
+ expect(wells).toEqual([
+ { name: 'trade', words: new Set(['forge', 'anvil', 'temper']) },
+ { name: 'body', words: new Set(['pulse', 'sinew']) },
+ ]);
+ });
+
+ it('skips malformed / empty fragments and duplicate names, never throws', () => {
+ expect(parseVoiceWells('')).toEqual([]);
+ expect(parseVoiceWells(' ')).toEqual([]);
+ expect(parseVoiceWells('no-colon-here')).toEqual([]);
+ expect(parseVoiceWells('empty: ; body: pulse')).toEqual([
+ { name: 'body', words: new Set(['pulse']) },
+ ]);
+ // First "trade" wins; the duplicate is dropped.
+ const dup = parseVoiceWells('trade: forge; trade: anvil');
+ expect(dup).toHaveLength(1);
+ expect(dup[0].words).toEqual(new Set(['forge']));
+ });
+});
+
+describe('computeFingerprint', () => {
+ it('measures sentence-length mean/std/CV and fragment/long rates', () => {
+ // Three sentences: 3, 3, and 30 words → mean 12, and the 30-word one is NOT
+ // > 30 (long is strictly > 30) while the 3-word ones ARE < 5 (fragments).
+ const text = `${sentence(3)} ${sentence(3)} ${sentence(30)}`;
+ const fp = computeFingerprint(text);
+ expect(fp.sentences).toBe(3);
+ expect(fp.metrics.sentenceLenMean).toBe(12); // (3+3+30)/3
+ // fragments = the two 3-word sentences → 2/3 = 66.7%
+ expect(fp.metrics.fragmentPct).toBe(66.7);
+ // long (>30) — the 30-word sentence is exactly 30, not > 30 → 0%
+ expect(fp.metrics.longSentencePct).toBe(0);
+ });
+
+ it('flags a > 30 word sentence as long', () => {
+ const fp = computeFingerprint(`${sentence(10)} ${sentence(31)}`);
+ expect(fp.metrics.longSentencePct).toBe(50); // 1 of 2
+ });
+
+ it('measures dialogue ratio from quoted spans', () => {
+ // 4 words total, 2 inside quotes → 50%.
+ const fp = computeFingerprint('She said "run now" quietly.');
+ // words: She said run now quietly = 5; quoted "run now" = 2 → 40%
+ expect(fp.metrics.dialogueRatio).toBe(40);
+ });
+
+ it('measures em-dash rate, abstract-noun density, and simile density per 1k', () => {
+ // "realization" (tion) + "kindness" (ness) are abstract; 2 of 9 words → 222.2/1k.
+ const abstract = computeFingerprint('the realization brought a strange kindness to him now');
+ expect(abstract.metrics.abstractNounDensity).toBe(222.2);
+
+ const dash = computeFingerprint('a b c — d e f g h i');
+ // 1 em-dash, 9 word tokens (dash isn't a word) → 111.1/1k
+ expect(dash.metrics.emDashRate).toBe(111.1);
+
+ // "like a" and "as bright as" → 2 similes over 9 words → 222.2/1k.
+ const simile = computeFingerprint('it moved like a ghost as bright as dawn');
+ expect(simile.metrics.simileDensity).toBe(222.2);
+ });
+
+ it('measures dominant sentence-opener share', () => {
+ // Two of three sentences open with "he" → 66.7%.
+ const fp = computeFingerprint('He ran. He fell. She laughed.');
+ expect(fp.metrics.dominantOpenerPct).toBe(66.7);
+ });
+
+ it('tracks configured vocabulary wells as per-1k coverage', () => {
+ const wells = parseVoiceWells('trade: forge, anvil');
+ // "forge" appears once in 4 words → 250/1k.
+ const fp = computeFingerprint('the forge burned bright', { wells });
+ expect(fp.metrics['well:trade']).toBe(250);
+ });
+
+ it('returns all-zero (never NaN) metrics for empty text', () => {
+ const fp = computeFingerprint('');
+ expect(fp.words).toBe(0);
+ for (const key of VOICE_METRICS.map((m) => m.key)) {
+ expect(Number.isFinite(fp.metrics[key])).toBe(true);
+ expect(fp.metrics[key]).toBe(0);
+ }
+ });
+});
+
+describe('splitManuscriptByIssue', () => {
+ it('splits on # Issue N headers in numeric order', () => {
+ const ms = '# Issue 2\n\nbeta prose here.\n\n# Issue 1\n\nalpha prose here.';
+ const blocks = splitManuscriptByIssue(ms);
+ expect(blocks.map((b) => b.issue)).toEqual([1, 2]);
+ expect(blocks.find((b) => b.issue === 1).text).toContain('alpha');
+ expect(blocks.find((b) => b.issue === 2).text).toContain('beta');
+ });
+
+ it('merges duplicate issue headers (a chunk boundary) into one block', () => {
+ const ms = '# Issue 1\n\nfirst half.\n\n# Issue 1\n\nsecond half.';
+ const blocks = splitManuscriptByIssue(ms);
+ expect(blocks).toHaveLength(1);
+ expect(blocks[0].text).toContain('first half');
+ expect(blocks[0].text).toContain('second half');
+ });
+
+ it('returns [] with no headers or empty input', () => {
+ expect(splitManuscriptByIssue('just prose, no headers')).toEqual([]);
+ expect(splitManuscriptByIssue('')).toEqual([]);
+ expect(splitManuscriptByIssue(null)).toEqual([]);
+ });
+});
+
+describe('voiceFingerprintMatrix', () => {
+ it('fingerprints every issue and lists metric keys with wells last', () => {
+ const wells = parseVoiceWells('trade: forge');
+ const ms = manuscriptOf([issueBlock(2, 5), issueBlock(2, 5)]);
+ const matrix = voiceFingerprintMatrix(ms, { wells });
+ expect(matrix.issues.map((i) => i.issue)).toEqual([1, 2]);
+ expect(matrix.metricKeys[0]).toBe('sentenceLenMean');
+ expect(matrix.metricKeys[matrix.metricKeys.length - 1]).toBe('well:trade');
+ expect(matrix.wells).toEqual(['trade']);
+ });
+});
+
+describe('computeVoiceDrift', () => {
+ it('gates off below minIssues (σ meaningless)', () => {
+ const ms = manuscriptOf([issueBlock(3, 5), issueBlock(3, 20)]); // only 2 issues
+ const drift = computeVoiceDrift(ms);
+ expect(drift.gatedOff).toBe(true);
+ expect(drift.issueCount).toBe(2);
+ expect(drift.outliers).toEqual([]);
+ });
+
+ it('flags the outlier issue on sentence-length mean with hand-computed σ', () => {
+ // 3 issues at mean 5, 1 issue at mean 20 → values [5,5,5,20].
+ // mean = 8.75, σ = √42.1875 ≈ 6.495, z(issue4) = 11.25/6.495 ≈ 1.732 (> 1.5).
+ const ms = manuscriptOf([issueBlock(3, 5), issueBlock(3, 5), issueBlock(3, 5), issueBlock(3, 20)]);
+ const drift = computeVoiceDrift(ms);
+ expect(drift.gatedOff).toBe(false);
+ expect(drift.series.sentenceLenMean.mean).toBeCloseTo(8.75, 2);
+ // Every outlier is the drifting issue (4), never issues 1–3.
+ expect(drift.outliers.every((o) => o.issue === 4)).toBe(true);
+ const meanOutlier = drift.outliers.find((o) => o.metricKey === 'sentenceLenMean');
+ expect(meanOutlier).toBeTruthy();
+ expect(meanOutlier.direction).toBe('high');
+ expect(Math.abs(meanOutlier.z)).toBeCloseTo(1.732, 2);
+ });
+
+ it('skips metrics with zero spread (no manufactured infinite z)', () => {
+ const ms = manuscriptOf([issueBlock(3, 5), issueBlock(3, 5), issueBlock(3, 5), issueBlock(3, 20)]);
+ const drift = computeVoiceDrift(ms);
+ // No issue uses similes / em-dashes / fragments → those σ are 0, so they can
+ // never produce an outlier.
+ for (const flat of ['simileDensity', 'emDashRate', 'sentenceLenStd', 'sentenceLenCV']) {
+ expect(drift.outliers.some((o) => o.metricKey === flat)).toBe(false);
+ expect(drift.series[flat].std).toBe(0);
+ }
+ });
+
+ it('respects a custom sigma threshold', () => {
+ const ms = manuscriptOf([issueBlock(3, 5), issueBlock(3, 5), issueBlock(3, 5), issueBlock(3, 20)]);
+ // z ≈ 1.732: flagged at 1.5, but NOT at 2.0.
+ expect(computeVoiceDrift(ms, { threshold: 2.0 }).outliers.some((o) => o.metricKey === 'sentenceLenMean')).toBe(false);
+ expect(computeVoiceDrift(ms, { threshold: 1.5 }).outliers.some((o) => o.metricKey === 'sentenceLenMean')).toBe(true);
+ });
+
+ it('sorts outliers by |z| descending', () => {
+ const ms = manuscriptOf([issueBlock(3, 5), issueBlock(3, 5), issueBlock(3, 5), issueBlock(3, 40)]);
+ const drift = computeVoiceDrift(ms);
+ const zs = drift.outliers.map((o) => Math.abs(o.z));
+ for (let i = 1; i < zs.length; i += 1) expect(zs[i - 1]).toBeGreaterThanOrEqual(zs[i]);
+ });
+});
+
+describe('describeDrift + renderFingerprintTable', () => {
+ it('describeDrift names the issue, values, σ, and direction', () => {
+ const o = {
+ issue: 7, metricKey: 'sentenceLenCV', label: 'sentence-length variation (CV)',
+ value: 0.18, mean: 0.41, std: 0.1, z: -2.3, direction: 'low', unit: '',
+ };
+ const text = describeDrift(o);
+ expect(text).toContain('Issue 7');
+ expect(text).toContain('0.18');
+ expect(text).toContain('0.41');
+ expect(text).toContain('metronomic'); // the "lower" phrase for CV
+ expect(text).toContain('below');
+ });
+
+ it('renderFingerprintTable renders rows, mean/σ, and marks outliers with *', () => {
+ const ms = manuscriptOf([issueBlock(3, 5), issueBlock(3, 5), issueBlock(3, 5), issueBlock(3, 20)]);
+ const drift = computeVoiceDrift(ms);
+ const table = renderFingerprintTable(drift);
+ expect(table).toContain('#4');
+ expect(table).toContain('mean');
+ expect(table).toContain('σ');
+ expect(table).toContain('*'); // issue 4's outlier cell is starred
+ });
+
+ it('metricLabel resolves static metrics and wells', () => {
+ expect(metricLabel('sentenceLenMean')).toBe('sentence-length mean');
+ expect(metricLabel('well:trade')).toContain('trade');
+ });
+});
+
+describe('style.voice-drift check (registry wiring)', () => {
+ const runCheck = (ms, config = {}, severityDefault = 'low') => {
+ const check = getCheck('style.voice-drift');
+ expect(check).toBeTruthy();
+ return check.run({ manuscript: ms, config, severityDefault });
+ };
+
+ it('is registered as a deterministic series check', () => {
+ const check = getCheck('style.voice-drift');
+ expect(check.scope).toBe('series');
+ expect(check.kind).toBe('deterministic');
+ expect(check.needsManuscript).toBe(true);
+ });
+
+ it('emits findings anchored to the drifting issue', () => {
+ const ms = manuscriptOf([issueBlock(3, 5), issueBlock(3, 5), issueBlock(3, 5), issueBlock(3, 20)]);
+ const findings = runCheck(ms);
+ expect(findings.length).toBeGreaterThan(0);
+ expect(findings.every((f) => f.issueNumber === 4)).toBe(true);
+ expect(findings.every((f) => f.category === 'style')).toBe(true);
+ expect(findings[0].location).toContain('Issue 4');
+ });
+
+ it('gates off (no findings) below 3 issues', () => {
+ const ms = manuscriptOf([issueBlock(3, 5), issueBlock(3, 20)]);
+ expect(runCheck(ms)).toEqual([]);
+ });
+
+ it('caps findings at maxFindings, most significant first', () => {
+ const ms = manuscriptOf([issueBlock(3, 5), issueBlock(3, 5), issueBlock(3, 5), issueBlock(3, 40)]);
+ const findings = runCheck(ms, { maxFindings: 1 });
+ expect(findings).toHaveLength(1);
+ });
+
+ it('escalates a strong (≥2.5σ) outlier above the low floor', () => {
+ // 8 issues, one drifting → z = √7 ≈ 2.646 (≥ 2.5) → severity escalates low→medium.
+ const blocks = [...Array(7).fill(issueBlock(3, 5)), issueBlock(3, 20)];
+ const ms = manuscriptOf(blocks);
+ const findings = runCheck(ms);
+ const meanFinding = findings.find((f) => f.problem.includes('sentence-length mean'));
+ expect(meanFinding).toBeTruthy();
+ expect(meanFinding.severity).toBe('medium');
+ expect(meanFinding.issueNumber).toBe(8);
+ });
+});