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: voice-drift check can baseline on style-guide voice exemplars (#2179)
Adam Eivy6e3bff5943ae
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d2253c9fe9..ac27feefff 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -34,6 +34,7 @@- **[issue-2179] A series style guide can now carry concrete voice exemplar and anti-exemplar passages — "the tuning fork" — that get injected into every draft and revision prompt.** Adjective lists ("witty, atmospheric") anchor prose voice far more weakly than an actual passage does, so the series style guide gains two new fields: `voiceExemplars` (1–3 short passages that nail the target voice, each with an optional one-line note on what it demonstrates) and `voiceAntiExemplars` (passages in the wrong register kept as negative examples, noted with what's wrong — "too ornate", "wrong emotional temperature"). Add and edit them inline on the series style-guide editor. On generation they render into the house-style block as a "MATCH this voice — echo their rhythm, diction, and register" block and a "NEVER drift toward this" block — conditional, so a guide with no passages injects nothing. They ride the existing `{{series.styleNotes}}` template variable (via `composeStyleNotes`), so prose drafting, revision, arc planning, and episode-seed passes all honor them with no new prompt-template variable and no migration. The sanitizer drops empty passages, trims each to ~2000 chars, and caps the list at 3 so the fixed per-call prompt overhead stays tight. (First slice of #2179 — the AI-assisted voice-discovery flow, Writers Room parity, and the voice-fingerprint baseline hook ship separately.)- **[issue-2178] Canon can now be reveal-gated so a mystery or twist doesn't leak into the prose before it's due.** Canon context — including character secrets and late-story facts — was injected into every issue's drafting prompt, so the writer model could (and would) spill a reveal issues early. Each canon entry (character, place, or object) now carries optional reveal gating: a `revealIssue` number hides the fact from any issue before it; a `spoiler` flag hard-hides it from all drafting context; and an optional `surfaceDescriptor` is the spoiler-free stand-in shown before the reveal ("the locked east wing" instead of "the wing where the heir is imprisoned"). The drafting/rewrite prompts (`buildStageContext`, the alternate-POV rewrite cast) filter canon to each issue's reveal horizon, while the judge and editorial checks still receive the full canon so they can verify hint placement. Absent gate fields mean "always visible," so every existing canon entry and every federation peer round-trips unchanged. A reveal-timing editor with a spoiler badge lands on every canon-entry card (universe + series). A new `continuity.premature-reveal` editorial check (gated on the series having authored any reveal-gated canon) scans drafted prose for a gated fact stated or unambiguously implied before its reveal issue, distinguishing a genuine leak from deliberate foreshadowing — and its reveal issue feeds the Chekhov setups-payoffs check as an authored payoff so an orphaned reveal is flagged too.- **[issue-2177] Prose drafts now flow across issue boundaries instead of each issue opening and closing in a vacuum.** When drafting an issue's prose, the generator now injects the previous issue's actual closing prose (its last ~2000 characters) and the next issue's opening beats into the draft prompt — with guidance to open so it flows from the previous ending (without repeating its closing image or re-explaining what the reader just read) and to land the ending so it hands off to the next issue's beats. This is what keeps the narrative voice carrying across units and prevents the "every issue opens/closes the same way" tic, improving the autonomous first draft so the editorial loop has less to fix. Both blocks are token-budgeted (they degrade by trimming on a small-context local model rather than erroring), and when the previous issue hasn't been drafted yet — non-linear or parallel generation, or the first issue of a volume — the block simply doesn't render, so there's never any fabricated continuity. Every full prose (re)generation path gets it: the manual draft button, the auto-runner, and Series Autopilot. Existing installs auto-upgrade their prose prompt (a customized prompt is left untouched and flagged).+- **[issue-2179] The voice-drift check can now measure each issue against the voice you CHOSE — its style-guide exemplars — instead of the average of what got drafted.** The `style.voice-drift` check flags an issue whose prose fingerprint sits more than a threshold's σ from a baseline; that baseline used to be the drafted-issue mean, which has a blind spot — if every issue drifted the same way, the average drifts with them and nothing flags. A new **Drift baseline** setting on the check adds two modes on top of the default `drafted`: `exemplars` re-centers every metric on the combined fingerprint of the style guide's voice exemplars (the "tuning fork" passages from the first #2179 slice), and `blended` uses the midpoint of the two. In exemplar/blended mode the spread (σ) is still the drafted corpus's — only the center shifts — so an issue is judged against the chosen voice while still tolerating the series' natural per-metric variance. When the style guide has too little exemplar prose (under ~40 words combined) the run silently falls back to `drafted` and says so. Findings read "…vs the style guide's chosen voice of 5 words" instead of implying drift from the drafted mean, and the deep-linkable **Voice Fingerprint** matrix view renders the chosen-voice baseline as its own footer row with the outlier cells measured against it. The check now also lists the style guide as a source, so editing an exemplar re-stales the finding — exactly like its LLM siblings. (Third slice of #2179 — the voice-fingerprint baseline hook; the AI-assisted voice-discovery flow and Writers Room parity ship separately.) (`server/lib/editorial/voiceFingerprint.js`, `server/lib/editorial/checks/proseStyle.js`, `server/services/pipeline/voiceFingerprint.js`, `client/src/pages/PipelineVoiceFingerprint.jsx`)## Human Activity Trackingdiff --git a/client/src/pages/PipelineVoiceFingerprint.jsx b/client/src/pages/PipelineVoiceFingerprint.jsxindex 7366f9ef55..663d793ea5 100644--- a/client/src/pages/PipelineVoiceFingerprint.jsx+++ b/client/src/pages/PipelineVoiceFingerprint.jsx@@ -67,6 +67,8 @@ export default function PipelineVoiceFingerprint() {const seriesStats = data?.series || {};const outlierSet = new Set((data?.outliers || []).map((o) => outlierKey(o.issue, o.metricKey)));const hasMatrix = issues.length > 0;+ const baselineMode = data?.baselineMode || 'drafted';+ const usesChosenVoice = data?.exemplarBaselineUsed === true;return (<div className="h-full overflow-y-auto p-4 md:p-6">@@ -94,9 +96,13 @@ export default function PipelineVoiceFingerprint() {<p className="text-xs text-gray-500 mb-4 max-w-3xl">Every drafted issue's prose fingerprint. Each column is a metric; a cellhighlighted in <span className="text-port-warning">amber</span> is a- statistical outlier — more than {data?.threshold ?? 1.5}σ from the series- mean on that metric. The bottom rows are the series mean and standard- deviation (σ). This measures the same vectors the deterministic{' '}+ statistical outlier — more than {data?.threshold ?? 1.5}σ from the{' '}+ {usesChosenVoice+ ? "style guide's chosen voice (its voice exemplars)"+ : 'series mean'}{' '}+ on that metric. The bottom rows are the series mean and standard+ deviation (σ){usesChosenVoice ? ', plus the chosen-voice baseline the outliers are measured against' : ''}.+ This measures the same vectors the deterministic{' '}<code className="text-gray-400">style.voice-drift</code> editorial checkflags; it just shows the whole matrix, not only the flagged outliers.</p>@@ -121,6 +127,8 @@ export default function PipelineVoiceFingerprint() {issues={issues}seriesStats={seriesStats}outlierSet={outlierSet}+ baselineMode={baselineMode}+ usesChosenVoice={usesChosenVoice}/><p className="text-xs text-gray-500 mt-3">{issues.length} issue{issues.length === 1 ? '' : 's'} · {columns.length} metrics@@ -155,8 +163,16 @@ function EmptyState({ gatedOff, issueCount, minIssues }) {);}-function FingerprintMatrix({ columns, issues, seriesStats, outlierSet }) {+function FingerprintMatrix({ columns, issues, seriesStats, outlierSet, baselineMode, usesChosenVoice }) {const round2 = (n) => Math.round((Number(n) || 0) * 100) / 100;+ // The baseline an outlier tooltip / footer row names: the chosen voice (or a+ // blend) when the exemplar baseline is active (#2179), else the series mean.+ const centerNoun = usesChosenVoice+ ? (baselineMode === 'blended' ? 'blend of series + chosen voice' : 'chosen voice')+ : 'series mean';+ const centerOf = (col) => (usesChosenVoice+ ? (seriesStats?.[col.key]?.center ?? seriesStats?.[col.key]?.mean)+ : seriesStats?.[col.key]?.mean);// Below minIssues the server gates drift off and returns `series: {}`, so a// mean/σ footer would render misleading 0s — only show it once stats exist.const hasStats = seriesStats && Object.keys(seriesStats).length > 0;@@ -196,7 +212,7 @@ function FingerprintMatrix({ columns, issues, seriesStats, outlierSet }) {? 'bg-port-warning/20 text-port-warning font-semibold': 'text-gray-300'}`}- title={isOutlier ? `Outlier — series mean ${round2(seriesStats?.[col.key]?.mean)}${col.unit || ''}` : undefined}+ title={isOutlier ? `Outlier — ${centerNoun} ${round2(centerOf(col))}${col.unit || ''}` : undefined}>{round2(v)}{col.unit || ''}</td>@@ -223,6 +239,21 @@ function FingerprintMatrix({ columns, issues, seriesStats, outlierSet }) {</td>))}</tr>+ {usesChosenVoice ? (+ <tr className="bg-port-card">+ <td+ className="sticky left-0 z-10 bg-port-card text-port-accent px-3 py-1.5"+ title={`Outliers are measured against this ${centerNoun}, not the drafted mean.`}+ >+ {baselineMode === 'blended' ? 'blend' : 'voice'}+ </td>+ {columns.map((col) => (+ <td key={col.key} className="px-2 py-1.5 text-right text-port-accent tabular-nums">+ {round2(centerOf(col))}{col.unit || ''}+ </td>+ ))}+ </tr>+ ) : null}</tfoot>) : null}</table>diff --git a/client/src/pages/PipelineVoiceFingerprint.test.jsx b/client/src/pages/PipelineVoiceFingerprint.test.jsxindex 0e0f4af8eb..4e9af4eb8f 100644--- a/client/src/pages/PipelineVoiceFingerprint.test.jsx+++ b/client/src/pages/PipelineVoiceFingerprint.test.jsx@@ -87,6 +87,25 @@ describe('PipelineVoiceFingerprint', () => {expect(screen.queryByText('σ')).not.toBeInTheDocument();});+ it('surfaces the chosen-voice baseline row + copy when exemplars mode is active (#2179)', async () => {+ getVoiceFingerprint.mockResolvedValue({+ ...MATRIX_PAYLOAD,+ baselineMode: 'exemplars',+ exemplarBaselineUsed: true,+ series: {+ sentenceLenMean: { mean: 10.5, std: 3, center: 5 },+ dialogueRatio: { mean: 15, std: 8, center: 2 },+ },+ });+ renderAt();+ await waitFor(() => expect(screen.getByText('Voice Fingerprint')).toBeInTheDocument());+ // The intro copy names the chosen-voice baseline instead of the series mean.+ expect(screen.getByText(/chosen voice/)).toBeInTheDocument();+ // A dedicated "voice" baseline footer row renders (label + the centered value).+ expect(screen.getByText('voice')).toBeInTheDocument();+ expect(screen.getByText('5 words')).toBeInTheDocument();+ });+it('renders an empty state when nothing is drafted', async () => {getVoiceFingerprint.mockResolvedValue({...MATRIX_PAYLOAD,diff --git a/server/lib/editorial/checks/proseStyle.js b/server/lib/editorial/checks/proseStyle.jsindex ba648dfd63..de4362ed87 100644--- a/server/lib/editorial/checks/proseStyle.js+++ b/server/lib/editorial/checks/proseStyle.js@@ -38,7 +38,9 @@ import {styleGuideExpectations,z,} from '../checkInfra.js';-import { computeVoiceDrift, describeDrift, parseVoiceWells } from '../voiceFingerprint.js';+import {+ computeVoiceDrift, describeDrift, parseVoiceWells, VOICE_BASELINE_MODES,+} from '../voiceFingerprint.js';export const proseStyleChecks = [{@@ -1005,10 +1007,13 @@ export const proseStyleChecks = [},{id: 'style.voice-drift',- sources: ['manuscript'],+ // Reads the style guide's voice exemplars too (#2179) so an exemplar edit+ // re-stales the finding, exactly as its LLM siblings do — the baseline can be+ // the CHOSEN voice, not just the drafted-issue mean.+ sources: ['manuscript', 'series.styleGuide'],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 below 4 issues drafted — with a tiny series the largest possible σ-distance (√(N−1)) can't reach the default 1.5σ threshold. No LLM cost.",+ "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 baseline, 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. With the \"Drift baseline\" set to exemplars/blended it measures against the style guide's voice-exemplar profile (the CHOSEN voice) instead of the mean of what got drafted — so it flags drift from the voice you picked, not from the average of a corpus that may all have drifted together. Gates off below 4 issues drafted — with a tiny series the largest possible σ-distance (√(N−1)) can't reach the default 1.5σ threshold. No LLM cost.",scope: 'series',kind: 'deterministic',category: 'style',@@ -1032,6 +1037,19 @@ export const proseStyleChecks = [// 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(''),+ // Which baseline each issue's drift is measured against (#2179):+ // drafted — the mean of the drafted issues (default; original behavior).+ // exemplars — the style guide's voice-exemplar profile (the CHOSEN voice),+ // so an issue is flagged for drifting from the voice the author+ // picked, not from the average of what got drafted.+ // blended — the midpoint of the two.+ // Preprocessed: any unrecognized value coerces to 'drafted' so a hand-typed+ // config can't fail the whole check's safeParse (and an exemplars/blended run+ // with no usable exemplars falls back to drafted at compute time anyway).+ baselineMode: z.preprocess(+ (v) => (VOICE_BASELINE_MODES.includes(v) ? v : 'drafted'),+ z.enum(VOICE_BASELINE_MODES),+ ).default('drafted'),}),configFields: [{@@ -1067,6 +1085,12 @@ export const proseStyleChecks = [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.',},+ {+ key: 'baselineMode',+ label: 'Drift baseline',+ type: 'text',+ help: 'What each issue is measured against: "drafted" (the mean of the drafted issues — the default), "exemplars" (the style guide\'s voice-exemplar profile, so drift is judged against the voice you CHOSE, not the average of what got drafted), or "blended" (the midpoint). Exemplars/blended fall back to drafted when the style guide has too little exemplar prose.',+ },],gate: (ctx) => (ctx.manuscript || '').trim().length > 0,run: (ctx) => {@@ -1076,6 +1100,11 @@ export const proseStyleChecks = [threshold: cfg.sigmaThreshold ?? 1.5,minIssues: cfg.minIssues ?? 4,wells,+ // The chosen-voice baseline (#2179): render the drift against the style+ // guide's voice exemplars when configured. A thin/absent exemplar set makes+ // computeVoiceDrift fall back to the drafted mean and report it.+ baselineMode: cfg.baselineMode || 'drafted',+ voiceExemplars: ctx.series?.styleGuide?.voiceExemplars,});if (drift.gatedOff) return [];const cap = cfg.maxFindings ?? 12;diff --git a/server/lib/editorial/voiceFingerprint.js b/server/lib/editorial/voiceFingerprint.jsindex b09b7b0497..217f22e176 100644--- a/server/lib/editorial/voiceFingerprint.js+++ b/server/lib/editorial/voiceFingerprint.js@@ -284,6 +284,52 @@ export function voiceFingerprintMatrix(manuscript, opts = {}) {return { issues, metricKeys, wells: wells.map((w) => w.name) };}+// The three drift-baseline modes (#2179, CWQE Phase 14). Which per-metric CENTER+// each drafted issue's z-score is measured against:+// 'drafted' — the mean of the drafted issues (default; the original behavior).+// 'exemplars' — the style guide's voice EXEMPLARS' combined fingerprint (the+// CHOSEN voice), so an issue is flagged for drifting from the+// voice the author picked, not from the average of what got+// drafted (which itself may all have drifted the same way).+// 'blended' — the midpoint of the two, splitting the difference.+// The spread (σ) is ALWAYS the drafted-issue σ regardless of mode — 1–3 short+// exemplar passages can't yield a meaningful population σ, and "how much this+// series naturally varies per metric" is a property of the drafted corpus. So an+// exemplar/blended run re-centers the target, keeping the drafted spread.+export const VOICE_BASELINE_MODES = Object.freeze(['drafted', 'exemplars', 'blended']);++// A combined exemplar fingerprint needs at least this many words to be a stable+// baseline — a one-line "exemplar" is too thin to center against, so below this+// the baseline is treated as absent (the run falls back to 'drafted').+const MIN_EXEMPLAR_WORDS = 40;++/**+ * Combine a style guide's voice exemplar passages into ONE fingerprint — the+ * statistical profile of the series' CHOSEN voice, used as the drift baseline in+ * `exemplars` / `blended` mode (#2179). Concatenates the passages (they are the+ * same register by construction) and fingerprints the whole, so the metric+ * profile reflects the exemplars' aggregate rhythm/diction. Pure.+ *+ * Returns `null` when there are no usable passages or the combined text is below+ * `MIN_EXEMPLAR_WORDS` (too thin to center against) — callers then fall back to+ * the drafted-mean baseline.+ *+ * @param {Array<{ passage?: string }>} voiceExemplars+ * @param {{ wells?: Array<{ name: string, words: Set<string> }> }} [opts]+ * @returns {{ metrics: Record<string, number>, words: number, passages: number } | null}+ */+export function computeExemplarBaseline(voiceExemplars, opts = {}) {+ const wells = Array.isArray(opts.wells) ? opts.wells : [];+ const passages = (Array.isArray(voiceExemplars) ? voiceExemplars : [])+ .map((e) => (typeof e?.passage === 'string' ? e.passage.trim() : ''))+ .filter(Boolean);+ if (!passages.length) return null;+ const combined = passages.join('\n\n');+ const fp = computeFingerprint(combined, { wells });+ if (fp.words < MIN_EXEMPLAR_WORDS) return null;+ return { metrics: fp.metrics, words: fp.words, passages: passages.length };+}+// Human label for a metric key (static descriptor label, or the well name).export function metricLabel(key) {if (typeof key === 'string' && key.startsWith('well:')) {@@ -339,14 +385,24 @@ export function describeMetricColumn(key) {}// 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").+// the issue value vs the baseline center, the σ distance, and the plain-language+// direction ("prose has gone metronomic"). The baseline label reflects which+// center the outlier was measured against (#2179): the drafted-issue mean, the+// style guide's chosen-voice exemplars, or a blend of the two — so an+// exemplar-baseline finding reads "vs the style guide's chosen voice" instead of+// implying it drifted from the average of what got drafted.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} `+ // `center` is the baseline value; older callers/tests that pass only `mean`+ // still work (center falls back to mean).+ const centerVal = Number.isFinite(o.center) ? o.center : o.mean;+ const center = `${round2(centerVal)}${o.unit || ''}`;+ const baselineNoun = o.baselineMode === 'exemplars'+ ? "the style guide's chosen voice"+ : (o.baselineMode === 'blended' ? "the blend of the series mean and the chosen voice" : 'the series mean');+ return `Issue ${o.issue}'s ${label} is ${val} vs ${baselineNoun} of ${center} `+ `(${Math.abs(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.';}@@ -368,21 +424,44 @@ export function describeDrift(o) {** 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.+ * outlier on a metric when its value is more than `threshold`·σ from the CENTER.* Outliers are sorted by |z| descending so the most significant drift survives a* downstream `maxFindings` cap.*+ * `opts.baselineMode` (#2179) selects what CENTER each issue is measured against:+ * `'drafted'` (default — the drafted-issue mean), `'exemplars'` (the style+ * guide's chosen-voice exemplar profile), or `'blended'` (the midpoint). In the+ * exemplar/blended modes the σ is STILL the drafted-issue σ (see+ * `VOICE_BASELINE_MODES`) — only the center shifts — so an issue is flagged for+ * drifting from the *chosen* voice rather than from the average of what got+ * drafted. When the mode asks for exemplars but `opts.voiceExemplars` yields no+ * usable baseline, the run silently falls back to `'drafted'` and reports the+ * effective mode in `baselineMode` + `exemplarBaselineUsed: false`.+ ** @param {string} manuscript- * @param {{ threshold?: number, minIssues?: number, wells?: Array<{ name: string, words: Set<string> }> }} [opts]+ * @param {{ threshold?: number, minIssues?: number, wells?: Array<{ name: string, words: Set<string> }>,+ * baselineMode?: 'drafted'|'exemplars'|'blended',+ * voiceExemplars?: Array<{ passage?: string }> }} [opts]* @returns {{ gatedOff: boolean, issueCount: number, threshold: number,- * matrix: object, series: Record<string, {mean:number, std:number}>,+ * baselineMode: string, exemplarBaselineUsed: boolean,+ * matrix: object, series: Record<string, {mean:number, std:number, center:number}>,* outliers: Array<{ issue:number, metricKey:string, label:string, value:number,- * mean:number, std:number, z:number, direction:'high'|'low', unit:string }> }}+ * mean:number, center:number, std:number, z:number, direction:'high'|'low',+ * unit:string, baselineMode: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 : 4;- const fullMatrix = voiceFingerprintMatrix(manuscript, { wells: opts.wells });+ const wells = opts.wells;+ const requestedMode = VOICE_BASELINE_MODES.includes(opts.baselineMode) ? opts.baselineMode : 'drafted';+ // Compute the exemplar baseline once (only when a non-drafted mode asked for+ // it). A thin/absent exemplar set → null → fall back to the drafted mean.+ const exemplarBaseline = requestedMode === 'drafted'+ ? null+ : computeExemplarBaseline(opts.voiceExemplars, { wells });+ const effectiveMode = exemplarBaseline ? requestedMode : 'drafted';++ const fullMatrix = voiceFingerprintMatrix(manuscript, { wells });// Drop empty / not-yet-drafted issue sections (a `# Issue N` header with no// prose behind it). Counting them would let a stub satisfy `minIssues` and// inject an all-zero row that pulls the series mean and flags the unwritten@@ -393,8 +472,15 @@ export function computeVoiceDrift(manuscript, opts = {}) {const matrix = { ...fullMatrix, issues };const { metricKeys } = matrix;+ const base = {+ issueCount: issues.length,+ threshold,+ baselineMode: effectiveMode,+ exemplarBaselineUsed: effectiveMode !== 'drafted',+ };+if (issues.length < minIssues) {- return { gatedOff: true, issueCount: issues.length, threshold, matrix, series: {}, outliers: [] };+ return { ...base, gatedOff: true, matrix, series: {}, outliers: [] };}const series = {};@@ -404,13 +490,23 @@ export function computeVoiceDrift(manuscript, opts = {}) {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) };+ // The CENTER each issue's z-score is measured against. Drafted mode centers on+ // the drafted mean; exemplars mode on the chosen-voice profile; blended on the+ // midpoint. The exemplar value for a metric the exemplars don't carry falls+ // back to the drafted mean (never NaN). The σ is always the drafted spread.+ let center = mean;+ if (exemplarBaseline) {+ const exemplarVal = exemplarBaseline.metrics[key];+ const target = Number.isFinite(exemplarVal) ? exemplarVal : mean;+ center = effectiveMode === 'blended' ? (mean + target) / 2 : target;+ }+ series[key] = { mean: round2(mean), std: round2(std), center: round2(center) };// 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;+ const z = (value - center) / std;if (Math.abs(z) <= threshold) continue;outliers.push({issue: it.issue,@@ -418,16 +514,18 @@ export function computeVoiceDrift(manuscript, opts = {}) {label: metricLabel(key),value,mean,+ center,std,z,direction: z > 0 ? 'high' : 'low',unit: metricUnit(key),+ baselineMode: effectiveMode,});}}outliers.sort((a, b) => Math.abs(b.z) - Math.abs(a.z));- return { gatedOff: false, issueCount: issues.length, threshold, matrix, series, outliers };+ return { ...base, gatedOff: false, matrix, series, outliers };}/**@@ -454,6 +552,13 @@ export function renderFingerprintTable(drift) {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}`)]);+ // When drift was measured against a non-drafted baseline (exemplars/blended),+ // the flagged cells sit against `center`, not `mean` — surface it as its own+ // row so the starred outliers are readable against the actual baseline.+ if (drift.exemplarBaselineUsed) {+ const label = drift.baselineMode === 'blended' ? 'blend' : 'voice';+ rows.push([label, ...keys.map((k) => `${series[k]?.center ?? series[k]?.mean ?? 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();diff --git a/server/lib/editorial/voiceFingerprint.test.js b/server/lib/editorial/voiceFingerprint.test.jsindex c56e18f2d9..b842192dd0 100644--- a/server/lib/editorial/voiceFingerprint.test.js+++ b/server/lib/editorial/voiceFingerprint.test.js@@ -1,8 +1,10 @@import { describe, it, expect } from 'vitest';import {VOICE_METRICS,+ VOICE_BASELINE_MODES,parseVoiceWells,computeFingerprint,+ computeExemplarBaseline,splitManuscriptByIssue,voiceFingerprintMatrix,computeVoiceDrift,@@ -225,6 +227,130 @@ describe('computeVoiceDrift', () => {});});+describe('computeExemplarBaseline (#2179)', () => {+ it('combines exemplar passages into one fingerprint', () => {+ // Two passages, each 4 sentences of 8 words → combined mean 8 words/sentence.+ const exemplars = [+ { passage: issueBlock(4, 8), note: 'spare, clipped' },+ { passage: issueBlock(4, 8) },+ ];+ const baseline = computeExemplarBaseline(exemplars);+ expect(baseline).toBeTruthy();+ expect(baseline.passages).toBe(2);+ expect(baseline.metrics.sentenceLenMean).toBe(8);+ expect(baseline.words).toBeGreaterThanOrEqual(40);+ });++ it('returns null for no usable passages', () => {+ expect(computeExemplarBaseline(null)).toBeNull();+ expect(computeExemplarBaseline([])).toBeNull();+ expect(computeExemplarBaseline([{ note: 'no passage' }, { passage: ' ' }])).toBeNull();+ });++ it('returns null when the combined text is below the min-word floor', () => {+ // A single short passage (< 40 words) is too thin to center against.+ expect(computeExemplarBaseline([{ passage: issueBlock(1, 5) }])).toBeNull();+ });++ it('honors configured wells', () => {+ const wells = parseVoiceWells('trade: forge');+ const baseline = computeExemplarBaseline(+ [{ passage: 'the forge burned bright and hot today '.repeat(8) }], // 56 words, ≥ floor+ { wells },+ );+ expect(baseline).toBeTruthy();+ expect(baseline.metrics['well:trade']).toBeGreaterThan(0);+ });+});++describe('computeVoiceDrift baseline modes (#2179)', () => {+ // Four drafted issues that all share a sentence-length mean of 20 words — so the+ // drafted mean is 20 and the drafted σ on that metric is 0 (no drafted-mode+ // drift possible). The style-guide exemplars establish a much SHORTER chosen+ // voice (mean 5), so every drafted issue is far from the chosen voice.+ const draftedUniform = manuscriptOf([issueBlock(4, 20), issueBlock(4, 20), issueBlock(4, 20), issueBlock(4, 20)]);+ // Give the fragment metric some drafted spread so σ is non-zero and an exemplar+ // re-center can actually flag: issues vary their fragment counts.+ const draftedSpread = manuscriptOf([+ `${issueBlock(3, 20)} ${issueBlock(1, 3)}`,+ `${issueBlock(3, 20)} ${issueBlock(2, 3)}`,+ `${issueBlock(3, 20)} ${issueBlock(1, 3)}`,+ `${issueBlock(3, 20)} ${issueBlock(6, 3)}`,+ ]);+ const shortExemplars = [+ { passage: issueBlock(6, 5), note: 'spare' },+ { passage: issueBlock(6, 5) },+ ];++ it('drafted mode is the default and ignores exemplars', () => {+ const drift = computeVoiceDrift(draftedUniform, { voiceExemplars: shortExemplars });+ expect(drift.baselineMode).toBe('drafted');+ expect(drift.exemplarBaselineUsed).toBe(false);+ // sentence-length σ is 0 across identical issues → no outlier on that metric.+ expect(drift.outliers.some((o) => o.metricKey === 'sentenceLenMean')).toBe(false);+ });++ it('exemplars mode re-centers on the chosen voice and reports it', () => {+ const drift = computeVoiceDrift(draftedSpread, {+ baselineMode: 'exemplars',+ voiceExemplars: shortExemplars,+ });+ expect(drift.baselineMode).toBe('exemplars');+ expect(drift.exemplarBaselineUsed).toBe(true);+ // The chosen-voice sentence-length mean (~5) is the center, not the drafted+ // mean (~15.75); every drafted issue sits well above it.+ expect(drift.series.sentenceLenMean.center).toBeCloseTo(5, 1);+ expect(drift.series.sentenceLenMean.mean).toBeGreaterThan(10);+ const meanOutliers = drift.outliers.filter((o) => o.metricKey === 'sentenceLenMean');+ expect(meanOutliers.length).toBeGreaterThan(0);+ expect(meanOutliers.every((o) => o.direction === 'high')).toBe(true);+ expect(meanOutliers.every((o) => o.baselineMode === 'exemplars')).toBe(true);+ });++ it('blended mode centers on the midpoint of drafted mean and chosen voice', () => {+ const drift = computeVoiceDrift(draftedSpread, {+ baselineMode: 'blended',+ voiceExemplars: shortExemplars,+ });+ expect(drift.baselineMode).toBe('blended');+ const s = drift.series.sentenceLenMean;+ // center = (draftedMean + exemplarMean) / 2.+ expect(s.center).toBeCloseTo((s.mean + 5) / 2, 1);+ });++ it('falls back to drafted when the exemplar set is too thin', () => {+ const drift = computeVoiceDrift(draftedSpread, {+ baselineMode: 'exemplars',+ voiceExemplars: [{ passage: issueBlock(1, 4) }], // < 40 words+ });+ expect(drift.baselineMode).toBe('drafted');+ expect(drift.exemplarBaselineUsed).toBe(false);+ });++ it('falls back to drafted when no exemplars are provided', () => {+ const drift = computeVoiceDrift(draftedSpread, { baselineMode: 'exemplars' });+ expect(drift.baselineMode).toBe('drafted');+ expect(drift.exemplarBaselineUsed).toBe(false);+ });++ it('coerces an unrecognized baselineMode to drafted', () => {+ const drift = computeVoiceDrift(draftedSpread, { baselineMode: 'nonsense', voiceExemplars: shortExemplars });+ expect(drift.baselineMode).toBe('drafted');+ });++ it('exposes the three valid modes', () => {+ expect(VOICE_BASELINE_MODES).toEqual(['drafted', 'exemplars', 'blended']);+ });++ it('gates off below minIssues regardless of baseline mode', () => {+ const ms = manuscriptOf([issueBlock(3, 20), issueBlock(3, 20)]);+ const drift = computeVoiceDrift(ms, { baselineMode: 'exemplars', voiceExemplars: shortExemplars });+ expect(drift.gatedOff).toBe(true);+ // Effective mode is still reported so the UI can label the (empty) run.+ expect(drift.baselineMode).toBe('exemplars');+ });+});+describe('describeDrift + renderFingerprintTable', () => {it('describeDrift names the issue, values, σ, and direction', () => {const o = {@@ -235,10 +361,23 @@ describe('describeDrift + renderFingerprintTable', () => {expect(text).toContain('Issue 7');expect(text).toContain('0.18');expect(text).toContain('0.41');+ expect(text).toContain('the series mean'); // default (drafted) baseline nounexpect(text).toContain('metronomic'); // the "lower" phrase for CVexpect(text).toContain('below');});+ it('describeDrift labels the baseline as the chosen voice in exemplars mode (#2179)', () => {+ const o = {+ issue: 7, metricKey: 'sentenceLenMean', label: 'sentence-length mean',+ value: 20, mean: 15, center: 5, std: 4, z: 3.75, direction: 'high', unit: ' words',+ baselineMode: 'exemplars',+ };+ const text = describeDrift(o);+ expect(text).toContain("the style guide's chosen voice");+ expect(text).toContain('5 words'); // the center, not the drafted mean of 15+ expect(text).not.toContain('the series mean of');+ });+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);@@ -256,10 +395,10 @@ describe('describeDrift + renderFingerprintTable', () => {});describe('style.voice-drift check (registry wiring)', () => {- const runCheck = (ms, config = {}, severityDefault = 'low') => {+ const runCheck = (ms, config = {}, severityDefault = 'low', series = undefined) => {const check = getCheck('style.voice-drift');expect(check).toBeTruthy();- return check.run({ manuscript: ms, config, severityDefault });+ return check.run({ manuscript: ms, config, severityDefault, series });};it('is registered as a deterministic series check', () => {@@ -269,6 +408,32 @@ describe('style.voice-drift check (registry wiring)', () => {expect(check.needsManuscript).toBe(true);});+ it('declares series.styleGuide as a source so exemplar edits re-stale it (#2179)', () => {+ const check = getCheck('style.voice-drift');+ expect(check.sources).toContain('series.styleGuide');+ // The config schema advertises the baselineMode field.+ const parsed = check.configSchema.parse({ baselineMode: 'exemplars' });+ expect(parsed.baselineMode).toBe('exemplars');+ // An unrecognized value is coerced to drafted rather than failing the parse.+ expect(check.configSchema.parse({ baselineMode: 'bogus' }).baselineMode).toBe('drafted');+ });++ it('measures against the style guide voice exemplars when configured (#2179)', () => {+ // Drafted issues cluster tightly at a long sentence-length mean (14/15/15/16+ // words → drafted σ ≈ 0.71, so the biggest drafted-mode z ≈ 1.41 < 1.5 → no+ // drafted flag). The chosen voice is much shorter (mean 5), so against the+ // exemplar baseline every drafted issue is a wild outlier the drafted mean hid.+ const ms = manuscriptOf([issueBlock(4, 14), issueBlock(4, 15), issueBlock(4, 15), issueBlock(4, 16)]);+ const series = { styleGuide: { voiceExemplars: [{ passage: issueBlock(6, 5) }, { passage: issueBlock(6, 5) }] } };+ const drafted = runCheck(ms, { baselineMode: 'drafted' }, 'low', series);+ const exemplars = runCheck(ms, { baselineMode: 'exemplars' }, 'low', series);+ // The exemplar baseline surfaces sentence-length drift the drafted mean hides.+ expect(drafted.some((f) => f.problem.includes('sentence-length mean'))).toBe(false);+ const meanFinding = exemplars.find((f) => f.problem.includes('sentence-length mean'));+ expect(meanFinding).toBeTruthy();+ expect(meanFinding.problem).toContain("the style guide's chosen voice");+ });+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);diff --git a/server/services/pipeline/voiceFingerprint.js b/server/services/pipeline/voiceFingerprint.jsindex 992e613b2d..3e9ab5bc19 100644--- a/server/services/pipeline/voiceFingerprint.js+++ b/server/services/pipeline/voiceFingerprint.js@@ -44,7 +44,7 @@ export const VOICE_DRIFT_CHECK_ID = 'style.voice-drift';* (`style.voice-drift` is statically registered, so `getCheckById` never misses.)** @param {object} [settings] pre-loaded settings (optional; fetched when omitted)- * @returns {Promise<{ sigmaThreshold: number, minIssues: number, vocabularyWells: string, maxFindings: number }>}+ * @returns {Promise<{ sigmaThreshold: number, minIssues: number, vocabularyWells: string, maxFindings: number, baselineMode: string }>}*/export async function resolveVoiceDriftConfig(settings) {const s = settings || await getSettings();@@ -68,6 +68,8 @@ export async function resolveVoiceDriftConfig(settings) {* gatedOff: boolean,* issueCount: number,* threshold: number,+ * baselineMode: string,+ * exemplarBaselineUsed: boolean,* matrix: object,* series: object,* outliers: object[],@@ -75,20 +77,25 @@ export async function resolveVoiceDriftConfig(settings) {*/export async function getVoiceFingerprint(seriesId) {// Throws when the series is missing — the route maps it to a 404. Runs before any- // manuscript I/O so a bad id fails fast.- await getSeries(seriesId);+ // manuscript I/O so a bad id fails fast. Keep the loaded record: the drift baseline+ // can be the style guide's chosen-voice exemplars (#2179).+ const series = await getSeries(seriesId);const [sections, cfg] = await Promise.all([collectManuscriptSections(seriesId),resolveVoiceDriftConfig(),]);- // `cfg` is schema-validated, so sigmaThreshold/minIssues/vocabularyWells are- // always present (defaults applied by resolveCheckConfig) — no `??` needed.+ // `cfg` is schema-validated, so sigmaThreshold/minIssues/vocabularyWells/baselineMode+ // are always present (defaults applied by resolveCheckConfig) — no `??` needed. The+ // matrix view resolves the SAME config the finding-emitting run does, including the+ // chosen-voice baseline, so the highlighted outliers agree with the editor's findings.const drift = computeVoiceDrift(sectionsCorpus(sections), {threshold: cfg.sigmaThreshold,minIssues: cfg.minIssues,wells: parseVoiceWells(cfg.vocabularyWells),+ baselineMode: cfg.baselineMode,+ voiceExemplars: series?.styleGuide?.voiceExemplars,});return {@@ -99,6 +106,8 @@ export async function getVoiceFingerprint(seriesId) {gatedOff: drift.gatedOff,issueCount: drift.issueCount,threshold: drift.threshold,+ baselineMode: drift.baselineMode,+ exemplarBaselineUsed: drift.exemplarBaselineUsed,matrix: drift.matrix,series: drift.series,outliers: drift.outliers,diff --git a/server/services/pipeline/voiceFingerprint.test.js b/server/services/pipeline/voiceFingerprint.test.jsindex 1b9c0b7a5f..374d51c58f 100644--- a/server/services/pipeline/voiceFingerprint.test.js+++ b/server/services/pipeline/voiceFingerprint.test.js@@ -19,10 +19,11 @@ function buildManuscript() {let settingsStore = {};let manuscriptCorpus = buildManuscript();+let seriesStyleGuide = null;vi.mock('./series.js', () => ({getSeries: vi.fn(async (id) => {if (id === 'missing') throw Object.assign(new Error('nope'), { code: 'PIPELINE_SERIES_NOT_FOUND' });- return { id, name: 'Test Series' };+ return { id, name: 'Test Series', styleGuide: seriesStyleGuide };}),}));@@ -40,6 +41,7 @@ const { getVoiceFingerprint, resolveVoiceDriftConfig, VOICE_DRIFT_CHECK_ID } = abeforeEach(() => {settingsStore = {};manuscriptCorpus = buildManuscript();+ seriesStyleGuide = null;});describe('resolveVoiceDriftConfig', () => {@@ -48,6 +50,7 @@ describe('resolveVoiceDriftConfig', () => {expect(cfg.sigmaThreshold).toBe(1.5);expect(cfg.minIssues).toBe(4);expect(cfg.vocabularyWells).toBe('');+ expect(cfg.baselineMode).toBe('drafted');});it('reads the persisted per-check config slice', async () => {@@ -127,4 +130,41 @@ describe('getVoiceFingerprint', () => {it('propagates a NOT_FOUND error for a missing series', async () => {await expect(getVoiceFingerprint('missing')).rejects.toMatchObject({ code: 'PIPELINE_SERIES_NOT_FOUND' });});++ it('drafted baseline is the default and reports it (#2179)', async () => {+ const res = await getVoiceFingerprint('ser-1');+ expect(res.baselineMode).toBe('drafted');+ expect(res.exemplarBaselineUsed).toBe(false);+ });++ it('measures against the style guide chosen voice when configured (#2179)', async () => {+ settingsStore = {+ pipelineEditorialChecks: {+ checks: { [VOICE_DRIFT_CHECK_ID]: { config: { baselineMode: 'exemplars' } } },+ },+ };+ // A metronomic chosen voice — so the VARIED issues drift against it.+ seriesStyleGuide = { voiceExemplars: [{ passage: METRONOMIC }, { passage: METRONOMIC }] };+ const res = await getVoiceFingerprint('ser-1');+ expect(res.baselineMode).toBe('exemplars');+ expect(res.exemplarBaselineUsed).toBe(true);+ // The center row differs from the drafted mean on at least one metric.+ const shifted = res.columns.some((c) => {+ const s = res.series[c.key];+ return s && Number.isFinite(s.center) && Math.abs(s.center - s.mean) > 1e-6;+ });+ expect(shifted).toBe(true);+ });++ it('falls back to drafted when configured for exemplars but the style guide has none (#2179)', async () => {+ settingsStore = {+ pipelineEditorialChecks: {+ checks: { [VOICE_DRIFT_CHECK_ID]: { config: { baselineMode: 'exemplars' } } },+ },+ };+ seriesStyleGuide = { voiceExemplars: [] };+ const res = await getVoiceFingerprint('ser-1');+ expect(res.baselineMode).toBe('drafted');+ expect(res.exemplarBaselineUsed).toBe(false);+ });});