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([issue-2165]): deterministic slop score + burstiness metrics
Adam Eivy2d0eaecf3edc
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0a8773e9ed..a80237d847 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,5 +1,9 @@# Unreleased Changes+## 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.+## Human Activity Tracking- **[issue-2150] Activity timeline** — a new `/timeline` page shows a unified, day-by-day view of your activity (emails sent/received and calendar events, with more sources coming), backed by a machine-local `human_activity_events` store that your existing message and calendar syncs populate automatically. Pick any day (deep-linkable via `/timeline/:date`), see an hourly activity histogram and per-source tallies, and browse the day's events. Only metadata and a short summary line are stored — full message bodies stay in their per-source caches — and the timeline is machine-local (never federated to peers), like Tribe.diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.mdindex 537ac2a132..5a1dfa6181 100644--- a/server/lib/editorial/README.md+++ b/server/lib/editorial/README.md@@ -195,12 +195,13 @@ runner-injected `ctx.callInlineLLM` (an inline-prompt sibling of|---|---|| `checkRegistry.js` | The public entry point. Assembles `EDITORIAL_CHECKS` by spreading the per-category arrays from `./checks/*.js`, re-exports the shared infra from `./checkInfra.js`, and keeps the registry's lookup/state helpers that need the assembled array: `EDITORIAL_SOURCES` (the per-check `sources` vocabulary the staleness runner fingerprints, #1387), fail-fast guards (`assertValidChecks`), and `getCheck`, `getCheckById`, `getAllChecks`, `listChecks`, `resolveCheckState`, `getEnabledChecks`, `resolveCheckConfig`, `orderChecksByDependencies` (the dependency topo-sort, #1627) plus the user-defined-check helpers (`buildCustomCheck`, `readCustomCheckDefs`, `isCustomCheckId`, `isValidCustomCheckDef`). Decomposed from a 7,474-line god file in #1829. || `checkInfra.js` | Shared check infrastructure extracted in #1829: imports + constants + stage names + the pure summary/helper functions (e.g. `runManuscriptLlmCheck`, `canonCharacterTraitsSummary`, `editorialFindingKey`, `buildCustomCheckPrompt`, `normalizeCheckScopes`/`primaryCheckScope`) that the check definitions and the registry tail depend on. Kept side-effect-free so `./checks/*.js` import from it without a cycle through `checkRegistry.js` (whose `EDITORIAL_CHECKS` spread would otherwise hit a TDZ on the checks' eagerly-evaluated `configSchema`s). Re-exports its externals (zod + the sibling primitive modules) so a check file imports everything from one hub. |-| `checks/*.js` | The 68 `EDITORIAL_CHECKS` definitions, grouped by category (#1829): `naming`, `cast`, `pov`, `characterArc`, `continuity`, `comic`, `visual`, `scene`, `dialogue`, `proseStyle`, `research`. Each exports a `<group>Checks` array of declarative check entries (scope, kind, severity, `configSchema`, `gate`, `run(ctx)`); `checkRegistry.js` imports and spreads them. Internal to the registry — imported only via `checkRegistry.js`, not the barrel. |+| `checks/*.js` | The `EDITORIAL_CHECKS` definitions, grouped by category (#1829): `naming`, `cast`, `pov`, `characterArc`, `continuity`, `comic`, `visual`, `scene`, `dialogue`, `proseStyle`, `research`, `slop` (#2165 — `prose.slop-banned-words`/`prose.ai-tells`/`prose.structural-tics`/`prose.burstiness`, built on `../slopScore.js`). Each exports a `<group>Checks` array of declarative check entries (scope, kind, severity, `configSchema`, `gate`, `run(ctx)`); `checkRegistry.js` imports and spreads them. Internal to the registry — imported only via `checkRegistry.js`, not the barrel. || `nameSimilarity.js` | Pure, dependency-free name-confusability primitives for `naming.dissimilar-names` (#1291): `normalizeName`, `vowelSkeleton`, `soundex` (phonetic key), `levenshtein` (edit distance), `nameSimilaritySignals` (the per-pair signal list, with option toggles), and `firstLetterHistogram` / `findFirstLetterClusters` (cast first-letter crowding). || `cliches.js` | Pure, dependency-free cliché + overwriting primitives for `prose.cliches` and `prose.modifier-stacking` (#1308): `CLICHE_PHRASES` (seed stock-simile/idiom list), `findCliches` (whole-word phrase scan with house-style allow/extra lists), and `findModifierStacking` (cumulative no-comma runs of 3+ stacked adjectives/adverbs). The LLM sibling `prose.dead-metaphor` handles the judgment cases (mixed/dead metaphor, novel clichés, purple prose). || `italicThoughts.js` | Pure, dependency-free italic-thought primitive for `prose.italic-thoughts` (#1300): `findItalicThoughts` (multi-word markdown `*…*` / `_…_` italic runs, dedup + word-count threshold so single-word emphasis, bold, and `snake_case` are skipped). The LLM siblings (`opening.wrong-start`, `prose.mirror-description`, `dialogue.pleasantries`, `prose.kill-your-darlings`) handle the judgment cases in the #1300 anti-pattern bundle. || `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`. || `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/checkInfra.js b/server/lib/editorial/checkInfra.jsindex 309d6dcf79..4e083105cd 100644--- a/server/lib/editorial/checkInfra.js+++ b/server/lib/editorial/checkInfra.js@@ -35,6 +35,21 @@ import {findRepeatedOpeners,measureSentenceRhythm,} from './repetition.js';+import {+ findBannedWordsTier1,+ findSuspiciousWordClusters,+ findAiTells,+ findNotJustButPatterns,+ findNotSayingPatterns,+ findNegativeAssertions,+ findTheWaySimiles,+ findTriadicShortSentences,+ findStructuralTics,+ emDashDensityPer1000,+ transitionOpenerRatio,+ paragraphLengthUniformity,+ countSectionBreaks,+} from './slopScore.js';import {analyzePanelRhythm,comicPageTurnSummary,@@ -53,10 +68,14 @@ export {authoredRevealSummary,comicPageTurnSummary,comparisonName,+ countSectionBreaks,+ emDashDensityPer1000,estimateTokens,filterPassiveVoice,findAdverbs,+ findAiTells,findAxisReversals,+ findBannedWordsTier1,findCliches,findCrutchWords,findDialogueTagVariety,@@ -66,18 +85,27 @@ export {findHedgeWords,findItalicThoughts,findModifierStacking,+ findNegativeAssertions,+ findNotJustButPatterns,+ findNotSayingPatterns,findPassiveVoice,findRepeatedOpeners,findSaidBookisms,findShotTypeMonotony,+ findStructuralTics,+ findSuspiciousWordClusters,+ findTheWaySimiles,+ findTriadicShortSentences,findUnattributedDialogueRuns,findWordEchoes,measureSentenceRhythm,normalizeName,+ paragraphLengthUniformity,parseComicScript,renderCharacterArcsForPrompt,splitScenes,summarizeStoryboardShots,+ transitionOpenerRatio,z,};diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.jsindex 92029bd8f3..3cf641b7aa 100644--- a/server/lib/editorial/checkRegistry.js+++ b/server/lib/editorial/checkRegistry.js@@ -142,6 +142,7 @@ import { researchChecks } from './checks/research.js';import { characterArcChecks } from './checks/characterArc.js';import { proseStyleChecks } from './checks/proseStyle.js';import { dialogueChecks } from './checks/dialogue.js';+import { slopChecks } from './checks/slop.js';// Canonical display + run order of the built-in checks. Grouping the checks into// ./checks/*.js by category (#1829) would otherwise change the observable order@@ -201,6 +202,10 @@ const CHECK_ORDER = Object.freeze(['prose.repeated-gestures','prose.word-echoes','prose.sentence-rhythm',+ 'prose.slop-banned-words',+ 'prose.ai-tells',+ 'prose.structural-tics',+ 'prose.burstiness','prose.telling-emotion','prose.dead-metaphor','opening.wrong-start',@@ -233,6 +238,7 @@ const ASSEMBLED_CHECKS = [...characterArcChecks,...proseStyleChecks,...dialogueChecks,+ ...slopChecks,];for (const c of ASSEMBLED_CHECKS) {if (!CHECK_ORDER_INDEX.has(c.id)) {diff --git a/server/lib/editorial/checks/slop.js b/server/lib/editorial/checks/slop.jsnew file mode 100644index 0000000000..73f3eaf453--- /dev/null+++ b/server/lib/editorial/checks/slop.js@@ -0,0 +1,327 @@+// Editorial checks — deterministic "AI slop" group (#2165, CWQE Phase 1).+// Each entry is a declarative check; see ../README.md and ../checkInfra.js.+// The pure detectors these checks call live in ../slopScore.js — see that+// module's doc comment for how it EXTENDS (rather than duplicates) the+// existing proseTics.js / cliches.js / repetition.js anti-slop primitives.+import {+ countSectionBreaks,+ countWords,+ emDashDensityPer1000,+ findAiTells,+ findBannedWordsTier1,+ findStructuralTics,+ findSuspiciousWordClusters,+ paragraphLengthUniformity,+ sectionIssue,+ splitPhraseList,+ transitionOpenerRatio,+ z,+} from '../checkInfra.js';++// Problem/suggestion text per structural-tic type, keyed by the `type` field+// findStructuralTics() stamps on each hit.+const STRUCTURAL_TIC_PROBLEMS = {+ 'not-just-but': (h) => `"Not just X, but Y" construction ("${h.anchor}") — the single most overused LLM rhetorical pattern.`,+ 'not-saying': (h) => `"I'm not saying X, I'm saying Y" hedge-then-assert construction ("${h.anchor}").`,+ 'the-way-simile': (h) => `"The way X did Y" implicit-comparison construction ("${h.anchor}") standing in for direct description.`,+ 'triadic-short-sentences': (h) => `${h.count} very short sentences in a row ("${h.anchor}") — the punchy triadic-fragment rhythm LLM prose overuses.`,+ 'negative-assertion-density': (h) => `${h.count} "did not [verb]" negative assertions (about ${h.density}/1000 words) — a dense run of negation reads as a rhetorical tic rather than earned tension.`,+};+const STRUCTURAL_TIC_SUGGESTIONS = {+ 'not-just-but': 'State the point plainly, or vary the construction so it does not recur mechanically.',+ 'not-saying': 'Cut the hedge and state the claim directly.',+ 'the-way-simile': 'Replace with a direct, concrete description of the specific detail.',+ 'triadic-short-sentences': 'Vary sentence length — combine some fragments or add a longer sentence to break the rhythm.',+ 'negative-assertion-density': 'Show what DID happen instead of listing what did not.',+};++export const slopChecks = [+ {+ id: 'prose.slop-banned-words',+ sources: ['manuscript'],+ label: 'Tiered "AI slop" banned-word list',+ description:+ 'Flags overused LLM-generation vocabulary in two tiers: Tier 1 hard-ban words ("delve", "tapestry", "myriad", "plethora", "utilize", "leverage", …) penalized per occurrence (density-scaled), and Tier 2 suspicious words ("robust", "seamless", "pivotal", …) penalized only when 3+ cluster in one paragraph — a lone Tier 2 word is ordinary prose. Deterministic word-list scan; extend or mute per house style.',+ scope: 'issue',+ kind: 'deterministic',+ category: 'style',+ severityDefault: 'low',+ defaultEnabled: true,+ needsManuscript: true,+ configSchema: z.object({+ // Tier 1 per-1000-word rate at/above which a section is flagged.+ tier1DensityPer1000: z.number().min(0).max(50).default(3),+ // Tier 2 occurrences within one paragraph before it reads as a cluster.+ tier2ClusterThreshold: z.number().int().min(2).max(10).default(3),+ maxFindings: z.number().int().min(1).max(50).default(20),+ // House-style allowlist / extra words — applied to BOTH tiers' seed lists.+ allowWords: z.string().default(''),+ extraWords: z.string().default(''),+ }),+ configFields: [+ { key: 'tier1DensityPer1000', label: 'Tier 1 rate to flag (per 1000 words)', type: 'number', min: 0, max: 50, step: 1, help: 'Flag a section whose Tier 1 hard-ban word frequency per 1000 words is at or above this.' },+ { key: 'tier2ClusterThreshold', label: 'Tier 2 cluster size to flag', type: 'number', min: 2, max: 10, step: 1, help: 'How many Tier 2 suspicious words within one paragraph before the cluster is flagged. A lone Tier 2 word is never flagged.' },+ { key: 'maxFindings', label: 'Max findings per run', type: 'number', min: 1, max: 50, step: 1, help: 'Cap findings so a slop-heavy draft can not flood the review.' },+ { key: 'allowWords', label: 'House-style allowlist', type: 'text', help: 'Words to leave alone (comma-separated or one per line) — applies to both tiers.' },+ { key: 'extraWords', label: 'Extra banned words to flag', type: 'text', help: 'Series-specific words to add to the seed lists (comma-separated or one per line) — applies to both tiers.' },+ ],+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,+ run: (ctx) => {+ const cfg = ctx.config || {};+ const max = cfg.maxFindings ?? 20;+ const density = cfg.tier1DensityPer1000 ?? 3;+ const clusterThreshold = cfg.tier2ClusterThreshold ?? 3;+ const allowWords = splitPhraseList(cfg.allowWords);+ const extraWords = splitPhraseList(cfg.extraWords);+ const sections = Array.isArray(ctx.sections) ? ctx.sections : [];+ const findings = [];++ for (const s of sections) {+ if (findings.length >= max) break;+ const text = s?.content || '';+ const { number, location } = sectionIssue(s);++ // Tier 1 — density-scaled, one finding per offending section.+ const words = countWords(text);+ const hits = words > 0 ? findBannedWordsTier1(text, { allowWords, extraWords }) : [];+ if (hits.length) {+ const rate = Math.round((hits.length / words) * 1000 * 10) / 10;+ if (rate >= density) {+ findings.push({+ severity: ctx.severityDefault,+ category: 'style',+ location,+ problem: `${hits.length} Tier 1 "AI slop" word${hits.length === 1 ? '' : 's'} (e.g. "${hits[0].anchor}") — about ${rate}/1000 words. Words like "delve"/"myriad"/"utilize" are recognizable LLM-generation tells.`,+ suggestion: 'Replace with plain, specific vocabulary — or add intentional uses to the allowlist.',+ anchorQuote: hits[0].anchor,+ issueNumber: number,+ });+ }+ }+ if (findings.length >= max) break;++ // Tier 2 — cluster-only, one finding per clustered paragraph.+ const clusters = findSuspiciousWordClusters(text, { allowWords, extraWords, clusterThreshold });+ for (const cluster of clusters) {+ if (findings.length >= max) break;+ findings.push({+ severity: ctx.severityDefault,+ category: 'style',+ location,+ problem: `${cluster.count} suspicious "AI slop" words cluster in one paragraph (${cluster.anchor}) — no single word is a tell, but the density reads synthetic.`,+ suggestion: 'Vary the vocabulary — cut or replace at least one of the clustered words.',+ anchorQuote: cluster.anchor,+ issueNumber: number,+ });+ }+ }++ return findings;+ },+ },+ {+ id: 'prose.ai-tells',+ sources: ['manuscript'],+ label: 'Fiction AI-tell idioms',+ description:+ 'Flags recognizable LLM-generation idioms in fiction prose — "a sense of dread", "couldn\'t help but", "eyes widened", "let out a breath she didn\'t know she\'d been holding", "a wave of relief washed over him", "heart pounded in his chest", and a physical-tell immediately re-labeled with its named emotion. Deterministic regex scan; the LLM siblings (prose.telling-emotion, prose.dead-metaphor) handle novel or judgment-dependent cases.',+ scope: 'issue',+ kind: 'deterministic',+ category: 'style',+ severityDefault: 'medium',+ defaultEnabled: true,+ needsManuscript: true,+ configSchema: z.object({+ maxFindings: z.number().int().min(1).max(50).default(20),+ // Pattern ids to mute (see slopScore.js AI_TELL_PATTERNS).+ allowPatterns: z.string().default(''),+ }),+ configFields: [+ { key: 'maxFindings', label: 'Max findings per run', type: 'number', min: 1, max: 50, step: 1, help: 'Cap findings so a slop-heavy draft can not flood the review.' },+ { key: 'allowPatterns', label: 'Muted AI-tell patterns', type: 'text', help: 'Pattern ids to leave alone (comma-separated or one per line): sense-of, couldnt-help-but, eyes-widened, breath-didnt-know, wave-of-emotion, heart-pounded-chest, physical-named-emotion.' },+ ],+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,+ run: (ctx) => {+ const cfg = ctx.config || {};+ const max = cfg.maxFindings ?? 20;+ const allowPatterns = splitPhraseList(cfg.allowPatterns);+ const sections = Array.isArray(ctx.sections) ? ctx.sections : [];+ const findings = [];+ for (const s of sections) {+ if (findings.length >= max) break;+ const hits = findAiTells(s?.content || '', { allowPatterns });+ const { number, location } = sectionIssue(s);+ for (const hit of hits) {+ if (findings.length >= max) break;+ findings.push({+ severity: ctx.severityDefault,+ category: 'style',+ location,+ problem: `${hit.label} ("${hit.anchor}") — a recognizable LLM-generation idiom.`,+ suggestion: hit.suggestion,+ anchorQuote: hit.anchor,+ issueNumber: number,+ });+ }+ }+ return findings;+ },+ },+ {+ id: 'prose.structural-tics',+ sources: ['manuscript'],+ label: 'Structural rhetorical tics',+ description:+ 'Flags rhetorical constructions LLM-generated prose overuses independent of vocabulary: "not just X, but Y", "I\'m not saying X, I\'m saying Y", a dense run of "did not [verb]" negative assertions, "the way X did Y" implicit-comparison, and runs of very short punchy sentences ("Fast. Precise. Deadly.").',+ scope: 'issue',+ kind: 'deterministic',+ category: 'style',+ severityDefault: 'low',+ defaultEnabled: true,+ needsManuscript: true,+ configSchema: z.object({+ maxFindings: z.number().int().min(1).max(50).default(20),+ // "Fast. Precise. Deadly." run detection.+ triadicMaxWords: z.number().int().min(1).max(10).default(4),+ triadicMinRun: z.number().int().min(3).max(8).default(3),+ // Per-1000-word rate of "did not [verb]" at/above which it is flagged.+ negativeAssertionDensityPer1000: z.number().min(0).max(50).default(4),+ }),+ configFields: [+ { key: 'maxFindings', label: 'Max findings per run', type: 'number', min: 1, max: 50, step: 1, help: 'Cap findings so a tic-heavy draft can not flood the review.' },+ { key: 'triadicMaxWords', label: 'Short-sentence word cap', type: 'number', min: 1, max: 10, step: 1, help: 'A sentence at or under this word count counts as "short" for the triadic-run detector.' },+ { key: 'triadicMinRun', label: 'Short sentences in a row to flag', type: 'number', min: 3, max: 8, step: 1, help: 'How many consecutive short sentences trip the "Fast. Precise. Deadly." flag.' },+ { key: 'negativeAssertionDensityPer1000', label: '"Did not" rate to flag (per 1000 words)', type: 'number', min: 0, max: 50, step: 1, help: 'Flag a section whose "did not [verb]" / "didn\'t [verb]" frequency per 1000 words is at or above this.' },+ ],+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,+ run: (ctx) => {+ const cfg = ctx.config || {};+ const max = cfg.maxFindings ?? 20;+ const opts = {+ maxWords: cfg.triadicMaxWords ?? 4,+ minRun: cfg.triadicMinRun ?? 3,+ negativeAssertionDensityPer1000: cfg.negativeAssertionDensityPer1000 ?? 4,+ };+ const sections = Array.isArray(ctx.sections) ? ctx.sections : [];+ const findings = [];+ for (const s of sections) {+ if (findings.length >= max) break;+ const tics = findStructuralTics(s?.content || '', opts);+ const { number, location } = sectionIssue(s);+ for (const t of tics) {+ if (findings.length >= max) break;+ findings.push({+ severity: ctx.severityDefault,+ category: 'style',+ location,+ problem: STRUCTURAL_TIC_PROBLEMS[t.type](t),+ suggestion: STRUCTURAL_TIC_SUGGESTIONS[t.type],+ anchorQuote: t.anchor,+ issueNumber: number,+ });+ }+ }+ return findings;+ },+ },+ {+ id: 'prose.burstiness',+ sources: ['manuscript'],+ label: 'Structural burstiness (em-dash / transitions / paragraphs / scene breaks)',+ description:+ 'Flags the quantitative structural signals of synthetic uniformity: em-dash overuse, a high rate of essay-style transition-word sentence openers ("However, … Moreover, … Ultimately, …"), runs of paragraphs with near-identical word counts, and an over-fragmented rate of scene/section breaks. Deliberately separate from prose.sentence-rhythm (sentence-length variation, already deterministic there) so the two never double-report the same anchor — this module\'s sentence-length CV signal is folded only into the deterministic slop-score composite (slopScore.js computeSlopPenalty), never reported as its own finding here.',+ scope: 'issue',+ kind: 'deterministic',+ category: 'style',+ severityDefault: 'low',+ defaultEnabled: true,+ needsManuscript: true,+ configSchema: z.object({+ maxFindings: z.number().int().min(1).max(50).default(20),+ emDashThresholdPer1000: z.number().min(0).max(100).default(15),+ transitionRatioThreshold: z.number().min(0).max(1).default(0.3),+ paragraphUniformityMinRun: z.number().int().min(3).max(10).default(3),+ sectionBreakThresholdPer1000: z.number().min(0).max(50).default(8),+ }),+ configFields: [+ { key: 'maxFindings', label: 'Max findings per run', type: 'number', min: 1, max: 50, step: 1, help: 'Cap findings so a heavy draft can not flood the review.' },+ { key: 'emDashThresholdPer1000', label: 'Em-dash rate to flag (per 1000 words)', type: 'number', min: 0, max: 100, step: 1, help: 'Flag a section whose em-dash frequency per 1000 words is at or above this.' },+ { key: 'transitionRatioThreshold', label: 'Transition-opener ratio to flag', type: 'number', min: 0, max: 1, step: 0.05, help: 'Flag a section where more than this fraction of sentences open with an essay-style transition word.' },+ { key: 'paragraphUniformityMinRun', label: 'Uniform paragraphs in a row to flag', type: 'number', min: 3, max: 10, step: 1, help: 'How many consecutive similar-length paragraphs trip the mechanical-cadence flag.' },+ { key: 'sectionBreakThresholdPer1000', label: 'Scene-break rate to flag (per 1000 words)', type: 'number', min: 0, max: 50, step: 1, help: 'Flag a section whose scene/section-break marker frequency per 1000 words is at or above this — over-fragmented pacing.' },+ ],+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,+ run: (ctx) => {+ const cfg = ctx.config || {};+ const max = cfg.maxFindings ?? 20;+ const emDashThreshold = cfg.emDashThresholdPer1000 ?? 15;+ const transitionThreshold = cfg.transitionRatioThreshold ?? 0.3;+ const uniformityMinRun = cfg.paragraphUniformityMinRun ?? 3;+ const sectionBreakThreshold = cfg.sectionBreakThresholdPer1000 ?? 8;+ const sections = Array.isArray(ctx.sections) ? ctx.sections : [];+ const findings = [];+ for (const s of sections) {+ if (findings.length >= max) break;+ const text = s?.content || '';+ const words = countWords(text);+ const { number, location } = sectionIssue(s);++ const emDash = emDashDensityPer1000(text);+ if (findings.length < max && emDash.count > 0 && emDash.rate >= emDashThreshold) {+ findings.push({+ severity: ctx.severityDefault,+ category: 'style',+ location,+ problem: `Em-dash rate of ${emDash.rate}/1000 words (${emDash.count} total) — a heavy em-dash reliance reads as a mechanical punctuation crutch.`,+ suggestion: 'Recast some em-dash breaks as separate sentences, commas, or parentheticals to vary the punctuation texture.',+ anchorQuote: '',+ issueNumber: number,+ });+ }++ const transitions = transitionOpenerRatio(text);+ if (findings.length < max && transitions.total > 0 && transitions.ratio > transitionThreshold) {+ findings.push({+ severity: ctx.severityDefault,+ category: 'style',+ location,+ problem: `${transitions.count} of ${transitions.total} sentences (${Math.round(transitions.ratio * 100)}%) open with an essay-style transition word (e.g. "${transitions.anchor}") — reads as signposting rather than fiction's momentum.`,+ suggestion: 'Cut most transition openers and let the prose\'s own causality carry the connection.',+ anchorQuote: transitions.anchor,+ issueNumber: number,+ });+ }++ if (findings.length < max && words > 0) {+ const breaks = countSectionBreaks(text);+ const breakRate = Math.round((breaks / words) * 1000 * 10) / 10;+ if (breaks > 0 && breakRate >= sectionBreakThreshold) {+ findings.push({+ severity: ctx.severityDefault,+ category: 'style',+ location,+ problem: `${breaks} scene/section breaks (about ${breakRate}/1000 words) — an over-fragmented rate of breaks reads as choppy, mechanical pacing.`,+ suggestion: 'Consolidate some scenes, or replace a hard break with a transitional paragraph.',+ anchorQuote: '',+ issueNumber: number,+ });+ }+ }++ for (const run of paragraphLengthUniformity(text, { minRun: uniformityMinRun })) {+ if (findings.length >= max) break;+ findings.push({+ severity: ctx.severityDefault,+ category: 'style',+ location,+ problem: `${run.count} consecutive paragraphs averaging ${run.avgWords} words each with little variation — a mechanically uniform paragraph cadence.`,+ suggestion: 'Vary paragraph length deliberately — break a long paragraph or combine a few short ones.',+ anchorQuote: run.anchor,+ issueNumber: number,+ });+ }+ }+ return findings;+ },+ },+];diff --git a/server/lib/editorial/index.js b/server/lib/editorial/index.jsindex 9b2a3c6661..db54bcffde 100644--- a/server/lib/editorial/index.js+++ b/server/lib/editorial/index.js@@ -12,3 +12,4 @@ export * from './nameSimilarity.js';export * from './proseTics.js';export * from './repetition.js';export * from './shotContinuity.js';+export * from './slopScore.js';diff --git a/server/lib/editorial/slopScore.js b/server/lib/editorial/slopScore.jsnew file mode 100644index 0000000000..c4151208e1--- /dev/null+++ b/server/lib/editorial/slopScore.js@@ -0,0 +1,593 @@+/**+ * Deterministic slop-scoring primitives (#2165 — CWQE Phase 1) for the editorial+ * check registry. Pure and dependency-free (no side-effecting imports) so it+ * stays unit-testable in isolation — mirrors ./cliches.js / ./proseTics.js /+ * ./repetition.js, whose `tokenizeWords` / `splitSentences` / `measureSentenceRhythm`+ * it reuses rather than re-implementing.+ *+ * This module EXTENDS the existing anti-slop primitives — it deliberately does+ * NOT duplicate:+ * - proseTics.js — filter/hedge/crutch words, -ly adverbs, passive voice,+ * repeated gestures.+ * - cliches.js — stock similes/idioms, cumulative modifier stacking.+ * - repetition.js — word echoes, repeated sentence openers, and sentence-+ * length coefficient of variation (`measureSentenceRhythm`,+ * consumed by the `prose.sentence-rhythm` check).+ *+ * It adds the LLM-generation-specific "slop" signals autonovel's dual-immune-+ * system design catches: a tiered banned-word list, fiction-specific AI-tell+ * phrasing, rhetorical structural tics, and quantitative burstiness signals+ * (em-dash density, transition-opener ratio, paragraph-length uniformity,+ * section-break count). `computeSlopPenalty()` composites all of the above+ * — PLUS the sentence-length CV already measured by repetition.js — into a+ * single 0–10 penalty for Phase 3's `qualityScore = judgeOverall − slopPenalty`.+ *+ * Dedupe note: sentence-length CV is read from `measureSentenceRhythm`+ * (repetition.js) INSIDE `computeSlopPenalty` only — it is deliberately NOT+ * re-exposed as its own registry-check finding here. `prose.sentence-rhythm`+ * already owns that finding/anchor; the `prose.burstiness` check below reports+ * the OTHER quantitative signals (em-dash density, transition-opener ratio,+ * paragraph-length uniformity) so the two checks never double-report the same+ * anchor.+ */++import { tokenizeWords, splitSentences } from './proseTics.js';+import { measureSentenceRhythm } from './repetition.js';++function escapeRegExp(s) {+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}++function normalizeWord(p) {+ return typeof p === 'string' ? p.trim().toLowerCase() : '';+}++function toWordSet(words) {+ return new Set((Array.isArray(words) ? words : []).map(normalizeWord).filter(Boolean));+}++// Build a case-insensitive matcher for a list of single/multi-word (and+// hyphenated) phrase entries — mirrors proseTics.js's buildListMatcher, but+// also tolerates a hyphen where the seed used a space or vice versa+// ("ever-evolving" / "ever evolving") since generated prose is inconsistent+// about which it uses.+function buildListMatcher(seed, opts = {}) {+ const allow = toWordSet(opts.allowWords);+ const extra = (Array.isArray(opts.extraWords) ? opts.extraWords : []).map(normalizeWord).filter(Boolean);+ const seen = new Set();+ const entries = [];+ for (const w of [...seed, ...extra]) {+ const norm = normalizeWord(w);+ if (!norm || seen.has(norm) || allow.has(norm)) continue;+ seen.add(norm);+ entries.push(norm);+ }+ if (!entries.length) return null;+ const alt = entries+ .sort((a, b) => b.length - a.length)+ .map((e) => escapeRegExp(e).replace(/[\s-]+/g, '[\\s-]+'))+ .join('|');+ return new RegExp(`(?<!\\w)(?:${alt})(?!\\w)`, 'gi');+}++// ---------------------------------------------------------------------------+// Tiered banned-word lists.+// ---------------------------------------------------------------------------++// Tier 1 — hard-ban. Overused LLM-generation vocabulary; PENALIZED PER HIT+// regardless of context. Curated, not exhaustive; extendable (extraWords) /+// mutable (allowWords) per house style, mirroring the other word lists in+// this directory.+export const TIER1_BANNED_WORDS = Object.freeze([+ 'delve', 'delves', 'delved', 'delving',+ 'tapestry', 'tapestries',+ 'myriad',+ 'plethora',+ 'utilize', 'utilizes', 'utilized', 'utilizing', 'utilization',+ 'leverage', 'leverages', 'leveraged', 'leveraging',+ 'boasts', 'boasting',+ 'testament',+ 'underscore', 'underscores', 'underscored', 'underscoring',+ 'multifaceted',+ 'intricate', 'intricacies',+ 'nuanced',+ 'unprecedented',+ 'ever-evolving',+ 'game-changer',+ 'cutting-edge',+ 'in the realm of',+ 'in the world of',+ 'navigate the complexities of',+ 'stands as a testament',+]);++// Tier 2 — suspicious. Common enough in ordinary prose that a lone occurrence+// is not a tell; only a CLUSTER of `clusterThreshold`+ within one paragraph+// reads as synthetic (findSuspiciousWordClusters below).+export const TIER2_SUSPICIOUS_WORDS = Object.freeze([+ 'robust', 'seamless', 'seamlessly', 'pivotal', 'vibrant', 'profound',+ 'resonate', 'resonates', 'resonated', 'resonating', 'resonance',+ 'illuminate', 'illuminates', 'illuminated', 'illuminating',+ 'embark', 'embarks', 'embarked', 'embarking',+ 'foster', 'fosters', 'fostered', 'fostering',+ 'bolster', 'bolsters', 'bolstered', 'bolstering',+ 'palpable', 'poignant', 'visceral', 'evocative', 'ethereal',+]);++/**+ * Tier 1 hard-ban occurrences — one entry per match (every hit counts, unlike+ * the deduped cliché scanner, mirroring proseTics.js's density-scaled word+ * lists).+ * @param {string} text+ * @param {{ allowWords?: string[], extraWords?: string[] }} [opts]+ * @returns {Array<{ entry: string, index: number, anchor: string }>}+ */+export function findBannedWordsTier1(text, opts = {}) {+ if (typeof text !== 'string' || !text) return [];+ const matcher = buildListMatcher(TIER1_BANNED_WORDS, opts);+ if (!matcher) return [];+ const out = [];+ let m;+ while ((m = matcher.exec(text)) !== null) {+ out.push({ entry: m[0].toLowerCase().replace(/[\s-]+/g, ' '), index: m.index, anchor: m[0] });+ }+ return out;+}++/**+ * Paragraph splitter — mirrors dialogue.js's `findUnattributedDialogueRuns`+ * paragraph split (manuscript prose is stored one paragraph per line,+ * separated by blank lines): each non-blank line is one paragraph, with its+ * absolute character offset.+ * @param {string} text+ * @returns {Array<{ text: string, index: number }>}+ */+export function splitParagraphs(text) {+ if (typeof text !== 'string' || !text) return [];+ const out = [];+ const re = /[^\n]+/g;+ let m;+ while ((m = re.exec(text)) !== null) {+ if (m[0].trim()) out.push({ text: m[0], index: m.index });+ }+ return out;+}++/**+ * Tier 2 suspicious-word CLUSTERS — one finding per paragraph carrying+ * `clusterThreshold`+ distinct-or-repeated Tier 2 hits. An isolated Tier 2+ * word elsewhere in the paragraph is not reported.+ * @param {string} text+ * @param {{ allowWords?: string[], extraWords?: string[], clusterThreshold?: number }} [opts]+ * @returns {Array<{ words: string[], count: number, index: number, anchor: string }>}+ */+export function findSuspiciousWordClusters(text, opts = {}) {+ if (typeof text !== 'string' || !text) return [];+ const clusterThreshold = Number.isInteger(opts.clusterThreshold) && opts.clusterThreshold > 0+ ? opts.clusterThreshold+ : 3;+ const matcher = buildListMatcher(TIER2_SUSPICIOUS_WORDS, opts);+ if (!matcher) return [];+ const paragraphs = splitParagraphs(text);+ const out = [];+ for (const p of paragraphs) {+ matcher.lastIndex = 0;+ const hits = [];+ let m;+ while ((m = matcher.exec(p.text)) !== null) {+ hits.push({ word: m[0].toLowerCase(), index: p.index + m.index, anchor: m[0] });+ }+ if (hits.length >= clusterThreshold) {+ out.push({+ words: hits.map((h) => h.word),+ count: hits.length,+ index: hits[0].index,+ anchor: hits.map((h) => h.anchor).join(', '),+ });+ }+ }+ return out;+}++// ---------------------------------------------------------------------------+// Fiction AI-tell regexes — recognizable idioms/constructions that recur+// across LLM-generated prose. One finding per DISTINCT pattern (first+// occurrence) — a recurring idiom is one tic to fix, not many, mirroring+// cliches.js's dedupe-to-first-occurrence philosophy.+// ---------------------------------------------------------------------------+export const AI_TELL_PATTERNS = Object.freeze([+ {+ id: 'sense-of',+ label: 'vague "a sense of X" telling',+ re: /\ba sense of\s+[a-z]+(?:\s+[a-z]+){0,2}/gi,+ suggestion: 'Replace the vague abstraction with a concrete, dramatized detail specific to this moment.',+ },+ {+ id: 'couldnt-help-but',+ label: '"couldn\'t help but" hedge-tell',+ re: /\bcould(?:n'?t| not) help but\b/gi,+ suggestion: 'Commit to the action directly — cut the hedge and just show the character doing it.',+ },+ {+ id: 'eyes-widened',+ label: '"eyes widened" stock reaction',+ re: /\beyes?\s+widened\b/gi,+ suggestion: 'Vary the physical reaction, or cut it and let the dialogue/context carry the surprise.',+ },+ {+ id: 'breath-didnt-know',+ label: '"let out a breath (s)he didn\'t know" idiom',+ re: /\blet out (?:a|the) breath\b[^.!?\n]{0,60}\b(?:holding|held)\b/gi,+ suggestion: 'This idiom is now a recognizable AI tic — cut it or write the release of tension in fresher terms.',+ },+ {+ id: 'wave-of-emotion',+ label: '"a wave of X washed over" idiom',+ re: /\ba wave of\s+[a-z]+\s+(?:washed|crashed|swept) over\b/gi,+ suggestion: 'Dramatize the feeling through action or dialogue instead of naming an abstract wave.',+ },+ {+ id: 'heart-pounded-chest',+ label: '"heart pounded in his/her chest" stock tell',+ re: /\bheart\s+(?:pounded|hammered|thudded|slammed|raced)\s+(?:in|against)\s+(?:his|her|their|my|its)\s+chest\b/gi,+ suggestion: 'The chest location is implied — cut it, or ground the physical sensation in something more specific.',+ },+ {+ id: 'physical-named-emotion',+ label: 'physical tell immediately re-labeled with the named emotion',+ re: /\b(?:heart\s+\w+ed|throat\s+(?:tightened|closed)|stomach\s+(?:knotted|dropped|twisted)|chest\s+tightened)\b[^.!?\n]{0,30}\b(?:with|from|in)\b[^.!?\n]{0,15}\b(?:fear|joy|excitement|sadness|anger|grief|dread|anxiety|panic|relief|happiness|nervousness)\b/gi,+ suggestion: 'Pick one — the physical detail already shows the feeling; naming the emotion on top of it is double-dipping (show, don\'t also tell).',+ },+]);++/**+ * Fiction AI-tell occurrences — one per distinct pattern id (first+ * occurrence), position-ordered.+ * @param {string} text+ * @param {{ allowPatterns?: string[] }} [opts] allowPatterns — pattern `id`s to mute.+ * @returns {Array<{ id: string, label: string, index: number, anchor: string, suggestion: string }>}+ */+export function findAiTells(text, opts = {}) {+ if (typeof text !== 'string' || !text) return [];+ const allow = new Set((Array.isArray(opts.allowPatterns) ? opts.allowPatterns : []).map(normalizeWord));+ const out = [];+ for (const pattern of AI_TELL_PATTERNS) {+ if (allow.has(pattern.id)) continue;+ pattern.re.lastIndex = 0;+ const m = pattern.re.exec(text);+ if (m) out.push({ id: pattern.id, label: pattern.label, index: m.index, anchor: m[0], suggestion: pattern.suggestion });+ }+ return out.sort((a, b) => a.index - b.index);+}++// ---------------------------------------------------------------------------+// Structural tics — rhetorical constructions that recur across LLM-generated+// prose independent of vocabulary choice.+// ---------------------------------------------------------------------------++const NOT_JUST_BUT_RE = /\bnot\s+(?:just|only)\b[^.!?\n]{1,100}?\bbut\b(?:\s+also)?[^.!?\n]{1,100}?[.!?]/gi;+const NOT_SAYING_RE = /\bI'?m\s+not\s+saying\b[^.!?\n]{1,100}?\bI'?m\s+saying\b[^.!?\n]{1,100}?[.!?]/gi;+const NEGATIVE_ASSERTION_RE = /\b(?:did|does)\s+not\s+[a-z]+\b|\b(?:didn'?t|doesn'?t)\s+[a-z]+\b/gi;+const THE_WAY_RE = /\bthe\s+way\s+(?:[a-z']+\s+){1,4}?(?:[a-z]+(?:ed|ing)|did|does|would|had|has|was|were|is|are|could|can|might|should)\b/gi;++/**+ * "Not just X, but Y" rhetorical construction — the single most overused LLM+ * sentence pattern.+ * @param {string} text+ * @returns {Array<{ index: number, anchor: string }>}+ */+export function findNotJustButPatterns(text) {+ if (typeof text !== 'string' || !text) return [];+ NOT_JUST_BUT_RE.lastIndex = 0;+ const out = [];+ let m;+ while ((m = NOT_JUST_BUT_RE.exec(text)) !== null) {+ out.push({ index: m.index, anchor: m[0].trim() });+ }+ return out;+}++/**+ * "I'm not saying X, I'm saying Y" hedge-then-assert construction.+ * @param {string} text+ * @returns {Array<{ index: number, anchor: string }>}+ */+export function findNotSayingPatterns(text) {+ if (typeof text !== 'string' || !text) return [];+ NOT_SAYING_RE.lastIndex = 0;+ const out = [];+ let m;+ while ((m = NOT_SAYING_RE.exec(text)) !== null) {+ out.push({ index: m.index, anchor: m[0].trim() });+ }+ return out;+}++/**+ * "Did not [verb]" / "didn't [verb]" negative-assertion occurrences (raw —+ * density is the tic, not any single occurrence; callers scale by frequency).+ * @param {string} text+ * @returns {Array<{ index: number, anchor: string }>}+ */+export function findNegativeAssertions(text) {+ if (typeof text !== 'string' || !text) return [];+ NEGATIVE_ASSERTION_RE.lastIndex = 0;+ const out = [];+ let m;+ while ((m = NEGATIVE_ASSERTION_RE.exec(text)) !== null) {+ out.push({ index: m.index, anchor: m[0] });+ }+ return out;+}++/**+ * "The way [subject] [verb]" implicit-comparison construction ("the way her+ * voice cracked", "the way he carried himself") — overused as a substitute for+ * direct description.+ * @param {string} text+ * @returns {Array<{ index: number, anchor: string }>}+ */+export function findTheWaySimiles(text) {+ if (typeof text !== 'string' || !text) return [];+ THE_WAY_RE.lastIndex = 0;+ const out = [];+ let m;+ while ((m = THE_WAY_RE.exec(text)) !== null) {+ out.push({ index: m.index, anchor: m[0] });+ }+ return out;+}++function countSentenceWords(s) {+ return (s.match(/[A-Za-z][A-Za-z']*/g) || []).length;+}++/**+ * Runs of `minRun`+ consecutive very short sentences ("Fast. Precise.+ * Deadly.") — the punchy triadic-fragment rhythm LLM prose overuses.+ * @param {string} text+ * @param {{ maxWords?: number, minRun?: number }} [opts]+ * maxWords — a sentence at/under this word count counts as "short" (default 4).+ * minRun — consecutive short sentences before a run is flagged (default 3, min 3).+ * @returns {Array<{ index: number, anchor: string, count: number }>}+ */+export function findTriadicShortSentences(text, opts = {}) {+ const sentences = splitSentences(text);+ if (sentences.length < 3) return [];+ const maxWords = Number.isInteger(opts.maxWords) && opts.maxWords > 0 ? opts.maxWords : 4;+ const minRun = Math.max(3, Number.isInteger(opts.minRun) ? opts.minRun : 3);+ const out = [];+ let runStart = -1;+ let runCount = 0;+ const flush = (endIdx) => {+ if (runCount >= minRun && runStart >= 0) {+ out.push({+ index: sentences[runStart].index,+ anchor: sentences.slice(runStart, endIdx).map((s) => s.text).join(' '),+ count: runCount,+ });+ }+ runStart = -1;+ runCount = 0;+ };+ for (let i = 0; i < sentences.length; i += 1) {+ const wc = countSentenceWords(sentences[i].text);+ if (wc > 0 && wc <= maxWords) {+ if (runStart === -1) runStart = i;+ runCount += 1;+ } else {+ flush(i);+ }+ }+ flush(sentences.length);+ return out;+}++/**+ * Combined structural-tic scan — merges the four per-pattern detectors above,+ * plus a density-gated negative-assertion entry (only included when the+ * `did not [verb]` rate crosses `negativeAssertionDensityPer1000`, since that+ * signal is a rate, not a per-hit tic). Position-ordered.+ * @param {string} text+ * @param {{ maxWords?: number, minRun?: number, negativeAssertionDensityPer1000?: number }} [opts]+ * @returns {Array<{ type: string, index: number, anchor: string, count?: number, density?: number }>}+ */+export function findStructuralTics(text, opts = {}) {+ if (typeof text !== 'string' || !text) return [];+ const out = [+ ...findNotJustButPatterns(text).map((h) => ({ type: 'not-just-but', ...h })),+ ...findNotSayingPatterns(text).map((h) => ({ type: 'not-saying', ...h })),+ ...findTheWaySimiles(text).map((h) => ({ type: 'the-way-simile', ...h })),+ ...findTriadicShortSentences(text, opts).map((h) => ({ type: 'triadic-short-sentences', ...h })),+ ];+ const negAssertions = findNegativeAssertions(text);+ if (negAssertions.length) {+ const words = tokenizeWords(text).length;+ const density = words > 0 ? (negAssertions.length / words) * 1000 : 0;+ const threshold = typeof opts.negativeAssertionDensityPer1000 === 'number'+ ? opts.negativeAssertionDensityPer1000+ : 4;+ if (density >= threshold) {+ out.push({+ type: 'negative-assertion-density',+ index: negAssertions[0].index,+ anchor: negAssertions[0].anchor,+ count: negAssertions.length,+ density: Math.round(density * 10) / 10,+ });+ }+ }+ return out.sort((a, b) => a.index - b.index);+}++// ---------------------------------------------------------------------------+// Quantitative / statistical burstiness signals.+// ---------------------------------------------------------------------------++/**+ * Em-dash density per 1000 words. AI-generated prose leans heavily on the em+ * dash as an all-purpose punctuation crutch; a genuinely varied human draft+ * rarely sustains a high rate across a whole passage.+ * @param {string} text+ * @returns {{ count: number, words: number, rate: number }}+ */+export function emDashDensityPer1000(text) {+ if (typeof text !== 'string' || !text) return { count: 0, words: 0, rate: 0 };+ const words = tokenizeWords(text).length;+ const count = (text.match(/—/g) || []).length;+ const rate = words > 0 ? Math.round((count / words) * 1000 * 10) / 10 : 0;+ return { count, words, rate };+}++// Seed transition-opener vocabulary — sentence-initial connective tissue that,+// overused, reads as an essay's signposting rather than fiction's momentum.+export const TRANSITION_OPENERS = Object.freeze([+ 'however', 'moreover', 'furthermore', 'additionally', 'meanwhile',+ 'nevertheless', 'nonetheless', 'consequently', 'ultimately', 'indeed',+ 'thus', 'therefore', 'in fact', 'of course', 'naturally', 'as a result',+ 'in addition', 'even so', 'all the same',+]);++/**+ * Fraction of sentences that open with a transition/connective word or+ * phrase. A steady drumbeat of "However, … Moreover, … Ultimately, …" reads+ * as essay signposting rather than fiction's momentum.+ * @param {string} text+ * @param {{ extraOpeners?: string[] }} [opts]+ * @returns {{ ratio: number, count: number, total: number, index: number|null, anchor: string }}+ */+export function transitionOpenerRatio(text, opts = {}) {+ const sentences = splitSentences(text);+ if (!sentences.length) return { ratio: 0, count: 0, total: 0, index: null, anchor: '' };+ const extra = (Array.isArray(opts.extraOpeners) ? opts.extraOpeners : []).map(normalizeWord).filter(Boolean);+ const openers = [...new Set([...TRANSITION_OPENERS, ...extra])].sort((a, b) => b.length - a.length);+ let count = 0;+ let index = null;+ let anchor = '';+ for (const s of sentences) {+ const lower = s.text.toLowerCase();+ const hit = openers.find((o) => lower.startsWith(o));+ if (hit) {+ count += 1;+ if (index === null) {+ index = s.index;+ anchor = s.text.slice(0, Math.min(s.text.length, hit.length + 20)).trim();+ }+ }+ }+ return { ratio: count / sentences.length, count, total: sentences.length, index, anchor };+}++/**+ * Runs of `minRun`+ consecutive paragraphs whose word counts stay within+ * `tolerance` of the previous paragraph — a mechanically uniform paragraph+ * cadence a human draft rarely sustains.+ * @param {string} text+ * @param {{ minRun?: number, tolerance?: number }} [opts]+ * minRun — consecutive similar-length paragraphs before a run is flagged (default 3).+ * tolerance — fractional difference allowed between consecutive paragraphs (default 0.15).+ * @returns {Array<{ index: number, anchor: string, count: number, avgWords: number }>}+ */+export function paragraphLengthUniformity(text, opts = {}) {+ const paragraphs = splitParagraphs(text);+ const minRun = Math.max(3, Number.isInteger(opts.minRun) ? opts.minRun : 3);+ const tolerance = typeof opts.tolerance === 'number' ? opts.tolerance : 0.15;+ if (paragraphs.length < minRun) return [];+ const lengths = paragraphs.map((p) => tokenizeWords(p.text).length);+ const out = [];+ let runStart = 0;+ for (let i = 1; i <= paragraphs.length; i += 1) {+ const prevLen = lengths[i - 1];+ const curLen = i < paragraphs.length ? lengths[i] : null;+ const withinTolerance = curLen !== null && prevLen > 0+ && Math.abs(curLen - prevLen) / prevLen <= tolerance;+ if (!withinTolerance) {+ const runLen = i - runStart;+ if (runLen >= minRun) {+ out.push({+ index: paragraphs[runStart].index,+ anchor: paragraphs[runStart].text.slice(0, 120),+ count: runLen,+ avgWords: Math.round(lengths.slice(runStart, i).reduce((a, b) => a + b, 0) / runLen),+ });+ }+ runStart = i;+ }+ }+ return out;+}++// Scene/section-break markers: a line that is ONLY a break glyph run+// ("***", "* * *", "---", "###", "~~~").+const SECTION_BREAK_LINE_RE = /^\s*(?:\*\s*\*\s*\*+|-{3,}|_{3,}|~{3,}|#{1,6})\s*$/;++/**+ * Count of scene/section-break marker lines in the text.+ * @param {string} text+ * @returns {number}+ */+export function countSectionBreaks(text) {+ if (typeof text !== 'string' || !text) return 0;+ return text.split('\n').filter((line) => SECTION_BREAK_LINE_RE.test(line)).length;+}++// ---------------------------------------------------------------------------+// Composite score.+// ---------------------------------------------------------------------------++// Documented, clamped weights for the composite 0–10 penalty. Each signal+// contributes an independently capped amount so no single detector can blow+// out the whole score; the final sum is clamped to [0, 10].+export const SLOP_PENALTY_WEIGHTS = Object.freeze({+ tier1PerHit: 0.5,+ tier1Cap: 4,+ tier2PerCluster: 0.4,+ tier2Cap: 2,+ aiTellPerHit: 0.4,+ aiTellCap: 3,+ structuralTicPerHit: 0.3,+ structuralTicCap: 2,+ emDashThresholdPer1000: 15,+ emDashPenalty: 1,+ lowSentenceCvThreshold: 0.3,+ lowSentenceCvPenalty: 1,+ transitionRatioThreshold: 0.3,+ highTransitionRatioPenalty: 0.75,+ paragraphUniformityPenalty: 0.75,+});++/**+ * Composite deterministic slop penalty (0–10, clamped) for `text`, combining+ * every detector above PLUS the sentence-length CV already measured by+ * `measureSentenceRhythm` (repetition.js) — read here for scoring only, never+ * re-emitted as its own finding (see the module doc comment's dedupe note).+ *+ * @param {string} text+ * @param {object} [opts] passed through to every underlying detector+ * (allowWords/extraWords/allowPatterns/clusterThreshold/etc.), plus an+ * optional `weights` object to override individual `SLOP_PENALTY_WEIGHTS`.+ * @returns {number} penalty in [0, 10]+ */+export function computeSlopPenalty(text, opts = {}) {+ if (typeof text !== 'string' || !text.trim()) return 0;+ const w = { ...SLOP_PENALTY_WEIGHTS, ...(opts.weights || {}) };+ let penalty = 0;++ penalty += Math.min(findBannedWordsTier1(text, opts).length * w.tier1PerHit, w.tier1Cap);+ penalty += Math.min(findSuspiciousWordClusters(text, opts).length * w.tier2PerCluster, w.tier2Cap);+ penalty += Math.min(findAiTells(text, opts).length * w.aiTellPerHit, w.aiTellCap);+ penalty += Math.min(findStructuralTics(text, opts).length * w.structuralTicPerHit, w.structuralTicCap);++ const emDash = emDashDensityPer1000(text);+ if (emDash.rate >= w.emDashThresholdPer1000) penalty += w.emDashPenalty;++ const rhythm = measureSentenceRhythm(text);+ if (rhythm && rhythm.cv < w.lowSentenceCvThreshold) penalty += w.lowSentenceCvPenalty;++ const transitions = transitionOpenerRatio(text, opts);+ if (transitions.total > 0 && transitions.ratio > w.transitionRatioThreshold) penalty += w.highTransitionRatioPenalty;++ if (paragraphLengthUniformity(text, opts).length > 0) penalty += w.paragraphUniformityPenalty;++ return Math.max(0, Math.min(10, Math.round(penalty * 100) / 100));+}diff --git a/server/lib/editorial/slopScore.test.js b/server/lib/editorial/slopScore.test.jsnew file mode 100644index 0000000000..be45d16f99--- /dev/null+++ b/server/lib/editorial/slopScore.test.js@@ -0,0 +1,387 @@+import { describe, it, expect } from 'vitest';+import {+ TIER1_BANNED_WORDS,+ TIER2_SUSPICIOUS_WORDS,+ AI_TELL_PATTERNS,+ TRANSITION_OPENERS,+ SLOP_PENALTY_WEIGHTS,+ findBannedWordsTier1,+ findSuspiciousWordClusters,+ splitParagraphs,+ findAiTells,+ findNotJustButPatterns,+ findNotSayingPatterns,+ findNegativeAssertions,+ findTheWaySimiles,+ findTriadicShortSentences,+ findStructuralTics,+ emDashDensityPer1000,+ transitionOpenerRatio,+ paragraphLengthUniformity,+ countSectionBreaks,+ computeSlopPenalty,+} from './slopScore.js';++describe('findBannedWordsTier1', () => {+ it('flags every occurrence of a Tier 1 word (not deduped)', () => {+ const text = 'She would delve into the archive. Later, she delved again.';+ const hits = findBannedWordsTier1(text);+ expect(hits).toHaveLength(2);+ expect(hits[0].entry).toBe('delve');+ expect(hits[1].entry).toBe('delved');+ });++ it('matches multi-word and hyphenated seed phrases with flexible spacing', () => {+ expect(findBannedWordsTier1('This is an ever-evolving landscape.')).toHaveLength(1);+ expect(findBannedWordsTier1('This is an ever evolving landscape.')).toHaveLength(1);+ expect(findBannedWordsTier1('It stands as a testament to her will.')).toHaveLength(1);+ });++ it('respects allowWords and extraWords', () => {+ expect(findBannedWordsTier1('She would delve into it.', { allowWords: ['delve'] })).toHaveLength(0);+ expect(findBannedWordsTier1('A truly bespoke solution.', { extraWords: ['bespoke'] })).toHaveLength(1);+ });++ it('does not flag ordinary prose', () => {+ expect(findBannedWordsTier1('She opened the door and stepped inside.')).toHaveLength(0);+ });++ it('has no overlap with the Tier 2 suspicious list', () => {+ const tier1 = new Set(TIER1_BANNED_WORDS.map((w) => w.toLowerCase()));+ for (const w of TIER2_SUSPICIOUS_WORDS) {+ expect(tier1.has(w.toLowerCase())).toBe(false);+ }+ });+});++describe('splitParagraphs', () => {+ it('splits on blank lines and reports absolute offsets', () => {+ const text = 'First paragraph.\n\nSecond paragraph.\n\nThird.';+ const paras = splitParagraphs(text);+ expect(paras.map((p) => p.text)).toEqual(['First paragraph.', 'Second paragraph.', 'Third.']);+ for (const p of paras) {+ expect(text.slice(p.index, p.index + p.text.length)).toBe(p.text);+ }+ });+});++describe('findSuspiciousWordClusters', () => {+ it('does NOT flag an isolated Tier 2 word', () => {+ const text = 'The plan was robust, but nothing else in this paragraph is suspicious.';+ expect(findSuspiciousWordClusters(text)).toHaveLength(0);+ });++ it('flags a cluster of 3+ Tier 2 words within one paragraph', () => {+ const text = 'The robust plan fostered a seamless transition, and it felt pivotal to the whole effort.';+ const clusters = findSuspiciousWordClusters(text);+ expect(clusters).toHaveLength(1);+ expect(clusters[0].count).toBeGreaterThanOrEqual(3);+ expect(clusters[0].words).toEqual(expect.arrayContaining(['robust', 'fostered', 'seamless', 'pivotal']));+ });++ it('isolated vs. clustered Tier 2 words in different paragraphs of the same text', () => {+ const text = [+ 'The robust plan fostered a seamless transition that felt pivotal.',+ '',+ 'Meanwhile, the weather was merely pleasant that day.',+ ].join('\n');+ const clusters = findSuspiciousWordClusters(text);+ expect(clusters).toHaveLength(1);+ });++ it('honors a custom clusterThreshold', () => {+ const text = 'The plan was robust and seamless.';+ expect(findSuspiciousWordClusters(text, { clusterThreshold: 3 })).toHaveLength(0);+ expect(findSuspiciousWordClusters(text, { clusterThreshold: 2 })).toHaveLength(1);+ });+});++describe('findAiTells', () => {+ it('flags each fiction AI-tell idiom', () => {+ const fixtures = {+ 'sense-of': 'A sense of dread settled over the room.',+ 'couldnt-help-but': "She couldn't help but smile at the memory.",+ 'eyes-widened': 'His eyes widened at the sight.',+ 'breath-didnt-know': "She let out a breath she didn't know she'd been holding.",+ 'wave-of-emotion': 'A wave of relief washed over him.',+ 'heart-pounded-chest': 'Her heart pounded in her chest as the door creaked open.',+ 'physical-named-emotion': 'Her heart raced with fear as the shadow moved.',+ };+ for (const [id, text] of Object.entries(fixtures)) {+ const hits = findAiTells(text);+ expect(hits.map((h) => h.id), `expected pattern "${id}" to fire on: ${text}`).toContain(id);+ }+ });++ it('reports one finding per distinct pattern (first occurrence only)', () => {+ const text = 'His eyes widened. Moments later her eyes widened too.';+ const hits = findAiTells(text);+ expect(hits.filter((h) => h.id === 'eyes-widened')).toHaveLength(1);+ });++ it('respects allowPatterns', () => {+ const text = 'His eyes widened at the sight.';+ expect(findAiTells(text, { allowPatterns: ['eyes-widened'] })).toHaveLength(0);+ });++ it('does not flag clean prose', () => {+ expect(findAiTells('The door creaked open and she stepped through.')).toHaveLength(0);+ });++ it('every pattern declares a unique id', () => {+ const ids = AI_TELL_PATTERNS.map((p) => p.id);+ expect(new Set(ids).size).toBe(ids.length);+ });+});++describe('findNotJustButPatterns', () => {+ it('flags the "not just X, but Y" construction', () => {+ const text = 'It was not just a house, but a home to three generations.';+ const hits = findNotJustButPatterns(text);+ expect(hits).toHaveLength(1);+ expect(hits[0].anchor).toMatch(/not just a house, but a home/i);+ });++ it('flags "not only ... but also"', () => {+ const text = 'The plan was not only ambitious, but also dangerous.';+ expect(findNotJustButPatterns(text)).toHaveLength(1);+ });++ it('does not flag ordinary negation', () => {+ expect(findNotJustButPatterns('She did not want to leave the house tonight.')).toHaveLength(0);+ });+});++describe('findNotSayingPatterns', () => {+ it('flags "I\'m not saying X, I\'m saying Y"', () => {+ const text = "I'm not saying he's guilty, I'm saying the evidence is thin.";+ expect(findNotSayingPatterns(text)).toHaveLength(1);+ });++ it('does not flag a lone "I\'m not saying" clause', () => {+ expect(findNotSayingPatterns("I'm not saying anything else about it tonight.")).toHaveLength(0);+ });+});++describe('findNegativeAssertions', () => {+ it('matches "did not [verb]" and contracted forms', () => {+ const text = 'She did not flinch. He did not move. They didn\'t speak. It doesn\'t matter.';+ const hits = findNegativeAssertions(text);+ expect(hits.length).toBe(4);+ });++ it('returns nothing for text with no negative assertions', () => {+ expect(findNegativeAssertions('She smiled and walked away.')).toHaveLength(0);+ });+});++describe('findTheWaySimiles', () => {+ it('flags "the way [subject] [verb]" constructions', () => {+ const text = 'He loved the way her voice cracked when she laughed.';+ expect(findTheWaySimiles(text).length).toBeGreaterThanOrEqual(1);+ });++ it('does not flag an unrelated use of "the way"', () => {+ expect(findTheWaySimiles('Which way should we go from here?')).toHaveLength(0);+ });+});++describe('findTriadicShortSentences', () => {+ it('flags 3+ consecutive very short sentences', () => {+ const text = 'Fast. Precise. Deadly. That was the whole plan from the very beginning.';+ const hits = findTriadicShortSentences(text);+ expect(hits).toHaveLength(1);+ expect(hits[0].count).toBe(3);+ });++ it('does not flag two short sentences (below minRun)', () => {+ const text = 'Fast. Precise. That was the whole elaborate and carefully considered plan.';+ expect(findTriadicShortSentences(text)).toHaveLength(0);+ });++ it('does not flag normal-length sentences', () => {+ const text = 'She walked across the room slowly. He watched her every movement. Neither spoke a word for a long while.';+ expect(findTriadicShortSentences(text)).toHaveLength(0);+ });++ it('honors a custom minRun', () => {+ const text = 'Fast. Precise. Deadly. Quiet. That was the plan they settled on eventually.';+ expect(findTriadicShortSentences(text, { minRun: 5 })).toHaveLength(0);+ expect(findTriadicShortSentences(text, { minRun: 4 })).toHaveLength(1);+ });+});++describe('findStructuralTics', () => {+ it('merges all four pattern types, position-ordered', () => {+ const text = [+ 'Fast. Precise. Deadly.',+ 'It was not just brave, but reckless.',+ 'He loved the way she carried herself into the room.',+ ].join(' ');+ const hits = findStructuralTics(text);+ const types = hits.map((h) => h.type);+ expect(types).toContain('triadic-short-sentences');+ expect(types).toContain('not-just-but');+ expect(types).toContain('the-way-simile');+ // Position-ordered.+ for (let i = 1; i < hits.length; i += 1) {+ expect(hits[i].index).toBeGreaterThanOrEqual(hits[i - 1].index);+ }+ });++ it('gates negative-assertion density below the threshold (no finding)', () => {+ // A single "did not" in a long passage sits well under the default+ // 4-per-1000-words threshold.+ const filler = 'word '.repeat(300);+ const text = `${filler}She did not flinch. ${filler}`;+ const tics = findStructuralTics(text);+ expect(tics.find((t) => t.type === 'negative-assertion-density')).toBeUndefined();+ });++ it('reports negative-assertion density once the rate crosses the threshold', () => {+ const text = 'She did not flinch. He did not move. They did not speak. It did not matter. Nothing did not change.';+ const tics = findStructuralTics(text);+ const found = tics.find((t) => t.type === 'negative-assertion-density');+ expect(found).toBeDefined();+ expect(found.count).toBeGreaterThanOrEqual(4);+ });++ it('returns an empty array for clean prose', () => {+ expect(findStructuralTics('She opened the door and stepped inside, unsure of what she would find.')).toHaveLength(0);+ });+});++describe('emDashDensityPer1000', () => {+ it('hand-computes the rate from a known word/em-dash count', () => {+ // 10 words, 2 em dashes -> 200 per 1000.+ const text = 'one two three — four five — six seven eight nine ten';+ const result = emDashDensityPer1000(text);+ expect(result.words).toBe(10);+ expect(result.count).toBe(2);+ expect(result.rate).toBe(200);+ });++ it('returns zeros for text with no em dashes', () => {+ const result = emDashDensityPer1000('one two three four five');+ expect(result.count).toBe(0);+ expect(result.rate).toBe(0);+ });+});++describe('transitionOpenerRatio', () => {+ it('hand-computes the ratio from known sentence openers', () => {+ // 4 sentences, 2 open with a transition word -> ratio 0.5.+ const text = 'However, the weather turned. She walked home anyway. Moreover, she smiled. He waved back at her.';+ const result = transitionOpenerRatio(text);+ expect(result.total).toBe(4);+ expect(result.count).toBe(2);+ expect(result.ratio).toBe(0.5);+ });++ it('returns a zero ratio when no sentence opens with a transition word', () => {+ const text = 'She walked home. He waved back. They smiled.';+ const result = transitionOpenerRatio(text);+ expect(result.count).toBe(0);+ expect(result.ratio).toBe(0);+ });+});++describe('paragraphLengthUniformity', () => {+ it('flags 3+ consecutive paragraphs of near-identical word count', () => {+ const para = (n) => Array.from({ length: n }, (_, i) => `word${i}`).join(' ');+ const text = [para(10), para(10), para(11), para(10)].join('\n\n');+ const runs = paragraphLengthUniformity(text);+ expect(runs).toHaveLength(1);+ expect(runs[0].count).toBe(4);+ });++ it('does not flag paragraphs of widely varying length', () => {+ const para = (n) => Array.from({ length: n }, (_, i) => `word${i}`).join(' ');+ const text = [para(5), para(40), para(8), para(60)].join('\n\n');+ expect(paragraphLengthUniformity(text)).toHaveLength(0);+ });++ it('is a no-op below minRun paragraphs', () => {+ const para = (n) => Array.from({ length: n }, (_, i) => `word${i}`).join(' ');+ const text = [para(10), para(10)].join('\n\n');+ expect(paragraphLengthUniformity(text)).toHaveLength(0);+ });+});++describe('countSectionBreaks', () => {+ it('counts common scene-break marker lines', () => {+ const text = [+ 'Some prose.',+ '***',+ 'More prose.',+ '---',+ 'Even more prose.',+ '* * *',+ ].join('\n');+ expect(countSectionBreaks(text)).toBe(3);+ });++ it('does not count a line that merely contains punctuation among prose', () => {+ expect(countSectionBreaks('She said - "wait" - and stopped.')).toBe(0);+ });++ it('returns 0 for text with no markers', () => {+ expect(countSectionBreaks('Just plain prose with no breaks at all.')).toBe(0);+ });+});++describe('computeSlopPenalty', () => {+ it('returns 0 for empty/non-string input', () => {+ expect(computeSlopPenalty('')).toBe(0);+ expect(computeSlopPenalty(' ')).toBe(0);+ expect(computeSlopPenalty(null)).toBe(0);+ expect(computeSlopPenalty(undefined)).toBe(0);+ });++ it('returns 0 for clean, varied human-style prose', () => {+ const text = [+ 'Mira set the cup down and looked out the window.',+ 'Rain traced slow lines down the glass, and somewhere below a dog barked twice, then quit.',+ 'She thought about calling him.',+ 'She didn\'t.',+ ].join(' ');+ expect(computeSlopPenalty(text)).toBe(0);+ });++ it('clamps the Tier 1 contribution at the documented cap', () => {+ const repeated = 'delve '.repeat(50); // far more hits than tier1Cap / tier1PerHit+ const penalty = computeSlopPenalty(repeated);+ expect(penalty).toBeLessThanOrEqual(SLOP_PENALTY_WEIGHTS.tier1Cap + 0.01);+ });++ it('never exceeds 10 even for an adversarially slop-heavy passage', () => {+ const adversarial = [+ TIER1_BANNED_WORDS.join(' '),+ TIER2_SUSPICIOUS_WORDS.join(' '),+ ...AI_TELL_PATTERNS.map((p) => p.re.source), // not real matches, just bulk text+ 'It was not just brave, but reckless. It was not just brave, but reckless.',+ 'Fast. Precise. Deadly. Fast. Precise. Deadly.',+ 'She did not flinch. He did not move. They did not speak. It did not matter.',+ '— '.repeat(100),+ TRANSITION_OPENERS.map((t) => `${t}, it happened again.`).join(' '),+ ].join(' ');+ const penalty = computeSlopPenalty(adversarial);+ expect(penalty).toBeLessThanOrEqual(10);+ expect(penalty).toBeGreaterThan(0);+ });++ it('adds the low-sentence-CV penalty for hand-computed monotonous sentence lengths', () => {+ // 8 sentences of EXACTLY 6 words each -> stddev 0, cv 0 (< 0.3 threshold).+ const sentence = (n) => `word${n} word word word word word.`;+ const text = Array.from({ length: 8 }, (_, i) => sentence(i)).join(' ');+ const penalty = computeSlopPenalty(text);+ expect(penalty).toBeGreaterThanOrEqual(SLOP_PENALTY_WEIGHTS.lowSentenceCvPenalty);+ });++ it('honors overridden weights', () => {+ const repeated = 'delve delve delve';+ const withDefault = computeSlopPenalty(repeated);+ const withOverride = computeSlopPenalty(repeated, { weights: { tier1PerHit: 0, tier1Cap: 0 } });+ expect(withOverride).toBeLessThan(withDefault);+ });+});