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

refactor: share metric-column descriptor from the lib, drop dead config defaults

[._.]/ Adam Eivy86f7dafe3a24
diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.md
index e5682dc8f2..11a60d420b 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). `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`); `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. |
| `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/voiceFingerprint.js b/server/lib/editorial/voiceFingerprint.js
index 4c0c76d1d4..b09b7b0497 100644
--- a/server/lib/editorial/voiceFingerprint.js
+++ b/server/lib/editorial/voiceFingerprint.js
@@ -293,6 +293,15 @@ export function metricLabel(key) {
return desc ? desc.label : key;
}
+// The rendered unit suffix for a metric key (static descriptor unit, or '' for a
+// well). Single source of truth so the drift outlier's `unit`, the finding text,
+// and the matrix column header all agree.
+export function metricUnit(key) {
+ if (typeof key === 'string' && key.startsWith('well:')) return '';
+ const desc = VOICE_METRICS.find((mm) => mm.key === key);
+ return desc ? desc.unit : '';
+}
+
// Directional phrase for a drift: what a value ABOVE / BELOW the series mean means
// for this metric. Wells share a generic phrasing (no static descriptor).
function directionPhrase(key, direction) {
@@ -306,6 +315,29 @@ function directionPhrase(key, direction) {
return direction === 'high' ? desc.higher : desc.lower;
}
+/**
+ * Self-describing column descriptor for a metric key — the label, unit, and the
+ * plain-language phrasing for a value that runs high vs low against the series
+ * mean, plus whether it's a vocabulary well. The single source of truth for
+ * rendering a fingerprint-matrix column header (server and client), built on the
+ * same `metricLabel` / `directionPhrase` / `metricUnit` primitives the finding
+ * text (`describeDrift`) uses — so header tooltips can't silently diverge from the
+ * finding cards.
+ *
+ * @param {string} key
+ * @returns {{ key: string, label: string, unit: string, higher: string, lower: string, isWell: boolean }}
+ */
+export function describeMetricColumn(key) {
+ return {
+ key,
+ label: metricLabel(key),
+ unit: metricUnit(key),
+ higher: directionPhrase(key, 'high'),
+ lower: directionPhrase(key, 'low'),
+ isWell: typeof key === 'string' && key.startsWith('well:'),
+ };
+}
+
// One-sentence finding text for a drift outlier — names the issue, the metric,
// the issue value vs the series mean, the σ distance, and the plain-language
// direction ("prose has gone metronomic").
@@ -367,11 +399,6 @@ export function computeVoiceDrift(manuscript, opts = {}) {
const series = {};
const outliers = [];
- const unitOf = (key) => {
- if (typeof key === 'string' && key.startsWith('well:')) return '';
- const d = VOICE_METRICS.find((mm) => mm.key === key);
- return d ? d.unit : '';
- };
for (const key of metricKeys) {
const values = issues.map((it) => it.metrics[key] ?? 0);
@@ -394,7 +421,7 @@ export function computeVoiceDrift(manuscript, opts = {}) {
std,
z,
direction: z > 0 ? 'high' : 'low',
- unit: unitOf(key),
+ unit: metricUnit(key),
});
}
}
diff --git a/server/routes/pipeline/editorial.js b/server/routes/pipeline/editorial.js
index cdf5d435e7..faf68575cd 100644
--- a/server/routes/pipeline/editorial.js
+++ b/server/routes/pipeline/editorial.js
@@ -53,18 +53,15 @@ 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.
+// not just the flagged outliers that surface as editorial findings. The service's
+// `getSeries` guard is the single id-validity check (mirrors the sibling routes)
+// — an unknown/blank id resolves to a mapped 404.
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); });
+ const result = await voiceFingerprint.getVoiceFingerprint(req.params.id).catch((err) => { throw mapServiceError(err); });
res.json(result);
}));
diff --git a/server/services/pipeline/voiceFingerprint.js b/server/services/pipeline/voiceFingerprint.js
index 6869b2f50c..992e613b2d 100644
--- a/server/services/pipeline/voiceFingerprint.js
+++ b/server/services/pipeline/voiceFingerprint.js
@@ -26,8 +26,7 @@ import {
import {
computeVoiceDrift,
parseVoiceWells,
- metricLabel,
- VOICE_METRICS,
+ describeMetricColumn,
} from '../../lib/editorial/voiceFingerprint.js';
// The deterministic check whose per-series config (threshold / minIssues /
@@ -36,46 +35,20 @@ import {
// 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`.
+ * hand-edited or absent slice. `resolveCheckConfig` validates the stored slice
+ * through the check's Zod `configSchema`, so every key comes back populated with
+ * its schema default when unset — the caller can trust the fields are present.
+ * (`style.voice-drift` is statically registered, so `getCheckById` never misses.)
*
* @param {object} [settings] pre-loaded settings (optional; fetched when omitted)
- * @returns {Promise<{ sigmaThreshold: number, minIssues: number, vocabularyWells: string }>}
+ * @returns {Promise<{ sigmaThreshold: number, minIssues: number, vocabularyWells: string, maxFindings: number }>}
*/
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);
}
@@ -89,7 +62,7 @@ export async function resolveVoiceDriftConfig(settings) {
* @param {string} seriesId
* @returns {Promise<{
* seriesId: string,
- * config: { sigmaThreshold: number, minIssues: number, vocabularyWells: string },
+ * config: object,
* wells: string[],
* columns: Array<{ key, label, unit, higher, lower, isWell }>,
* gatedOff: boolean,
@@ -109,26 +82,20 @@ export async function getVoiceFingerprint(seriesId) {
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,
+ // `cfg` is schema-validated, so sigmaThreshold/minIssues/vocabularyWells are
+ // always present (defaults applied by resolveCheckConfig) — no `??` needed.
+ const drift = computeVoiceDrift(sectionsCorpus(sections), {
+ threshold: cfg.sigmaThreshold,
+ minIssues: cfg.minIssues,
+ wells: parseVoiceWells(cfg.vocabularyWells),
});
- const columns = (drift.matrix.metricKeys || []).map(describeColumn);
-
return {
seriesId,
- config: {
- sigmaThreshold: cfg.sigmaThreshold ?? 1.5,
- minIssues: cfg.minIssues ?? 4,
- vocabularyWells: cfg.vocabularyWells || '',
- },
+ config: cfg,
wells: drift.matrix.wells || [],
- columns,
+ columns: (drift.matrix.metricKeys || []).map(describeMetricColumn),
gatedOff: drift.gatedOff,
issueCount: drift.issueCount,
threshold: drift.threshold,