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

fix([issue-2166]): address review — exclude empty issues, minIssues=4, dedupe tokenize

Adam Eivy41240a9fb2f2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 4752f39fb6..ffea82f80f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -11,7 +11,7 @@
## Creative Writing Quality Engine
- **[issue-2165] Editorial review now catches recognizable "AI slop" writing tells automatically.** Four new deterministic editorial checks join the existing 68: a tiered banned-word scan (hard-bans like "delve"/"myriad"/"utilize"; suspicious words like "robust"/"seamless" only flagged when 3+ cluster in one paragraph), fiction-specific AI-tell idioms ("a sense of dread", "couldn't help but", "eyes widened", "a wave of relief washed over him"), rhetorical structural tics ("not just X, but Y", runs of "did not [verb]", punchy three-sentence-in-a-row bursts like "Fast. Precise. Deadly."), and structural burstiness (em-dash overuse, essay-style transition-word openers, mechanically uniform paragraph lengths). Each surfaces as an editorial finding with the exact offending quote, same as the existing prose checks — configurable thresholds and house-style allowlists included.
-- **[issue-2166] Editorial review now flags an issue whose narrative voice statistically drifts from the rest of the series.** A new deterministic `style.voice-drift` check measures each issue's prose fingerprint — sentence-length rhythm (mean, spread, variation), fragment and long-sentence rates, paragraph shape, dialogue ratio, em-dash rate, abstract-noun and simile density, and how often sentences open the same way — then compares every issue against the series average and flags the outliers (e.g. "Issue 7's sentence-length variation is 0.18 vs the series 0.41 — prose has gone metronomic"). It's the cheap, deterministic complement to the existing LLM voice-consistency check: no model cost, and it names the exact issue and metric that drifted. You can tune the sensitivity (σ threshold), and optionally declare vocabulary "wells" — register categories like `trade: forge, anvil; body: pulse, sinew` — so it also flags an issue that drops a register the series leans on. It stays off until at least 3 issues are drafted (statistics need a series to compare against).
+- **[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).
## Human Activity Tracking
diff --git a/server/lib/editorial/checks/proseStyle.js b/server/lib/editorial/checks/proseStyle.js
index 4cb401e2f5..3262d237e2 100644
--- a/server/lib/editorial/checks/proseStyle.js
+++ b/server/lib/editorial/checks/proseStyle.js
@@ -1006,7 +1006,7 @@ export const proseStyleChecks = [
sources: ['manuscript'],
label: 'Statistical voice drift (deterministic)',
description:
- "Deterministic sibling of style.voice-consistency — where that LLM check judges tone subjectively, this MEASURES each issue's prose fingerprint (sentence rhythm, fragment/long-sentence rates, paragraph shape, dialogue ratio, em-dash rate, abstract-noun/simile density, dominant sentence-opener, plus any configured vocabulary wells), computes the series mean/σ per metric, and flags an issue that sits more than a threshold's σ from the series voice — naming the metric, the issue value vs the series mean, and the direction (\"issue 7 sentence-length CV 0.18 vs series 0.41 — prose has gone metronomic\"). It VERIFIES that the asserted voice is statistically true per issue. Gates off with fewer than 3 issues drafted (σ is meaningless). No LLM cost.",
+ "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.",
scope: 'series',
kind: 'deterministic',
category: 'style',
@@ -1020,8 +1020,11 @@ export const proseStyleChecks = [
configSchema: z.object({
// How many σ from the series mean before an issue's metric is flagged.
sigmaThreshold: z.number().min(0.5).max(4).default(1.5),
- // Minimum issues drafted before the check runs (σ is meaningless below 3).
- minIssues: z.number().int().min(3).max(30).default(3),
+ // Minimum issues drafted before the check runs. Defaults to 4: at N=3 the
+ // largest possible σ-distance is √2 ≈ 1.41, below the default 1.5σ
+ // threshold, so a 3-issue series could never flag. An explicit 3 is honored
+ // (useful only with a lower threshold).
+ minIssues: z.number().int().min(3).max(30).default(4),
// Cap findings per run so a wildly-uneven series can't flood the review.
maxFindings: z.number().int().min(1).max(50).default(12),
// Optional vocabulary "wells" — register categories to track coverage of,
@@ -1045,7 +1048,7 @@ export const proseStyleChecks = [
min: 3,
max: 30,
step: 1,
- help: 'The check stays off until at least this many issues are drafted — below 3 the standard deviation is meaningless and every issue reads as an outlier.',
+ help: 'The check stays off until at least this many issues are drafted. It defaults to 4 because the biggest σ-distance a series of N issues can show is √(N−1), and at 3 issues that (√2 ≈ 1.41) falls below the default 1.5σ threshold — so a 3-issue series can never flag drift unless you also lower the threshold.',
},
{
key: 'maxFindings',
@@ -1069,7 +1072,7 @@ export const proseStyleChecks = [
const wells = parseVoiceWells(cfg.vocabularyWells || '');
const drift = computeVoiceDrift(ctx.manuscript, {
threshold: cfg.sigmaThreshold ?? 1.5,
- minIssues: cfg.minIssues ?? 3,
+ minIssues: cfg.minIssues ?? 4,
wells,
});
if (drift.gatedOff) return [];
diff --git a/server/lib/editorial/voiceFingerprint.js b/server/lib/editorial/voiceFingerprint.js
index 8230e8cd1d..4c0c76d1d4 100644
--- a/server/lib/editorial/voiceFingerprint.js
+++ b/server/lib/editorial/voiceFingerprint.js
@@ -154,8 +154,10 @@ export function computeFingerprint(text, opts = {}) {
const paragraphs = splitParagraphs(src);
// Sentence-length metrics (words per sentence via the shared word tokenizer, so
- // "the cat's" counts identically to every other check).
- const sentenceLengths = sentences.map((s) => tokenizeWords(s.text).length);
+ // "the cat's" counts identically to every other check). Tokenize each sentence
+ // ONCE — both the length pass and the dominant-opener pass below read this.
+ const sentenceTokenLists = sentences.map((s) => tokenizeWords(s.text));
+ const sentenceLengths = sentenceTokenLists.map((toks) => toks.length);
const sMean = meanOf(sentenceLengths);
const sStd = stdOf(sentenceLengths, sMean);
const sCount = sentenceLengths.length;
@@ -195,11 +197,10 @@ export function computeFingerprint(text, opts = {}) {
// Dominant sentence-opener share: the most common sentence-initial word, as a
// fraction of sentences. High = every sentence opens the same way ("He … He …").
const openerCounts = new Map();
- for (const s of sentences) {
- const first = tokenizeWords(s.text)[0];
+ for (const toks of sentenceTokenLists) {
+ const first = toks[0];
if (!first) continue;
- const key = first.lower;
- openerCounts.set(key, (openerCounts.get(key) || 0) + 1);
+ openerCounts.set(first.lower, (openerCounts.get(first.lower) || 0) + 1);
}
let dominantOpener = 0;
for (const c of openerCounts.values()) if (c > dominantOpener) dominantOpener = c;
@@ -229,8 +230,12 @@ export function computeFingerprint(text, opts = {}) {
}
// Split the stitched manuscript into per-issue text blocks on the `# Issue N`
-// headers the manuscript stitcher emits (the same header shape
-// `conflictIntensityTally` in checkInfra.js keys on). Duplicate issue numbers (a
+// headers the manuscript stitcher emits. The header pattern intentionally mirrors
+// `conflictIntensityTally` in checkInfra.js (its own local `headerRe`) — kept as a
+// parallel literal here rather than a shared `/g` constant on purpose: a single
+// exported `/g` regex instance carries mutable `lastIndex` state, so two `.exec`
+// callers in different modules would corrupt each other's scan. If the stitcher's
+// header shape ever changes, update both. Duplicate issue numbers (a
// chunk boundary that repeats a header) accumulate into ONE block so an issue
// isn't split into two thin, noisy fingerprints. Returns [] when there are no
// headers (the drift check then gates off — a single unlabelled blob can't drift
@@ -310,7 +315,7 @@ export function describeDrift(o) {
const val = `${o.value}${o.unit || ''}`;
const mean = `${round2(o.mean)}${o.unit || ''}`;
return `Issue ${o.issue}'s ${label} is ${val} vs the series mean of ${mean} `
- + `(${o.z.toFixed(1)}σ ${o.direction === 'high' ? 'above' : 'below'}) — ${dir}. `
+ + `(${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.';
}
@@ -319,9 +324,15 @@ export function describeDrift(o) {
* structured results the `style.voice-drift` check maps to editorial findings (so
* the severity/config policy lives in the check, not here).
*
- * Small-N gate: with fewer than `minIssues` issues drafted, σ is meaningless
- * (a two-point "series" always shows each point as ±1σ), so the check gates OFF
- * and emits nothing — `{ gatedOff: true, issueCount, outliers: [] }`.
+ * Small-N gate: with fewer than `minIssues` issues drafted, σ is too small to be
+ * meaningful, so the check gates OFF and emits nothing — `{ gatedOff: true,
+ * issueCount, outliers: [] }`. The default `minIssues` is 4, not 3, because the
+ * LARGEST possible population z-score for N points is √(N−1) (one issue vs the
+ * rest identical): at N=3 that ceiling is √2 ≈ 1.41 — below the default 1.5σ
+ * threshold, so a 3-issue series could NEVER flag drift and the check would
+ * silently be a no-op. At N=4 the ceiling is √3 ≈ 1.73, so drift is reachable. An
+ * explicit `minIssues: 3` is still honored (it only matters with a lower
+ * `threshold` — e.g. 1.0, where √2 clears it).
*
* 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
@@ -338,9 +349,17 @@ export function describeDrift(o) {
*/
export function computeVoiceDrift(manuscript, opts = {}) {
const threshold = Number.isFinite(opts.threshold) && opts.threshold > 0 ? opts.threshold : 1.5;
- const minIssues = Number.isInteger(opts.minIssues) && opts.minIssues >= 3 ? opts.minIssues : 3;
- const matrix = voiceFingerprintMatrix(manuscript, { wells: opts.wells });
- const { issues, metricKeys } = matrix;
+ const minIssues = Number.isInteger(opts.minIssues) && opts.minIssues >= 3 ? opts.minIssues : 4;
+ const fullMatrix = voiceFingerprintMatrix(manuscript, { wells: opts.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
+ // issue as a wild outlier on every metric. Drift is computed over the drafted
+ // issues only; the matrix returned is likewise restricted so renderFingerprintTable
+ // agrees with the stats.
+ const issues = fullMatrix.issues.filter((it) => it.words > 0 && it.sentences > 0);
+ const matrix = { ...fullMatrix, issues };
+ const { metricKeys } = matrix;
if (issues.length < minIssues) {
return { gatedOff: true, issueCount: issues.length, threshold, matrix, series: {}, outliers: [] };
diff --git a/server/lib/editorial/voiceFingerprint.test.js b/server/lib/editorial/voiceFingerprint.test.js
index bf0497c6f7..63696988b8 100644
--- a/server/lib/editorial/voiceFingerprint.test.js
+++ b/server/lib/editorial/voiceFingerprint.test.js
@@ -155,6 +155,35 @@ describe('computeVoiceDrift', () => {
expect(drift.outliers).toEqual([]);
});
+ it('excludes empty / not-yet-drafted issue sections from the gate and stats', () => {
+ // Three drafted issues + one empty stub header → only 3 contentful issues,
+ // below the default minIssues of 4, so the check gates off rather than
+ // treating the stub as a fourth issue.
+ const withStub = manuscriptOf([issueBlock(3, 5), issueBlock(3, 5), issueBlock(3, 5)]) + '\n\n# Issue 4\n\n ';
+ const gated = computeVoiceDrift(withStub);
+ expect(gated.gatedOff).toBe(true);
+ expect(gated.issueCount).toBe(3);
+
+ // Four drafted issues + an empty stub → the stub is neither counted toward
+ // the gate nor flagged as a (wild all-zero) outlier.
+ const withStub2 = manuscriptOf([issueBlock(3, 5), issueBlock(3, 5), issueBlock(3, 5), issueBlock(3, 5)]) + '\n\n# Issue 5\n\n';
+ const drift = computeVoiceDrift(withStub2);
+ expect(drift.gatedOff).toBe(false);
+ expect(drift.issueCount).toBe(4);
+ expect(drift.outliers.some((o) => o.issue === 5)).toBe(false);
+ });
+
+ it('defaults minIssues to 4 — a 3-issue series gates off (√2 < 1.5σ ceiling)', () => {
+ // Three drafted issues, one drifting. At N=3 the largest possible z is √2 ≈
+ // 1.41, below the default 1.5σ threshold, so the default gate stays closed.
+ const ms = manuscriptOf([issueBlock(3, 5), issueBlock(3, 5), issueBlock(3, 20)]);
+ expect(computeVoiceDrift(ms).gatedOff).toBe(true);
+ // An explicit minIssues:3 with a low enough threshold can still flag (√2 clears 1.0).
+ const opened = computeVoiceDrift(ms, { minIssues: 3, threshold: 1.0 });
+ expect(opened.gatedOff).toBe(false);
+ expect(opened.outliers.some((o) => o.metricKey === 'sentenceLenMean')).toBe(true);
+ });
+
it('flags the outlier issue on sentence-length mean with hand-computed σ', () => {
// 3 issues at mean 5, 1 issue at mean 20 → values [5,5,5,20].
// mean = 8.75, σ = √42.1875 ≈ 6.495, z(issue4) = 11.25/6.495 ≈ 1.732 (> 1.5).