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: series-level voice-drift finding for uniformly off-register corpus (#2248)
Adam Eivye043ceccd205
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex ac27feefff..57b4e7eec9 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -35,6 +35,7 @@- **[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`)+- **[issue-2248] The chosen-voice baseline now also catches drift the whole series shares — not just per-issue outliers.** The exemplar/blended `style.voice-drift` baseline (#2247) flags an issue that stands apart from the chosen voice, but it had a residual blind spot: when *every* drafted issue sits at the same value on a metric (zero spread) yet that shared value is far from the chosen voice, there is no per-issue outlier to name — the whole corpus is uniformly off-register. The classic case is a dialogue-free series measured against a dialogue-heavy chosen voice: every issue's dialogue ratio is 0, so the per-issue z-score model stays silent even though the register is plainly wrong. The check now emits a distinct **series-wide** finding for exactly this case ("The whole series sits at 0% on dialogue ratio vs the style guide's chosen voice of 42.5% — the corpus is uniformly below the chosen voice here"), gated on a scale-free relative distance so it works across metrics with wildly different scales and never fires under the default `drafted` baseline (where the center is the mean by definition). Series-wide findings carry no issue number (it's a corpus-wide observation, not an outlier) and escalate one severity rank above the per-issue floor, and the **Voice Fingerprint** matrix view surfaces them as a banner above the table since they have no single cell to highlight. (Follow-up slice of #2179.) (`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 9fa230488b..4696bfcce4 100644--- a/client/src/pages/PipelineVoiceFingerprint.jsx+++ b/client/src/pages/PipelineVoiceFingerprint.jsx@@ -25,6 +25,9 @@ import { getPipelineSeries, getVoiceFingerprint } from '../services/api';// A cell is an outlier when the (issue, metricKey) pair is in the drift set.// Keyed on `issue:metricKey` so a lookup is O(1) while rendering the grid.const outlierKey = (issue, metricKey) => `${issue}:${metricKey}`;+// Round a metric value to 2dp for display (the matrix cells + the seriesFindings+// banner, which carries the raw mean/center).+const round2 = (n) => Math.round((Number(n) || 0) * 100) / 100;export default function PipelineVoiceFingerprint() {const { seriesId } = useParams();@@ -66,6 +69,10 @@ export default function PipelineVoiceFingerprint() {const issues = data?.matrix?.issues || [];const seriesStats = data?.series || {};const outlierSet = new Set((data?.outliers || []).map((o) => outlierKey(o.issue, o.metricKey)));+ // #2248 — series-wide "the whole corpus is uniformly off the chosen voice"+ // findings. These have no single cell to highlight (the column is uniform), so+ // they surface as a banner above the matrix rather than an amber cell.+ const seriesFindings = data?.seriesFindings || [];const hasMatrix = issues.length > 0;const baselineMode = data?.baselineMode || 'drafted';// Only claim the chosen-voice baseline once it was actually applied: a gatedOff@@ -131,6 +138,25 @@ export default function PipelineVoiceFingerprint() {</span></div>) : null}+ {seriesFindings.length ? (+ <div className="mb-4 rounded-lg border border-port-warning/40 bg-port-warning/10 px-3 py-2 text-sm">+ <div className="flex items-center gap-2 text-port-warning font-medium mb-1">+ <Info size={14} className="shrink-0" />+ {seriesFindings.length} series-wide voice mismatch+ {seriesFindings.length === 1 ? '' : 'es'}+ </div>+ <ul className="space-y-1 text-gray-300">+ {seriesFindings.map((f) => (+ <li key={f.metricKey}>+ The whole series sits at {round2(f.mean)}{f.unit || ''} on{' '}+ <span className="text-white">{f.label}</span> vs the chosen voice's{' '}+ {round2(f.center)}{f.unit || ''} — uniformly {f.direction === 'high' ? 'above' : 'below'} the+ chosen voice (no single issue is an outlier).+ </li>+ ))}+ </ul>+ </div>+ ) : null}<FingerprintMatrixcolumns={columns}issues={issues}@@ -173,7 +199,6 @@ function EmptyState({ gatedOff, issueCount, minIssues }) {}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 = usesChosenVoicediff --git a/client/src/pages/PipelineVoiceFingerprint.test.jsx b/client/src/pages/PipelineVoiceFingerprint.test.jsxindex daf4034f4b..11f9e4faeb 100644--- a/client/src/pages/PipelineVoiceFingerprint.test.jsx+++ b/client/src/pages/PipelineVoiceFingerprint.test.jsx@@ -144,6 +144,35 @@ describe('PipelineVoiceFingerprint', () => {expect(screen.queryByText('voice')).not.toBeInTheDocument();});+ it('surfaces a series-wide mismatch banner for seriesFindings (#2248)', async () => {+ getVoiceFingerprint.mockResolvedValue({+ ...MATRIX_PAYLOAD,+ baselineMode: 'exemplars',+ exemplarBaselineUsed: true,+ series: {+ sentenceLenMean: { mean: 10.5, std: 3, center: 5 },+ dialogueRatio: { mean: 0, std: 0, center: 42.5 },+ },+ seriesFindings: [+ { metricKey: 'dialogueRatio', label: 'dialogue ratio', mean: 0, center: 42.5, std: 0, distance: 1, direction: 'low', unit: '%', baselineMode: 'exemplars' },+ ],+ });+ renderAt();+ await waitFor(() => expect(screen.getByText('Voice Fingerprint')).toBeInTheDocument());+ expect(screen.getByText(/series-wide voice mismatch/)).toBeInTheDocument();+ // The banner names the corpus value and the metric (the chosen-voice center+ // 42.5% also appears in the matrix footer row, so it's not banner-unique).+ expect(screen.getByText(/sits at 0% on/)).toBeInTheDocument();+ expect(screen.getByText(/uniformly below the/)).toBeInTheDocument();+ });++ it('renders no series-wide banner when seriesFindings is empty', async () => {+ getVoiceFingerprint.mockResolvedValue(MATRIX_PAYLOAD);+ renderAt();+ await waitFor(() => expect(screen.getByText('Voice Fingerprint')).toBeInTheDocument());+ expect(screen.queryByText(/series-wide voice mismatch/)).not.toBeInTheDocument();+ });+it('renders an empty state when nothing is drafted', async () => {getVoiceFingerprint.mockResolvedValue({...MATRIX_PAYLOAD,diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.mdindex 1cdca2c05b..201c7993bf 100644--- a/server/lib/editorial/README.md+++ b/server/lib/editorial/README.md@@ -202,7 +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); `describeMetricColumn(key)` / `metricUnit(key)` give the self-describing column header (label/unit/higher/lower/isWell) shared by the finding text and the deep-linkable matrix view (#2194). `VOICE_METRICS` is the static metric descriptor list. |+| `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`), and — under an exemplar/blended baseline (#2248) — emits a `seriesFindings[]` of series-level "the whole corpus is uniformly off the chosen voice" mismatches for metrics whose drafted σ≈0 but whose shared value sits a scale-free relative distance from the chosen-voice center; `parseVoiceWells` parses the `name: word, word; …` config spec; `describeDrift` renders a per-issue finding sentence and `describeSeriesDrift` the series-level one; `renderFingerprintTable` renders the issues×metrics matrix (outliers marked); `describeMetricColumn(key)` / `metricUnit(key)` give the self-describing column header (label/unit/higher/lower/isWell) shared by the finding text and the deep-linkable matrix view (#2194). `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/checks/proseStyle.js b/server/lib/editorial/checks/proseStyle.jsindex de4362ed87..e7bb474883 100644--- a/server/lib/editorial/checks/proseStyle.js+++ b/server/lib/editorial/checks/proseStyle.js@@ -39,7 +39,7 @@ import {z,} from '../checkInfra.js';import {- computeVoiceDrift, describeDrift, parseVoiceWells, VOICE_BASELINE_MODES,+ computeVoiceDrift, describeDrift, describeSeriesDrift, parseVoiceWells, VOICE_BASELINE_MODES,} from '../voiceFingerprint.js';export const proseStyleChecks = [@@ -1108,7 +1108,7 @@ export const proseStyleChecks = [});if (drift.gatedOff) return [];const cap = cfg.maxFindings ?? 12;- return drift.outliers.slice(0, cap).map((o) => ({+ const perIssue = 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),@@ -1122,6 +1122,26 @@ export const proseStyleChecks = [anchorQuote: null,issueNumber: o.issue,}));+ // #2248 — series-level "the WHOLE corpus is uniformly off the chosen voice"+ // findings (only under an exemplar/blended baseline). These have no+ // issueNumber (a series-wide register mismatch, not a per-issue outlier) and+ // escalate one rank above the low floor because a corpus-wide mismatch is a+ // stronger signal than a single-issue wobble. They share the maxFindings cap+ // with the per-issue outliers, listed first so a series-wide finding is never+ // starved out by a flood of per-issue ones.+ const seriesLevel = (drift.seriesFindings || []).map((o) => ({+ severity: escalateSeverity(ctx.severityDefault, 1),+ category: 'style',+ location: `Series-wide — narrative voice (${o.label})`,+ problem: describeSeriesDrift(o),+ suggestion:+ `The whole series sits off the chosen voice on its ${o.label}. `+ + 'Revise toward the chosen voice across the run, or update the style guide\'s voice '+ + 'exemplars if this uniform register IS the voice you want.',+ anchorQuote: null,+ issueNumber: null,+ }));+ return [...seriesLevel, ...perIssue].slice(0, cap);},},{diff --git a/server/lib/editorial/voiceFingerprint.js b/server/lib/editorial/voiceFingerprint.jsindex 3eadc412cd..cc57e90130 100644--- a/server/lib/editorial/voiceFingerprint.js+++ b/server/lib/editorial/voiceFingerprint.js@@ -303,6 +303,23 @@ export const VOICE_BASELINE_MODES = Object.freeze(['drafted', 'exemplars', 'blen// the baseline is treated as absent (the run falls back to 'drafted').const MIN_EXEMPLAR_WORDS = 40;+// Default relative-distance threshold for the SERIES-level "uniformly off the+// chosen voice" finding (#2248): the whole drafted corpus sits at ~one value on a+// metric (σ≈0) while the exemplar/blended center sits far away. Because the metric+// vector mixes wildly different scales (dialogueRatio 0–100, sentence-length CV+// ~0.4, em-dash rate per-1k), a single ABSOLUTE gap threshold is meaningless — so+// the finding gates on a SCALE-FREE relative distance `|center − mean| /+// max(|center|, |mean|)` in [0, 1]. 0.5 means "the corpus and the chosen voice are+// at least half apart on this metric's own scale" — the dialogue-free-series-vs-+// dialogue-heavy-voice example (mean 0 vs center 30) has distance 1.0 and flags+// hard, while a small uniform offset stays quiet.+const SERIES_DRIFT_DISTANCE = 0.5;+// Absolute floor so a metric where BOTH the corpus mean and the chosen-voice+// center round to ~0 can't manufacture a large relative distance from rounding+// noise (e.g. 0.0 vs 0.1 → relative 1.0). Below this |center − mean| gap the+// series-level finding is suppressed regardless of relative distance.+const SERIES_DRIFT_MIN_GAP = 1e-6;+/*** 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@@ -407,6 +424,27 @@ export function describeDrift(o) {+ 'A statistical outlier against the series voice; confirm it is an earned modulation, not drift.';}+// One-sentence finding text for a SERIES-LEVEL drift (#2248) — the whole drafted+// corpus sits uniformly at one value on a metric (σ≈0) that is far from the CHOSEN+// voice's center, so there is no per-issue outlier to name. Reads "the whole+// series sits at X vs the chosen voice's Y — <direction phrase>", explicitly a+// corpus-wide observation, not an issue outlier. Only meaningful under an+// exemplar/blended baseline (in drafted mode center===mean, so nothing flags).+export function describeSeriesDrift(o) {+ const label = metricLabel(o.metricKey);+ const dir = directionPhrase(o.metricKey, o.direction);+ const unit = o.unit || '';+ const val = `${round2(o.mean)}${unit}`;+ const center = `${round2(o.center)}${unit}`;+ const baselineNoun = o.baselineMode === 'blended'+ ? 'the blend of the series mean and the chosen voice'+ : "the style guide's chosen voice";+ return `The whole series sits at ${val} on ${label} vs ${baselineNoun} of ${center} `+ + `— the corpus is uniformly ${o.direction === 'high' ? 'above' : 'below'} the chosen voice here (${dir}). `+ + 'Not a per-issue outlier but a series-wide register mismatch; revise toward the chosen voice across the run, '+ + 'or update the voice exemplars if this IS the voice you want.';+}+/*** Compute the voice-drift outliers for a stitched manuscript. Pure — returns* structured results the `style.voice-drift` check maps to editorial findings (so@@ -438,20 +476,33 @@ export function describeDrift(o) {* usable baseline, the run silently falls back to `'drafted'` and reports the* effective mode in `baselineMode` + `exemplarBaselineUsed: false`.*+ * `seriesFindings` (#2248) covers the boundary the per-issue z-score model can't:+ * under an exemplar/blended baseline, when EVERY drafted issue shares the same+ * value on a metric (σ≈0) but that shared value sits far from the chosen-voice+ * center, there is no per-issue outlier — the whole corpus is uniformly+ * off-register. Each such metric emits ONE series-level finding (no `issue`),+ * gated on a scale-free relative distance ≥ `opts.seriesDistanceThreshold`.+ ** @param {string} manuscript* @param {{ threshold?: number, minIssues?: number, wells?: Array<{ name: string, words: Set<string> }>,* baselineMode?: 'drafted'|'exemplars'|'blended',+ * seriesDistanceThreshold?: number,* voiceExemplars?: Array<{ passage?: string }> }} [opts]* @returns {{ gatedOff: boolean, issueCount: number, threshold: 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, center:number, std:number, z:number, direction:'high'|'low',- * unit:string, baselineMode:string }> }}+ * unit:string, baselineMode:string }>,+ * seriesFindings: Array<{ metricKey:string, label:string, mean:number, center:number,+ * distance: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 seriesDistanceThreshold = Number.isFinite(opts.seriesDistanceThreshold) && opts.seriesDistanceThreshold > 0+ ? opts.seriesDistanceThreshold+ : SERIES_DRIFT_DISTANCE;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@@ -480,11 +531,14 @@ export function computeVoiceDrift(manuscript, opts = {}) {};if (issues.length < minIssues) {- return { ...base, gatedOff: true, matrix, series: {}, outliers: [] };+ return { ...base, gatedOff: true, matrix, series: {}, outliers: [], seriesFindings: [] };}const series = {};const outliers = [];+ // #2248 — series-level "uniformly off the chosen voice" findings (only ever+ // populated under an active exemplar/blended baseline; see the skip-site branch).+ const seriesFindings = [];for (const key of metricKeys) {const values = issues.map((it) => it.metrics[key] ?? 0);@@ -502,17 +556,38 @@ export function computeVoiceDrift(manuscript, opts = {}) {}series[key] = { mean: round2(mean), std: round2(std), center: round2(center) };// A metric with no drafted spread can't have a per-issue OUTLIER — and dividing- // by ~0 σ would manufacture infinite z-scores — so skip it. Note the boundary- // this leaves for the exemplar/blended baseline (#2179): when every drafted- // issue shares the SAME value on a metric (σ≈0) but that shared value sits far- // from the chosen-voice center, this per-issue z-score model emits nothing —- // there's no per-issue outlier, the whole corpus is uniformly off. That- // "uniformly-off-register" case wants a SERIES-level finding (a different shape- // than the per-issue outliers here), tracked as a #2179 follow-up. It does NOT- // affect the common case the feature targets: issues that drifted the same- // DIRECTION still have natural per-metric variance (σ>0), so they still flag- // against the chosen-voice center.- if (std < 1e-9) continue;+ // by ~0 σ would manufacture infinite z-scores — so skip the per-issue pass.+ // But (#2248) under an exemplar/blended baseline this σ≈0 case is exactly the+ // "uniformly off the chosen voice" boundary: every drafted issue shares the+ // SAME value on a metric, yet that shared value can sit far from the+ // chosen-voice center (e.g. a dialogue-free series vs a dialogue-heavy voice).+ // There's no per-issue outlier, but the whole corpus is off-register — so emit+ // ONE series-level finding (a different shape: no `issue`), gated on a+ // scale-free relative distance so it works across the metric vector's very+ // different scales. Drafted mode never trips this (center === mean → gap 0).+ // The common case the #2179 feature targets is untouched: issues that drifted+ // the same DIRECTION still have natural per-metric variance (σ>0), so they flag+ // per-issue below against the chosen-voice center.+ if (std < 1e-9) {+ if (exemplarBaseline) {+ const gap = Math.abs(center - mean);+ const denom = Math.max(Math.abs(center), Math.abs(mean));+ const distance = denom > 0 ? gap / denom : 0;+ if (gap >= SERIES_DRIFT_MIN_GAP && distance >= seriesDistanceThreshold) {+ seriesFindings.push({+ metricKey: key,+ label: metricLabel(key),+ mean,+ center,+ distance,+ direction: mean > center ? 'high' : 'low',+ unit: metricUnit(key),+ baselineMode: effectiveMode,+ });+ }+ }+ continue;+ }for (const it of issues) {const value = it.metrics[key] ?? 0;const z = (value - center) / std;@@ -534,7 +609,9 @@ export function computeVoiceDrift(manuscript, opts = {}) {}outliers.sort((a, b) => Math.abs(b.z) - Math.abs(a.z));- return { ...base, gatedOff: false, matrix, series, outliers };+ // Most-off-register first, so a downstream cap keeps the worst mismatches.+ seriesFindings.sort((a, b) => b.distance - a.distance);+ return { ...base, gatedOff: false, matrix, series, outliers, seriesFindings };}/**diff --git a/server/lib/editorial/voiceFingerprint.test.js b/server/lib/editorial/voiceFingerprint.test.jsindex b842192dd0..16e03e6a9b 100644--- a/server/lib/editorial/voiceFingerprint.test.js+++ b/server/lib/editorial/voiceFingerprint.test.js@@ -9,6 +9,7 @@ import {voiceFingerprintMatrix,computeVoiceDrift,describeDrift,+ describeSeriesDrift,renderFingerprintTable,metricLabel,} from './voiceFingerprint.js';@@ -351,6 +352,114 @@ describe('computeVoiceDrift baseline modes (#2179)', () => {});});+describe('computeVoiceDrift series-level findings (#2248)', () => {+ // Four IDENTICAL dialogue-free issues → σ≈0 on every metric, so the per-issue+ // z-score model emits no outlier. dialogueRatio is 0 on every issue.+ const dialogueFree = manuscriptOf([issueBlock(4, 20), issueBlock(4, 20), issueBlock(4, 20), issueBlock(4, 20)]);+ // A dialogue-heavy chosen voice: 6 quoted spans of 8 words each → ~48 words,+ // nearly all inside quotes, so the exemplar dialogueRatio is very high. Two+ // copies clear the 40-word exemplar floor comfortably.+ const quotedSpan = `"${Array.from({ length: 8 }, (_, j) => `d${j}`).join(' ')}."`;+ const dialogueExemplarPassage = Array.from({ length: 6 }, () => quotedSpan).join(' ');+ const dialogueExemplars = [+ { passage: dialogueExemplarPassage, note: 'chatty' },+ { passage: dialogueExemplarPassage },+ ];++ it('drafted mode never emits a series-level finding (center === mean)', () => {+ const drift = computeVoiceDrift(dialogueFree, { voiceExemplars: dialogueExemplars });+ expect(drift.baselineMode).toBe('drafted');+ expect(drift.seriesFindings).toEqual([]);+ });++ it('flags a uniformly-off-register metric under the exemplar baseline', () => {+ const drift = computeVoiceDrift(dialogueFree, {+ baselineMode: 'exemplars',+ voiceExemplars: dialogueExemplars,+ });+ expect(drift.exemplarBaselineUsed).toBe(true);+ // dialogueRatio: every issue is 0 (σ≈0) but the chosen voice is dialogue-heavy,+ // so there's no per-issue outlier — it surfaces as a series-level finding.+ expect(drift.outliers.some((o) => o.metricKey === 'dialogueRatio')).toBe(false);+ const dlg = drift.seriesFindings.find((f) => f.metricKey === 'dialogueRatio');+ expect(dlg).toBeTruthy();+ expect(dlg.mean).toBe(0);+ expect(dlg.center).toBeGreaterThan(0);+ expect(dlg.direction).toBe('low'); // the corpus uses LESS dialogue than the voice+ expect(dlg.distance).toBeGreaterThanOrEqual(0.5);+ expect(dlg.baselineMode).toBe('exemplars');+ // No `issue` field — it's a corpus-wide finding, not a per-issue outlier.+ expect(dlg.issue).toBeUndefined();+ });++ it('sorts series findings by distance descending', () => {+ const drift = computeVoiceDrift(dialogueFree, {+ baselineMode: 'exemplars',+ voiceExemplars: dialogueExemplars,+ });+ const distances = drift.seriesFindings.map((f) => f.distance);+ const sorted = [...distances].sort((a, b) => b - a);+ expect(distances).toEqual(sorted);+ });++ it('respects a custom seriesDistanceThreshold (relative distance maxes at 1)', () => {+ const drift = computeVoiceDrift(dialogueFree, {+ baselineMode: 'exemplars',+ voiceExemplars: dialogueExemplars,+ seriesDistanceThreshold: 2, // unreachable — relative distance is in [0, 1]+ });+ expect(drift.seriesFindings).toEqual([]);+ });++ it('does not flag a metric that already produces per-issue outliers (σ>0)', () => {+ // draftedSpread from the baseline-modes block: fragment metric has σ>0, so it+ // flows through the per-issue path, not the series-level branch.+ const spread = 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 drift = computeVoiceDrift(spread, {+ baselineMode: 'exemplars',+ voiceExemplars: [{ passage: issueBlock(6, 5) }, { passage: issueBlock(6, 5) }],+ });+ // fragmentPct has drafted spread, so it never appears as a series-level finding.+ expect(drift.seriesFindings.some((f) => f.metricKey === 'fragmentPct')).toBe(false);+ });++ it('gatedOff runs report an empty seriesFindings array', () => {+ const ms = manuscriptOf([issueBlock(3, 20), issueBlock(3, 20)]);+ const drift = computeVoiceDrift(ms, { baselineMode: 'exemplars', voiceExemplars: dialogueExemplars });+ expect(drift.gatedOff).toBe(true);+ expect(drift.seriesFindings).toEqual([]);+ });++ it('describeSeriesDrift names the metric, corpus value, chosen-voice center, and direction', () => {+ const f = {+ metricKey: 'dialogueRatio', label: 'dialogue ratio',+ mean: 0, center: 42.5, std: 0, distance: 1, direction: 'low', unit: '%',+ baselineMode: 'exemplars',+ };+ const text = describeSeriesDrift(f);+ expect(text).toContain('The whole series');+ expect(text).toContain('0%');+ expect(text).toContain('42.5%');+ expect(text).toContain("the style guide's chosen voice");+ expect(text).toContain('below');+ expect(text).toContain('narration-driven'); // the "lower" phrase for dialogue ratio+ });++ it('describeSeriesDrift labels a blended baseline as the blend', () => {+ const f = {+ metricKey: 'dialogueRatio', label: 'dialogue ratio',+ mean: 0, center: 20, std: 0, distance: 1, direction: 'low', unit: '%',+ baselineMode: 'blended',+ };+ expect(describeSeriesDrift(f)).toContain('the blend of the series mean and the chosen voice');+ });+});+describe('describeDrift + renderFingerprintTable', () => {it('describeDrift names the issue, values, σ, and direction', () => {const o = {@@ -464,4 +573,22 @@ describe('style.voice-drift check (registry wiring)', () => {expect(meanFinding.severity).toBe('medium');expect(meanFinding.issueNumber).toBe(8);});++ it('emits a series-wide finding (issueNumber null) for a uniformly off-register metric (#2248)', () => {+ // Four identical dialogue-free issues → σ≈0 everywhere, no per-issue outlier.+ const ms = manuscriptOf([issueBlock(4, 20), issueBlock(4, 20), issueBlock(4, 20), issueBlock(4, 20)]);+ const quotedSpan = `"${Array.from({ length: 8 }, (_, j) => `d${j}`).join(' ')}."`;+ const passage = Array.from({ length: 6 }, () => quotedSpan).join(' ');+ const series = { styleGuide: { voiceExemplars: [{ passage }, { passage }] } };+ const findings = runCheck(ms, { baselineMode: 'exemplars' }, 'low', series);+ const seriesLevel = findings.find((f) => f.problem.includes('The whole series') && f.problem.includes('dialogue ratio'));+ expect(seriesLevel).toBeTruthy();+ expect(seriesLevel.issueNumber).toBeNull();+ expect(seriesLevel.location).toContain('Series-wide');+ // A corpus-wide mismatch escalates one rank above the low floor.+ expect(seriesLevel.severity).toBe('medium');+ // Drafted mode never produces it (center === mean).+ const drafted = runCheck(ms, { baselineMode: 'drafted' }, 'low', series);+ expect(drafted.some((f) => f.problem.includes('The whole series'))).toBe(false);+ });});diff --git a/server/services/pipeline/voiceFingerprint.js b/server/services/pipeline/voiceFingerprint.jsindex 72b73a775d..c1b6675cd1 100644--- a/server/services/pipeline/voiceFingerprint.js+++ b/server/services/pipeline/voiceFingerprint.js@@ -93,6 +93,7 @@ export async function resolveVoiceDriftConfig(settings, seriesOverrides) {* matrix: object,* series: object,* outliers: object[],+ * seriesFindings: object[],* }>}*/export async function getVoiceFingerprint(seriesId) {@@ -133,5 +134,8 @@ export async function getVoiceFingerprint(seriesId) {matrix: drift.matrix,series: drift.series,outliers: drift.outliers,+ // #2248 — series-wide "uniformly off the chosen voice" findings (no per-issue+ // cell to highlight in the matrix), so the view can surface them as a banner.+ seriesFindings: drift.seriesFindings || [],};}