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: deep-linkable voice-fingerprint matrix view (#2194)

[._.]/ Adam Eivy3e20b7d74b5a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c2abc29b83..17228ae8fc 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -19,6 +19,7 @@
- **[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 4 issues are drafted (with fewer, the statistics are too small to distinguish real drift from a normal series).
- **[issue-2172] The draft prompts now carry a craft anti-pattern corpus, so first drafts avoid recognizable "AI prose" tells before the editorial pass ever runs.** A shared `craft-anti-patterns` prompt block — injected into the prose-draft stage and the Writers Room live-continuation suggestions — encodes hard rules the model must follow while writing: no triadic sensory lists, a cap on "did not [verb]" and "the way X did Y" similes, no "thought about X" constructions or over-explaining after showing, varied paragraph lengths, at least 70% in-scene (not summary), speech that sounds like speech, and at least one genuinely surprising moment per chapter. The same block carries "Stability Trap" countermeasures (from the Rettberg & Wigers 2025 finding that AI stories favor stability over change): characters must end truly different, bad things are allowed to stay bad, some losses are irreversible, information is withheld rather than dumped, and every real choice has a real cost. Preventing these in the draft is far cheaper than detecting them in editorial. Existing installs auto-upgrade their prose/writers-room prompts (customized prompts are left untouched and flagged).
- **[issue-2172] Series arc planning now emits a foreshadowing ledger that the Chekhov's-guns editorial check consumes directly.** When you generate a series arc overview, the model now plans 2–6 planted seeds as explicit `plant → reinforce → payoff` entries with the payoff landing at least 3 issues after the plant (so the reader has time to forget before the gun fires). The ledger persists on the series arc record (lockable and preserved across regenerates, like the reader map and ticking clock), and the `chekhov.setups-payoffs` check reconciles the manuscript against these author-declared seeds instead of inferring every setup from scratch — a more grounded, less hallucination-prone review.
+- **[issue-2194] The voice-drift engine now has a dedicated matrix view showing every issue's full fingerprint, not just the flagged outliers.** A new deep-linkable **Voice Fingerprint** page (`/pipeline/series/:seriesId/voice-fingerprint`, linked from the series header and reachable via ⌘K / voice) renders the whole issues×metrics matrix as a monospace table — one row per drafted issue, one column per fingerprint metric (sentence rhythm, fragment/long-sentence rates, paragraph shape, dialogue ratio, em-dash rate, abstract-noun/simile density, dominant opener, plus any configured vocabulary wells) — with each statistical outlier cell highlighted in amber and a series mean/σ footer. Where the `style.voice-drift` editorial finding only names the flagged outliers in prose, this view shows the full picture at a glance, reading the same per-series config (drift threshold, min issues, vocabulary wells) as the check. Read-only, no LLM cost.
- **[issue-2168] A new "adversarial cuts" editorial check and mechanical applier tightens prose by identifying what a ruthless editor would cut.** The `prose.adversarial-cuts` check asks an LLM editor persona to cut 8–12% of the text as 10–20 passages, classifying each cut by type: FAT (purple prose), REDUNDANT (repeated information), OVER-EXPLAIN (spelling out what's clear), GENERIC (stock phrases), TELL (emotion-telling after showing), or STRUCTURAL (scenes that don't advance the story). Each cut lands as a manuscriptReview finding with the exact verbatim quote. The Manuscript Editor gains an "Apply safe cuts" action that batch-removes OVER-EXPLAIN and REDUNDANT cuts mechanically — exact string match with whitespace-normalized fallback, refusing ambiguous or too-short quotes — through the same snapshotted stage-write path fixes use (full undo via version history). The check also reports `fat_percentage`, `tightest_passage` (protected), and `loosest_passage` for a quick health read.
- **[issue-2170] A simulated four-persona reader panel now reads your whole series and shows you where the readers disagree.** Convene the panel from a new **Reader Panel** tab on the Reader Map page (deep-linkable via `?tab=panel`) and four distinct readers — The Editor (prose texture, subtext, over-explaining), The Genre Reader (pacing and page-turn pull, "gets bored by beautiful prose that doesn't GO anywhere"), The Writer (structure, beats, foreshadowing payoff, whose worst insult is "I can see the outline"), and The First Reader (pure emotional response, no craft vocabulary) — each read a condensed, content-hash-pinned arc digest of the series (per-issue summary, opening/closing excerpts, and notable dialogue) and answer the same ten qualitative questions (where momentum is lost, is the ending earned, what to cut, a missing scene, the thinnest character, best/worst scene, would-recommend, what haunts you, would-read-the-next-book), citing specific issue numbers. The editorial signal is where they *disagree*: an issue flagged by 3+ personas is routed straight into your editorial-findings triage flow as a consensus concern; softer some-flagged-some-didn't calls and "polarizing" issues (one persona's best scene is another's worst) are surfaced for your judgment. One LLM call per persona, run only from the explicit Convene button — nothing fires on its own.
diff --git a/client/src/App.jsx b/client/src/App.jsx
index ef86af78c0..e30432a4fd 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -108,6 +108,7 @@ const PipelineSeriesRoadmap = lazyWithReload(() => import('./pages/PipelineSerie
const PipelineEditorialChecks = lazyWithReload(() => import('./pages/PipelineEditorialChecks'));
const PipelineFindingRedirect = lazyWithReload(() => import('./pages/PipelineFindingRedirect'));
const PipelineReverseOutline = lazyWithReload(() => import('./pages/PipelineReverseOutline'));
+const PipelineVoiceFingerprint = lazyWithReload(() => import('./pages/PipelineVoiceFingerprint'));
const PipelineContinuityBible = lazyWithReload(() => import('./pages/PipelineContinuityBible'));
const PipelineManuscriptEditor = lazyWithReload(() => import('./pages/PipelineManuscriptEditor'));
const PipelineIssue = lazyWithReload(() => import('./pages/PipelineIssue'));
@@ -357,6 +358,7 @@ export default function App() {
<Route path="pipeline/series/:seriesId" element={<PipelineSeries />} />
<Route path="pipeline/series/:seriesId/roadmap" element={<PipelineSeriesRoadmap />} />
<Route path="pipeline/series/:seriesId/reverse-outline" element={<PipelineReverseOutline />} />
+ <Route path="pipeline/series/:seriesId/voice-fingerprint" element={<PipelineVoiceFingerprint />} />
<Route path="pipeline/series/:seriesId/continuity-bible" element={<PipelineContinuityBible />} />
{/* Splat (not a :param route) so navigating between issues reuses the
same component instance instead of remounting + refetching. */}
diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsx
index e84be2216b..60ce2e009e 100644
--- a/client/src/pages/PipelineSeries.jsx
+++ b/client/src/pages/PipelineSeries.jsx
@@ -15,7 +15,7 @@ import { Link, useParams, useNavigate } from 'react-router-dom';
import {
ArrowLeft, Save, Loader2, Workflow as WorkflowIcon, Globe, NotebookPen,
PanelLeftClose, PanelLeftOpen, Sparkles, BookOpen, FileInput, Compass, BookMarked,
- Plus, Trash2,
+ Fingerprint, Plus, Trash2,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import ArcCanvas from '../components/pipeline/ArcCanvas';
@@ -230,6 +230,13 @@ export default function PipelineSeries() {
>
<BookMarked size={12} /> Continuity
</Link>
+ <Link
+ to={`/pipeline/series/${series.id}/voice-fingerprint`}
+ className="ml-2 inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-400 hover:text-white border border-port-border bg-port-card"
+ title="See every issue's statistical prose fingerprint (sentence rhythm, register, dialogue ratio…) with drift outliers highlighted"
+ >
+ <Fingerprint size={12} /> Voice Fingerprint
+ </Link>
<Link
to={buildImporterLink({ universeId: series.universeId, seriesId: series.id })}
className="ml-2 inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-400 hover:text-white border border-port-border bg-port-card"
diff --git a/client/src/pages/PipelineVoiceFingerprint.jsx b/client/src/pages/PipelineVoiceFingerprint.jsx
new file mode 100644
index 0000000000..2372699ff4
--- /dev/null
+++ b/client/src/pages/PipelineVoiceFingerprint.jsx
@@ -0,0 +1,226 @@
+/**
+ * Pipeline — Voice-Fingerprint Matrix (#2194, CWQE Phase 2 follow-up).
+ *
+ * A dedicated, deep-linkable surface for the deterministic voice-drift engine:
+ * a monospace issues×metrics matrix where every drafted issue's full fingerprint
+ * vector (sentence rhythm, fragment/long-sentence rates, paragraph shape,
+ * dialogue ratio, em-dash rate, abstract-noun/simile density, dominant opener,
+ * plus any configured vocabulary wells) is a row, and each statistical outlier
+ * cell (> the series drift threshold in σ) is highlighted. The finding cards on
+ * the Editorial Checks page only surface the FLAGGED outliers as prose; this view
+ * shows the whole matrix + the series mean/σ footer so the drift is legible at a
+ * glance. Read-only — no LLM cost.
+ *
+ * The series id is the route param (`/pipeline/series/:seriesId/voice-fingerprint`),
+ * so the view is shareable/bookmarkable per the "URL is the source of truth"
+ * convention. A stale/deleted id falls back to the pipeline index.
+ */
+
+import { useEffect, useState } from 'react';
+import { Link, useParams, useNavigate } from 'react-router-dom';
+import { Loader2, ArrowLeft, Fingerprint, BookOpen, Info } from 'lucide-react';
+import toast from '../components/ui/Toast';
+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}`;
+
+export default function PipelineVoiceFingerprint() {
+ const { seriesId } = useParams();
+ const navigate = useNavigate();
+ const [series, setSeries] = useState(null);
+ const [data, setData] = useState(null);
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ let canceled = false;
+ setLoading(true);
+ Promise.all([
+ getPipelineSeries(seriesId),
+ getVoiceFingerprint(seriesId, { silent: true }),
+ ])
+ .then(([s, fp]) => {
+ if (canceled) return;
+ setSeries(s);
+ setData(fp);
+ })
+ .catch((err) => {
+ if (canceled) return;
+ toast.error(err.message || 'Failed to load voice fingerprint');
+ navigate('/pipeline');
+ })
+ .finally(() => { if (!canceled) setLoading(false); });
+ return () => { canceled = true; };
+ }, [seriesId, navigate]);
+
+ if (loading) {
+ return (
+ <div className="h-full flex items-center justify-center text-gray-400">
+ <Loader2 className="animate-spin" size={20} />
+ </div>
+ );
+ }
+
+ const columns = data?.columns || [];
+ const issues = data?.matrix?.issues || [];
+ const seriesStats = data?.series || {};
+ const outlierSet = new Set((data?.outliers || []).map((o) => outlierKey(o.issue, o.metricKey)));
+ const hasMatrix = issues.length > 0;
+
+ return (
+ <div className="h-full overflow-y-auto p-4 md:p-6">
+ <header className="flex flex-wrap items-center gap-2 mb-4">
+ <Link
+ to={`/pipeline/series/${seriesId}`}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-400 hover:text-white border border-port-border bg-port-card"
+ title="Back to series"
+ >
+ <ArrowLeft size={12} /> Series
+ </Link>
+ <h1 className="text-lg font-semibold text-white flex items-center gap-2">
+ <Fingerprint size={18} className="text-port-accent" /> Voice Fingerprint
+ </h1>
+ {series?.name ? <span className="text-sm text-gray-400 truncate">— {series.name}</span> : null}
+ <Link
+ to="/pipeline/editorial-checks"
+ className="ml-auto inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-400 hover:text-white border border-port-border bg-port-card"
+ title="Configure the style.voice-drift check (threshold, min issues, vocabulary wells)"
+ >
+ Editorial Checks
+ </Link>
+ </header>
+
+ <p className="text-xs text-gray-500 mb-4 max-w-3xl">
+ Every drafted issue's prose fingerprint. Each column is a metric; a cell
+ highlighted 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{' '}
+ <code className="text-gray-400">style.voice-drift</code> editorial check
+ flags; it just shows the whole matrix, not only the flagged outliers.
+ </p>
+
+ {!hasMatrix ? (
+ <EmptyState gatedOff={data?.gatedOff} issueCount={data?.issueCount ?? 0} minIssues={data?.config?.minIssues} />
+ ) : (
+ <>
+ {data?.gatedOff ? (
+ <div className="mb-4 flex items-start gap-2 px-3 py-2 rounded-lg border border-port-border bg-port-card text-gray-400 text-sm">
+ <Info size={14} className="mt-0.5 shrink-0" />
+ <span>
+ Drift detection is off — only {data.issueCount} issue
+ {data.issueCount === 1 ? '' : 's'} drafted (minimum{' '}
+ {data?.config?.minIssues ?? 4}). The fingerprint matrix is shown for
+ reference, but no outliers are flagged until more issues exist.
+ </span>
+ </div>
+ ) : null}
+ <FingerprintMatrix
+ columns={columns}
+ issues={issues}
+ seriesStats={seriesStats}
+ outlierSet={outlierSet}
+ />
+ <p className="text-xs text-gray-500 mt-3">
+ {issues.length} issue{issues.length === 1 ? '' : 's'} · {columns.length} metrics
+ {data?.wells?.length ? ` · vocabulary wells: ${data.wells.join(', ')}` : ''}
+ {data?.outliers?.length
+ ? ` · ${data.outliers.length} outlier${data.outliers.length === 1 ? '' : 's'} flagged`
+ : ''}
+ </p>
+ </>
+ )}
+ </div>
+ );
+}
+
+function EmptyState({ gatedOff, issueCount, minIssues }) {
+ if (gatedOff && issueCount > 0) {
+ return (
+ <div className="text-center text-gray-400 py-16">
+ <Fingerprint className="mx-auto mb-3 opacity-40" size={28} />
+ Only {issueCount} issue{issueCount === 1 ? '' : 's'} drafted — drift needs at
+ least {minIssues ?? 4} to compute a stable series voice. Draft more issues,
+ then return to see the fingerprint matrix.
+ </div>
+ );
+ }
+ return (
+ <div className="text-center text-gray-400 py-16">
+ <BookOpen className="mx-auto mb-3 opacity-40" size={28} />
+ Nothing is drafted yet. Write or import a manuscript, then return to see each
+ issue's voice fingerprint.
+ </div>
+ );
+}
+
+function FingerprintMatrix({ columns, issues, seriesStats, outlierSet }) {
+ const round2 = (n) => Math.round((Number(n) || 0) * 100) / 100;
+ return (
+ <div className="overflow-x-auto border border-port-border rounded-lg">
+ <table className="border-collapse font-mono text-xs w-full">
+ <thead>
+ <tr className="bg-port-card">
+ <th className="sticky left-0 z-10 bg-port-card text-left text-gray-400 font-medium px-3 py-2 min-w-[4rem]">
+ Issue
+ </th>
+ {columns.map((col) => (
+ <th
+ key={col.key}
+ className="px-2 py-2 text-right text-gray-400 font-medium whitespace-nowrap align-bottom"
+ title={`${col.label} — high = ${col.higher}; low = ${col.lower}`}
+ >
+ {col.label}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {issues.map((it) => (
+ <tr key={it.issue} className="border-t border-port-border">
+ <td className="sticky left-0 z-10 bg-port-bg text-gray-300 font-medium px-3 py-1.5">
+ #{it.issue}
+ </td>
+ {columns.map((col) => {
+ const v = it.metrics?.[col.key] ?? 0;
+ const isOutlier = outlierSet.has(outlierKey(it.issue, col.key));
+ return (
+ <td
+ key={col.key}
+ className={`px-2 py-1.5 text-right tabular-nums ${
+ isOutlier
+ ? '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}
+ >
+ {round2(v)}{col.unit || ''}
+ </td>
+ );
+ })}
+ </tr>
+ ))}
+ </tbody>
+ <tfoot>
+ <tr className="border-t-2 border-port-border bg-port-card">
+ <td className="sticky left-0 z-10 bg-port-card text-gray-500 px-3 py-1.5">mean</td>
+ {columns.map((col) => (
+ <td key={col.key} className="px-2 py-1.5 text-right text-gray-500 tabular-nums">
+ {round2(seriesStats?.[col.key]?.mean)}{col.unit || ''}
+ </td>
+ ))}
+ </tr>
+ <tr className="bg-port-card">
+ <td className="sticky left-0 z-10 bg-port-card text-gray-500 px-3 py-1.5">σ</td>
+ {columns.map((col) => (
+ <td key={col.key} className="px-2 py-1.5 text-right text-gray-500 tabular-nums">
+ {round2(seriesStats?.[col.key]?.std)}
+ </td>
+ ))}
+ </tr>
+ </tfoot>
+ </table>
+ </div>
+ );
+}
diff --git a/client/src/pages/PipelineVoiceFingerprint.test.jsx b/client/src/pages/PipelineVoiceFingerprint.test.jsx
new file mode 100644
index 0000000000..50a8938ab7
--- /dev/null
+++ b/client/src/pages/PipelineVoiceFingerprint.test.jsx
@@ -0,0 +1,96 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import { MemoryRouter, Routes, Route } from 'react-router-dom';
+import PipelineVoiceFingerprint from './PipelineVoiceFingerprint';
+
+const getPipelineSeries = vi.fn();
+const getVoiceFingerprint = vi.fn();
+
+vi.mock('../services/api', () => ({
+ getPipelineSeries: (...a) => getPipelineSeries(...a),
+ getVoiceFingerprint: (...a) => getVoiceFingerprint(...a),
+}));
+
+vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn(), warning: vi.fn() } }));
+
+function renderAt(seriesId = 'ser-1') {
+ return render(
+ <MemoryRouter initialEntries={[`/pipeline/series/${seriesId}/voice-fingerprint`]}>
+ <Routes>
+ <Route path="/pipeline/series/:seriesId/voice-fingerprint" element={<PipelineVoiceFingerprint />} />
+ <Route path="/pipeline" element={<div>Pipeline index</div>} />
+ </Routes>
+ </MemoryRouter>,
+ );
+}
+
+const MATRIX_PAYLOAD = {
+ seriesId: 'ser-1',
+ config: { sigmaThreshold: 1.5, minIssues: 4, vocabularyWells: '' },
+ wells: [],
+ columns: [
+ { key: 'sentenceLenMean', label: 'sentence-length mean', unit: ' words', higher: 'longer', lower: 'shorter', isWell: false },
+ { key: 'dialogueRatio', label: 'dialogue ratio', unit: '%', higher: 'more dialogue', lower: 'more narration', isWell: false },
+ ],
+ gatedOff: false,
+ issueCount: 5,
+ threshold: 1.5,
+ matrix: {
+ metricKeys: ['sentenceLenMean', 'dialogueRatio'],
+ issues: [
+ { issue: 1, words: 100, sentences: 8, metrics: { sentenceLenMean: 12.5, dialogueRatio: 20 } },
+ { issue: 5, words: 40, sentences: 8, metrics: { sentenceLenMean: 4, dialogueRatio: 0 } },
+ ],
+ },
+ series: { sentenceLenMean: { mean: 10.5, std: 3 }, dialogueRatio: { mean: 15, std: 8 } },
+ outliers: [
+ { issue: 5, metricKey: 'sentenceLenMean', label: 'sentence-length mean', value: 4, mean: 10.5, std: 3, z: -2.1, direction: 'low', unit: ' words' },
+ ],
+};
+
+beforeEach(() => {
+ getPipelineSeries.mockReset();
+ getVoiceFingerprint.mockReset();
+ getPipelineSeries.mockResolvedValue({ id: 'ser-1', name: 'Test Series' });
+});
+
+describe('PipelineVoiceFingerprint', () => {
+ it('renders the issues×metrics matrix with an outlier cell highlighted', async () => {
+ getVoiceFingerprint.mockResolvedValue(MATRIX_PAYLOAD);
+ renderAt();
+ await waitFor(() => expect(screen.getByText('Voice Fingerprint')).toBeInTheDocument());
+ // Both issue rows render.
+ expect(screen.getByText('#1')).toBeInTheDocument();
+ expect(screen.getByText('#5')).toBeInTheDocument();
+ // Column headers render.
+ expect(screen.getAllByText('sentence-length mean').length).toBeGreaterThan(0);
+ // The outlier cell (issue 5, sentenceLenMean = 4) is highlighted amber.
+ const outlierCell = screen.getByText('4 words');
+ expect(outlierCell.className).toContain('port-warning');
+ });
+
+ it('shows the gated-off notice below minIssues but still renders the matrix', async () => {
+ getVoiceFingerprint.mockResolvedValue({
+ ...MATRIX_PAYLOAD,
+ gatedOff: true,
+ issueCount: 2,
+ outliers: [],
+ matrix: { metricKeys: ['sentenceLenMean'], issues: [{ issue: 1, words: 5, sentences: 1, metrics: { sentenceLenMean: 5 } }, { issue: 2, words: 4, sentences: 1, metrics: { sentenceLenMean: 4 } }] },
+ });
+ renderAt();
+ await waitFor(() => expect(screen.getByText(/Drift detection is off/)).toBeInTheDocument());
+ expect(screen.getByText('#1')).toBeInTheDocument();
+ });
+
+ it('renders an empty state when nothing is drafted', async () => {
+ getVoiceFingerprint.mockResolvedValue({
+ ...MATRIX_PAYLOAD,
+ gatedOff: false,
+ issueCount: 0,
+ outliers: [],
+ matrix: { metricKeys: [], issues: [] },
+ });
+ renderAt();
+ await waitFor(() => expect(screen.getByText(/Nothing is drafted yet/)).toBeInTheDocument());
+ });
+});
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index bcb67c9ff6..29dab034c0 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -833,6 +833,13 @@ export const getReverseOutlineStatus = (seriesId, options = {}) =>
export const pipelineReverseOutlineSseUrl = (seriesId) =>
`/api/pipeline/series/${encodeURIComponent(seriesId)}/reverse-outline/generate/progress`;
+// ---- Voice fingerprint matrix (#2194) ----
+// The full issues×metrics fingerprint vector + deterministic drift result:
+// { seriesId, config, wells, columns, gatedOff, issueCount, threshold, matrix,
+// series, outliers }. Read-only, no LLM cost — drives the dedicated matrix view.
+export const getVoiceFingerprint = (seriesId, options = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/voice-fingerprint`, options);
+
// ---- Continuity Bible (established-facts ledger) ----
// The stored ledger: { facts, stale, status }. `status:'none'` when never
// generated, `'no-content'` shell while there's no canon and nothing drafted.
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 8cc0a80db5..52075e51b4 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -30,6 +30,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.create.pipeline', path: '/pipeline', label: 'Series Pipeline', section: 'Create', aliases: ['series', 'pipeline', 'production', 'series-pipeline', 'production-pipeline'], keywords: ['series', 'issue', 'episode', 'comic', 'script', 'prose', 'storyboard', 'narrative', 'workflow'] },
{ id: 'nav.create.pipeline.editorial-checks', path: '/pipeline/editorial-checks', label: 'Editorial Checks', section: 'Create', aliases: ['editorial-checks', 'editorial', 'checks', 'editorial-review', 'content-checks', 'manuscript-checks'], keywords: ['editorial', 'check', 'review', 'naming', 'exposition', 'info-dumping', 'continuity', 'quality', 'lint', 'triage', 'findings', 'deterministic', 'llm'] },
{ id: 'nav.create.pipeline-continuity-bible', path: '/pipeline', label: 'Series Continuity', section: 'Create', aliases: ['continuity-bible', 'continuity', 'series-continuity', 'facts-ledger', 'established-facts', 'canon-ledger'], keywords: ['continuity', 'bible', 'facts', 'ledger', 'established', 'knowledge-leak', 'contradiction', 'timeline', 'wardrobe', 'prop', 'physical-traits', 'who-knows-what'] },
+ { id: 'nav.create.pipeline-voice-fingerprint', path: '/pipeline', label: 'Voice Fingerprint', section: 'Create', aliases: ['voice-fingerprint', 'voice-drift', 'fingerprint', 'voice-matrix', 'prose-fingerprint'], keywords: ['voice', 'drift', 'fingerprint', 'matrix', 'style', 'prose', 'sentence-rhythm', 'outlier', 'metrics', 'deterministic', 'editorial', 'consistency', 'register', 'vocabulary-wells'] },
{ id: 'nav.create.sharing', path: '/sharing', label: 'Sharing', section: 'Create', aliases: ['sharing', 'share', 'buckets', 'share-buckets'], keywords: ['google drive', 'dropbox', 'icloud', 'syncthing', 'export', 'import', 'collaborate', 'federation', 'peer', 'cross-network'] },
{ id: 'nav.create.sharing-duplicates', path: '/sharing/duplicates', label: 'Duplicates', section: 'Create', aliases: ['duplicates', 'duplicate-universes', 'duplicate-series', 'dedupe', 'merge-duplicates'], keywords: ['duplicate', 'merge', 'rename', 'same name', 'two copies', 'reconcile', 'collision'] },
{ id: 'nav.create.start-story', path: '/start-story', label: 'Start a Story', section: 'Create', aliases: ['start-story', 'start-a-story', 'start', 'begin-story', 'create-story', 'onramp'], keywords: ['start here', 'begin', 'idea', 'import', 'prose', 'story builder', 'writers room', 'importer', 'how to start', 'new', 'front door', 'choose'] },
diff --git a/server/routes/pipeline/editorial.js b/server/routes/pipeline/editorial.js
index 917591be92..cdf5d435e7 100644
--- a/server/routes/pipeline/editorial.js
+++ b/server/routes/pipeline/editorial.js
@@ -31,6 +31,7 @@ import * as editorialAnalysis from '../../services/pipeline/editorialAnalysis.js
import * as editorialRunner from '../../services/pipeline/editorialAnalysisRunner.js';
import * as readerPanel from '../../services/pipeline/readerPanel.js';
import * as readerPanelRunner from '../../services/pipeline/readerPanelRunner.js';
+import * as voiceFingerprint from '../../services/pipeline/voiceFingerprint.js';
import * as checkRunner from '../../services/pipeline/editorial/checkRunner.js';
import { getSeriesHealth, READINESS_GATES, DEFAULT_READINESS_GATE } from '../../services/pipeline/editorialScore.js';
import { getSettings, updateSettingsWith } from '../../services/settings.js';
@@ -52,6 +53,21 @@ router.get('/series/:id/editorial', asyncHandler(async (req, res) => {
res.json(await editorialAnalysis.getSeriesEditorial(req.params.id));
}));
+// Series id path param — a non-empty trimmed string (record ids are `ser-<uuid>`
+// shaped; the service throws a mapped 404 for an unknown id).
+const seriesIdParamSchema = z.object({ id: z.string().trim().min(1).max(200) });
+
+// Voice-fingerprint matrix (#2194) — the full issues×metrics fingerprint vector
+// plus the deterministic drift result (outliers flagged), a thin read-only wrapper
+// over the pure `voiceFingerprintMatrix()`/`computeVoiceDrift()` primitives. Drives
+// the dedicated deep-linkable matrix view, which shows EVERY issue's fingerprint,
+// not just the flagged outliers that surface as editorial findings.
+router.get('/series/:id/voice-fingerprint', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(seriesIdParamSchema, req.params);
+ const result = await voiceFingerprint.getVoiceFingerprint(id).catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
// Full per-issue snapshot (section-by-section emotion log + character arcs)
router.get('/issues/:id/editorial', asyncHandler(async (req, res) => {
await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });
diff --git a/server/routes/pipeline/editorial.test.js b/server/routes/pipeline/editorial.test.js
index 3cffc73ff2..171ef64d6b 100644
--- a/server/routes/pipeline/editorial.test.js
+++ b/server/routes/pipeline/editorial.test.js
@@ -28,6 +28,16 @@ vi.mock('../../services/pipeline/issues.js', async (importOriginal) => ({
getIssue: vi.fn(async (id) => ({ id })),
}));
+// Voice-fingerprint service (#2194) — stub the read so the route test exercises
+// the series-resolve + param-validation wiring without the manuscript store.
+const getVoiceFingerprint = vi.fn(async (seriesId) => {
+ if (seriesId === 'missing') throw Object.assign(new Error('nope'), { code: 'PIPELINE_SERIES_NOT_FOUND' });
+ return { seriesId, gatedOff: false, issueCount: 5, threshold: 1.5, columns: [], wells: [], matrix: { issues: [] }, series: {}, outliers: [] };
+});
+vi.mock('../../services/pipeline/voiceFingerprint.js', () => ({
+ getVoiceFingerprint: (...a) => getVoiceFingerprint(...a),
+}));
+
const startEditorialChecksRun = vi.fn(() => ({ runId: 'run-1', alreadyRunning: false }));
const previewCustomCheck = vi.fn(async () => ({ findings: [{ severity: 'medium', problem: 'x' }], skipped: false, invalid: false }));
vi.mock('../../services/pipeline/editorial/checkRunner.js', () => ({
@@ -58,6 +68,22 @@ beforeEach(() => {
startEditorialChecksRun.mockClear();
previewCustomCheck.mockClear();
getSeriesHealth.mockClear();
+ getVoiceFingerprint.mockClear();
+});
+
+describe('GET /api/pipeline/series/:id/voice-fingerprint (#2194)', () => {
+ it('returns the fingerprint matrix payload for a known series', async () => {
+ const res = await request(app).get('/api/pipeline/series/ser-1/voice-fingerprint');
+ expect(res.status).toBe(200);
+ expect(res.body.seriesId).toBe('ser-1');
+ expect(res.body.gatedOff).toBe(false);
+ expect(getVoiceFingerprint).toHaveBeenCalledWith('ser-1');
+ });
+
+ it('404s for a missing series (mapped from the service NOT_FOUND code)', async () => {
+ const res = await request(app).get('/api/pipeline/series/missing/voice-fingerprint');
+ expect(res.status).toBe(404);
+ });
});
describe('GET /api/pipeline/editorial/checks', () => {
diff --git a/server/services/pipeline/voiceFingerprint.js b/server/services/pipeline/voiceFingerprint.js
new file mode 100644
index 0000000000..6869b2f50c
--- /dev/null
+++ b/server/services/pipeline/voiceFingerprint.js
@@ -0,0 +1,139 @@
+/**
+ * Pipeline — voice-fingerprint matrix service (#2194, CWQE Phase 2 follow-up).
+ *
+ * A thin read-only orchestration over the pure primitives in
+ * `server/lib/editorial/voiceFingerprint.js`: it stitches the series' drafted
+ * manuscript into the `# Issue N` corpus (the exact same corpus the deterministic
+ * `style.voice-drift` check reads — via `collectManuscriptSections`/`sectionsCorpus`),
+ * resolves the SAME per-series check config (drift threshold, minIssues, and the
+ * optional vocabulary-wells spec), then returns the full issues×metrics matrix plus
+ * the drift result so the dedicated matrix view can render every issue's fingerprint
+ * vector with the flagged outlier cells highlighted — not just the flagged outliers
+ * that surface as editorial findings.
+ *
+ * Pure math lives in the lib primitive; this file only reads state (series existence,
+ * manuscript sections, resolved check config). No LLM cost, no mutation.
+ */
+
+import { getSeries } from './series.js';
+import { collectManuscriptSections, sectionsCorpus } from './arcPlanner.js';
+import { getSettings } from '../settings.js';
+import {
+ getCheckById,
+ readChecksSlice,
+ resolveCheckConfig,
+} from '../../lib/editorial/index.js';
+import {
+ computeVoiceDrift,
+ parseVoiceWells,
+ metricLabel,
+ VOICE_METRICS,
+} from '../../lib/editorial/voiceFingerprint.js';
+
+// The deterministic check whose per-series config (threshold / minIssues /
+// vocabulary wells) governs both the finding-emitting run AND this read view, so
+// the matrix agrees with what the editor flags. Keep in sync with the check id in
+// server/lib/editorial/checks/proseStyle.js.
+export const VOICE_DRIFT_CHECK_ID = 'style.voice-drift';
+
+// One column descriptor per metric key so the UI renders a stable, self-describing
+// header without re-deriving labels/units/direction phrasing client-side. `higher`
+// / `lower` explain what a value above/below the series mean MEANS for that metric;
+// wells share a generic phrasing (no static descriptor).
+function describeColumn(key) {
+ const desc = VOICE_METRICS.find((m) => m.key === key);
+ if (desc) {
+ return {
+ key,
+ label: desc.label,
+ unit: desc.unit || '',
+ higher: desc.higher,
+ lower: desc.lower,
+ isWell: false,
+ };
+ }
+ const isWell = typeof key === 'string' && key.startsWith('well:');
+ return {
+ key,
+ label: metricLabel(key),
+ unit: '',
+ higher: isWell ? `leans harder on the "${key.slice(5)}" register` : 'runs high',
+ lower: isWell ? `uses the "${key.slice(5)}" register less` : 'runs low',
+ isWell,
+ };
+}
+
+/**
+ * Resolve the effective `style.voice-drift` config for a series from the persisted
+ * per-check settings (threshold / minIssues / vocabularyWells), tolerant of a
+ * hand-edited or absent slice — falls back to the registry defaults via
+ * `resolveCheckConfig`.
+ *
+ * @param {object} [settings] pre-loaded settings (optional; fetched when omitted)
+ * @returns {Promise<{ sigmaThreshold: number, minIssues: number, vocabularyWells: string }>}
+ */
+export async function resolveVoiceDriftConfig(settings) {
+ const s = settings || await getSettings();
+ const check = getCheckById(s, VOICE_DRIFT_CHECK_ID);
+ if (!check) return { sigmaThreshold: 1.5, minIssues: 4, vocabularyWells: '' };
+ const stored = readChecksSlice(s)[VOICE_DRIFT_CHECK_ID] || {};
+ return resolveCheckConfig(check, stored.config);
+}
+
+/**
+ * Compute the full voice-fingerprint matrix + drift for a series' drafted
+ * manuscript. Verifies the series exists (throws the service error the route maps
+ * to a 404), stitches the manuscript corpus, resolves the check config, and returns
+ * a UI-ready structured payload.
+ *
+ * @param {string} seriesId
+ * @returns {Promise<{
+ * seriesId: string,
+ * config: { sigmaThreshold: number, minIssues: number, vocabularyWells: string },
+ * wells: string[],
+ * columns: Array<{ key, label, unit, higher, lower, isWell }>,
+ * gatedOff: boolean,
+ * issueCount: number,
+ * threshold: number,
+ * matrix: object,
+ * series: object,
+ * outliers: object[],
+ * }>}
+ */
+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);
+
+ const [sections, cfg] = await Promise.all([
+ collectManuscriptSections(seriesId),
+ resolveVoiceDriftConfig(),
+ ]);
+ const manuscript = sectionsCorpus(sections);
+ const wells = parseVoiceWells(cfg.vocabularyWells || '');
+
+ const drift = computeVoiceDrift(manuscript, {
+ threshold: cfg.sigmaThreshold ?? 1.5,
+ minIssues: cfg.minIssues ?? 4,
+ wells,
+ });
+
+ const columns = (drift.matrix.metricKeys || []).map(describeColumn);
+
+ return {
+ seriesId,
+ config: {
+ sigmaThreshold: cfg.sigmaThreshold ?? 1.5,
+ minIssues: cfg.minIssues ?? 4,
+ vocabularyWells: cfg.vocabularyWells || '',
+ },
+ wells: drift.matrix.wells || [],
+ columns,
+ gatedOff: drift.gatedOff,
+ issueCount: drift.issueCount,
+ threshold: drift.threshold,
+ matrix: drift.matrix,
+ series: drift.series,
+ outliers: drift.outliers,
+ };
+}
diff --git a/server/services/pipeline/voiceFingerprint.test.js b/server/services/pipeline/voiceFingerprint.test.js
new file mode 100644
index 0000000000..1b9c0b7a5f
--- /dev/null
+++ b/server/services/pipeline/voiceFingerprint.test.js
@@ -0,0 +1,130 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// A stitched manuscript with 5 issues; issue 5 is deliberately metronomic (every
+// sentence the same short length) so it drifts on the sentence-rhythm metrics.
+const VARIED = 'The knight rode north through the burning fields. '
+ + 'He remembered, suddenly and against his will, the long slow summers of a childhood that no longer belonged to anyone alive, '
+ + 'and the memory tasted of ash. Rain. It fell like a curtain across the ruined valley, and the horse balked. '
+ + '"We should turn back," she said. He shook his head, saying nothing, watching the smoke climb.';
+const METRONOMIC = 'The man walked home. The dog ran fast. The sun went down. '
+ + 'The rain came hard. The road was long. The night grew cold. The fire burned low. The end came soon.';
+
+function buildManuscript() {
+ const sections = [];
+ for (let n = 1; n <= 4; n += 1) sections.push(`# Issue ${n} — Chapter ${n} (prose)\n\n${VARIED}`);
+ sections.push(`# Issue 5 — Chapter 5 (prose)\n\n${METRONOMIC}`);
+ return sections.join('\n\n---\n\n');
+}
+
+let settingsStore = {};
+let manuscriptCorpus = buildManuscript();
+
+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' };
+ }),
+}));
+
+vi.mock('./arcPlanner.js', () => ({
+ collectManuscriptSections: vi.fn(async () => [{ number: 1, content: 'x' }]),
+ sectionsCorpus: vi.fn(() => manuscriptCorpus),
+}));
+
+vi.mock('../settings.js', () => ({
+ getSettings: vi.fn(async () => settingsStore),
+}));
+
+const { getVoiceFingerprint, resolveVoiceDriftConfig, VOICE_DRIFT_CHECK_ID } = await import('./voiceFingerprint.js');
+
+beforeEach(() => {
+ settingsStore = {};
+ manuscriptCorpus = buildManuscript();
+});
+
+describe('resolveVoiceDriftConfig', () => {
+ it('falls back to registry defaults when nothing is stored', async () => {
+ const cfg = await resolveVoiceDriftConfig();
+ expect(cfg.sigmaThreshold).toBe(1.5);
+ expect(cfg.minIssues).toBe(4);
+ expect(cfg.vocabularyWells).toBe('');
+ });
+
+ it('reads the persisted per-check config slice', async () => {
+ settingsStore = {
+ pipelineEditorialChecks: {
+ checks: {
+ [VOICE_DRIFT_CHECK_ID]: { config: { sigmaThreshold: 2, minIssues: 3, vocabularyWells: 'trade: forge, anvil' } },
+ },
+ },
+ };
+ const cfg = await resolveVoiceDriftConfig();
+ expect(cfg.sigmaThreshold).toBe(2);
+ expect(cfg.minIssues).toBe(3);
+ expect(cfg.vocabularyWells).toBe('trade: forge, anvil');
+ });
+});
+
+describe('getVoiceFingerprint', () => {
+ it('returns a UI-ready matrix + drift for a drafted series', async () => {
+ const res = await getVoiceFingerprint('ser-1');
+ expect(res.seriesId).toBe('ser-1');
+ expect(res.gatedOff).toBe(false);
+ expect(res.issueCount).toBe(5);
+ expect(res.threshold).toBe(1.5);
+ // A stable, self-describing column list (static metrics; no wells configured).
+ expect(res.columns.length).toBeGreaterThan(0);
+ expect(res.columns.every((c) => typeof c.label === 'string' && typeof c.key === 'string')).toBe(true);
+ expect(res.wells).toEqual([]);
+ // Every issue is a matrix row with a numeric metric per column.
+ expect(res.matrix.issues.map((it) => it.issue)).toEqual([1, 2, 3, 4, 5]);
+ for (const it of res.matrix.issues) {
+ for (const col of res.columns) {
+ expect(typeof it.metrics[col.key]).toBe('number');
+ }
+ }
+ // The metronomic issue 5 drifts — at least one outlier is flagged, all with
+ // the fields the UI highlights on.
+ expect(res.outliers.length).toBeGreaterThan(0);
+ expect(res.outliers.some((o) => o.issue === 5)).toBe(true);
+ for (const o of res.outliers) {
+ expect(o).toHaveProperty('metricKey');
+ expect(o).toHaveProperty('z');
+ expect(['high', 'low']).toContain(o.direction);
+ }
+ // Series mean/σ footer keyed per metric.
+ for (const col of res.columns) {
+ expect(res.series[col.key]).toHaveProperty('mean');
+ expect(res.series[col.key]).toHaveProperty('std');
+ }
+ });
+
+ it('gates off below minIssues (matrix still returned for reference)', async () => {
+ manuscriptCorpus = ['# Issue 1 (prose)\n\nThe man walked home.', '# Issue 2 (prose)\n\nThe dog ran fast.']
+ .join('\n\n---\n\n');
+ const res = await getVoiceFingerprint('ser-1');
+ expect(res.gatedOff).toBe(true);
+ expect(res.issueCount).toBe(2);
+ expect(res.outliers).toEqual([]);
+ expect(res.matrix.issues.length).toBe(2);
+ });
+
+ it('appends configured vocabulary wells as columns', async () => {
+ settingsStore = {
+ pipelineEditorialChecks: {
+ checks: {
+ [VOICE_DRIFT_CHECK_ID]: { config: { vocabularyWells: 'trade: forge, anvil, knight' } },
+ },
+ },
+ };
+ const res = await getVoiceFingerprint('ser-1');
+ expect(res.wells).toContain('trade');
+ const wellCol = res.columns.find((c) => c.key === 'well:trade');
+ expect(wellCol).toBeTruthy();
+ expect(wellCol.isWell).toBe(true);
+ });
+
+ it('propagates a NOT_FOUND error for a missing series', async () => {
+ await expect(getVoiceFingerprint('missing')).rejects.toMatchObject({ code: 'PIPELINE_SERIES_NOT_FOUND' });
+ });
+});