Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: editorial prose anti-pattern checks bundle (#1300)

Adam Eivy342658836dc8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 727bbe673d..bd0885b7a1 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **[issue-1300] Editorial checks flag five prose anti-patterns (weak openings, mirror self-description, empty pleasantries, italic thoughts, darlings).** A bundle of line/scene-level checks (Create → Editorial Checks) for the well-known tells that pull readers out. Four are LLM checks over the drafted manuscript: **Weak opening** flags clichéd or mis-placed openers — "he wakes up" / alarm-clock / dream starts, weather-and-scenery preambles, and scenes that begin before the interesting moment; **Mirror self-description** catches the tired trick of a character studying their reflection so the prose can catalog their looks, while leaving reflections that do real story work alone; **Empty greeting / small-talk openings** flags scenes that open on greeting rituals or logistical filler that carry no tension or information, while sparing pleasantries laced with subtext; **Kill your darlings** surfaces precious, self-indulgent passages — showpiece descriptions, digressions, over-explaining, favorite lines that stop the scene — as cut candidates, judged by story need rather than quality (complementing the dead-metaphor check, which targets stock rather than precious prose). The fifth, **Italicized internal thoughts**, is a deterministic, high-precision scan that flags multi-word `*…*` / `_…_` italic thought runs (the prose is already in the character's perspective, so italicizing a thought is a tell) while leaving single-word emphasis, bold, and `snake_case` alone, with a configurable word threshold. All findings anchor a verbatim quote + issue number; the LLM checks ship four new stage prompts (`pipeline-editorial-{opening-start,mirror-description,dialogue-pleasantries,kill-your-darlings}`) that migrate for existing installs (103–106), the deterministic check needs no model. (`server/lib/editorial/{italicThoughts,checkRegistry}.js`) (#1300)
+
- **[issue-1407] The LoRA-training form now exposes the per-run base-quant and low-RAM overrides.** The `baseQuant` (bf16 / 8-bit / 4-bit) and `lowRam` request params landed server-side under #1321 — schema, route threading, and the `LORA_TRAIN_MAX_QUANT_BITS` cap — but the training form had no controls for them, so opting a single run into a heavier or lighter frozen base than its memory-derived tier still meant a code change. The Train-LoRA panel now has two **Base quant** and **Low RAM spill** selects (both defaulting to **Auto**); an explicit pick overrides the tier — still clamped by the install's `LORA_TRAIN_MAX_QUANT_BITS` ceiling — while "Auto" sends an explicit `null` that forces the memory-derived tier. (The `null` is a deliberate clear, not an omitted key: the server re-merges `settings.loraTraining.defaults` into every run, so an omitted key would silently keep a *saved* default — `null` lets "Auto" actually beat one.) The controls only show when the mflux engine is the one that'll run; the torch/FLUX2 path trains the bf16 base and ignores them. (`client/src/components/loraTraining/TrainingPanel.jsx`, `server/lib/validation.js`, #1407)
- **Each managed app now declares where its autonomous work items live — PLAN.md, GitHub issues, GitLab issues, or JIRA.** Previously the CoS could only claim work from PLAN.md (`plan-task`) or GitHub issues (`claim-issue`) via separate per-app toggles. A new per-app **Work Tracker** setting (App settings → Edit) makes the work *source* a single explicit choice. It defaults to **Auto**, which resolves from the app's git `origin` host: a github.com remote → GitHub issues, a gitlab.* remote (incl. self-hosted) → GitLab issues, anything else → PLAN.md (JIRA is always an explicit opt-in). A new **`claim-work`** scheduled task is the single-source router: one toggle that, at dispatch, resolves the app's tracker and delegates to the matching claim flow — so the same agent still creates its own `claim/<slug>` worktree, opens its own PR/MR, and cleans up. **GitLab issue claiming is genuinely new**: a `claim-issue-gitlab` prompt drives the full 7-phase `/claim --issues` flow over `glab` issues + merge requests (the GitHub `claim-issue` flow is untouched). The legacy `plan-task` / `claim-issue` / `jira-sprint-manager` task types remain for backward compatibility. New `GET /api/apps/:id/work-tracker` resolves the effective tracker for the UI. (`server/lib/workTracker.js`, `server/services/{cosTaskGenerator,taskSchedule,apps}.js`, `server/services/taskPromptDefaults/prompts.js`, `server/routes/apps.js`, `client/src/components/apps/EditAppModal.jsx`)
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index 4b850b16f6..f4d7c8479d 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -506,6 +506,34 @@
"returnsJson": true,
"variables": []
},
+ "pipeline-editorial-opening-start": {
+ "name": "Pipeline — Editorial Check: Weak opening (wrong start)",
+ "description": "Editorial check (#1300): flags clichéd or mis-placed openings — \"he wakes up\" / alarm-clock / dream starts, weather and scene-setting preambles, and scenes that begin before the interesting moment. Reads the stitched manuscript, focusing on the story opening and each chapter/issue opening. Returns issue-anchored findings.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
+ },
+ "pipeline-editorial-mirror-description": {
+ "name": "Pipeline — Editorial Check: Mirror self-description",
+ "description": "Editorial check (#1300): flags the tired device of a character looking at themselves in a mirror or reflection so the prose can catalog their appearance, while leaving reflections that do real story work alone. Reads the stitched manuscript. Returns issue-anchored findings.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
+ },
+ "pipeline-editorial-dialogue-pleasantries": {
+ "name": "Pipeline — Editorial Check: Empty greeting / small-talk openings",
+ "description": "Editorial check (#1300): flags scenes that open on empty pleasantries — greeting rituals and logistical small talk that carry no tension or information — while leaving pleasantries laced with subtext alone. Reads the stitched manuscript. Returns issue-anchored findings.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
+ },
+ "pipeline-editorial-kill-your-darlings": {
+ "name": "Pipeline — Editorial Check: Kill your darlings",
+ "description": "Editorial check (#1300): surfaces precious, self-indulgent passages — showpiece descriptions, digressions, over-explaining, and favorite lines that stop the scene's momentum — as candidates to cut, judged by story need rather than quality. Reads the stitched manuscript. Returns issue-anchored findings.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
+ },
"pipeline-editorial-endings-cliffhanger": {
"name": "Pipeline — Editorial Check: Chapter-ending cliffhangers",
"description": "Editorial check (#1298): flags chapter/issue endings that resolve and settle (\"soft landings\") instead of ending on an unresolved beat that pulls the reader forward, leaving a clearly terminal final chapter alone. Reads the stitched manuscript and reconciles detected endings against the authored reader-map cliffhangers. Returns issue-anchored findings.",
diff --git a/data.reference/prompts/stages/pipeline-editorial-dialogue-pleasantries.md b/data.reference/prompts/stages/pipeline-editorial-dialogue-pleasantries.md
new file mode 100644
index 0000000000..3cd943e09f
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-editorial-dialogue-pleasantries.md
@@ -0,0 +1,62 @@
+# Pipeline — Editorial Check: Empty greeting / small-talk openings
+
+You are a line editor doing a single focused pass for ONE problem:
+**scenes that open on empty pleasantries** — greeting rituals and small talk that
+carry no tension or information. A scene should drop the reader into the middle of
+the exchange that matters, not the throat-clearing before it.
+
+Flag a scene opening (or a stretch of dialogue at a scene's start) when it is
+mostly:
+
+- **Greeting ritual** — "Hi." / "Hi, how are you?" / "Good, you?" / "Can't
+ complain." exchanges that just acknowledge two people are now talking.
+- **Logistical small talk** — comments on the weather, the traffic, the coffee,
+ "thanks for coming", offers of a drink — filler before the real conversation.
+- **Re-introductions** — characters telling each other things they both already
+ know to ease the reader in.
+
+Do NOT flag: pleasantries doing real work — small talk laced with subtext or
+menace, an awkward greeting that characterizes a strained relationship, or
+politeness that is itself the point of the scene. The bar is empty ritual that
+delays the scene, not any greeting.
+
+## Manuscript
+
+The manuscript is stitched from the drafted issues. Section headers attribute
+each chunk to an issue (e.g. `# Issue 3 — Title (prose)`). Use the issue number
+in each section header to attribute every finding to its `issueNumber`.
+
+```
+{{manuscript}}
+```
+
+## Task
+
+Find the empty greeting/small-talk openings. For each one, quote a short verbatim
+anchor from the text (≤ 200 characters) so the editor can jump to it, name the
+issue number it appears in, explain why it carries no tension or information, and
+suggest where the scene should actually start (usually a line or two in, at the
+first beat that matters).
+
+Be specific and cite the text. If the dialogue openings start in the right place,
+return an empty `findings` array — do not invent problems.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no
+commentary:
+
+```json
+{
+ "findings": [
+ {
+ "severity": "high|medium|low",
+ "issueNumber": 3,
+ "location": "string — where the small-talk opening is (e.g. 'Issue 3 — café scene')",
+ "problem": "1–3 sentences naming the empty pleasantries and why they delay the scene",
+ "suggestion": "1–3 sentences on where the scene should start instead",
+ "anchorQuote": "short verbatim quote from the manuscript (≤ 200 chars)"
+ }
+ ]
+}
+```
diff --git a/data.reference/prompts/stages/pipeline-editorial-kill-your-darlings.md b/data.reference/prompts/stages/pipeline-editorial-kill-your-darlings.md
new file mode 100644
index 0000000000..247270bb05
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-editorial-kill-your-darlings.md
@@ -0,0 +1,66 @@
+# Pipeline — Editorial Check: Kill your darlings
+
+You are a developmental editor doing a single focused pass for ONE problem:
+**darlings** — passages a writer is precious about that serve the author more than
+the story. These are the lines an author would defend hardest and that an editor
+most often cuts. Flag candidates to cut:
+
+- **Self-indulgent showpieces** — a virtuoso description, an extended metaphor, or
+ a lyrical riff that exists to show off the prose rather than move the scene.
+- **Digressions** — a tangent, backstory aside, or world-building detour the
+ scene doesn't need, however well-written.
+- **Over-explaining** — a point made well, then made again two more ways; a line
+ that spells out what the prose already showed.
+- **A favorite line that doesn't earn its place** — a clever aphorism, a joke, or
+ a "great" sentence that stops the scene's momentum to be admired.
+
+Judge by the story's need, not by quality — the better-written a darling is, the
+more this check matters, because quality is exactly why the author won't cut it.
+
+Do NOT flag: prose that is rich but load-bearing (it characterizes, raises
+tension, or pays off later), deliberate style that is consistent and earned, or
+anything you'd cut purely as a matter of taste. This is the precious/self-
+indulgent lens; stock and tired language is the dead-metaphor check's job. The bar
+is "the story is better without it," not "I would have written it differently."
+
+## Manuscript
+
+The manuscript is stitched from the drafted issues. Section headers attribute
+each chunk to an issue (e.g. `# Issue 3 — Title (prose)`). Use the issue number
+in each section header to attribute every finding to its `issueNumber`.
+
+```
+{{manuscript}}
+```
+
+## Task
+
+Find the darlings worth cutting. For each one, quote a short verbatim anchor from
+the text (≤ 200 characters) so the editor can jump to it, name the issue number it
+appears in, name what kind of darling it is in the `location` (e.g.
+`Issue 3 — showpiece description`, `Issue 5 — digression`), explain why the story
+is better without it, and suggest the cut or a leaner replacement.
+
+Be specific and cite the text. Favor a few high-confidence cuts over many
+uncertain ones. If nothing is precious, return an empty `findings` array — do not
+invent problems.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no
+commentary:
+
+```json
+{
+ "findings": [
+ {
+ "severity": "high|medium|low",
+ "issueNumber": 3,
+ "location": "string — the darling kind + where (e.g. 'Issue 3 — showpiece description')",
+ "problem": "1–3 sentences naming the darling and why the story is better without it",
+ "suggestion": "1–3 sentences proposing the cut or a leaner replacement",
+ "anchorQuote": "short verbatim quote from the manuscript (≤ 200 chars)"
+ }
+ ]
+}
+```
diff --git a/data.reference/prompts/stages/pipeline-editorial-mirror-description.md b/data.reference/prompts/stages/pipeline-editorial-mirror-description.md
new file mode 100644
index 0000000000..c0cc5b8e56
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-editorial-mirror-description.md
@@ -0,0 +1,59 @@
+# Pipeline — Editorial Check: Mirror self-description
+
+You are a line editor doing a single focused pass for ONE cliché:
+**the character who looks at themselves in a mirror (or other reflection) so the
+prose can describe their appearance**. This is a tired device for slipping a
+viewpoint character's physical description onto the page — readers recognize it
+immediately as an author convenience.
+
+Flag a passage when a character catches their reflection (a mirror, window,
+puddle, polished blade, phone screen, the back of a spoon) and the prose uses that
+moment primarily to **catalog their own looks** — hair, eyes, face, build, the
+clothes they're wearing — rather than to do something dramatically meaningful.
+
+Do NOT flag: a reflection used for genuine story work (a character not
+recognizing themselves after a change, a dysmorphic or dissociative beat, spotting
+someone *behind* them, a plot clue in the reflection), or a glance in a mirror
+that does NOT turn into a self-description. The bar is the description-delivery
+trick, not any mention of a mirror.
+
+## Manuscript
+
+The manuscript is stitched from the drafted issues. Section headers attribute
+each chunk to an issue (e.g. `# Issue 3 — Title (prose)`). Use the issue number
+in each section header to attribute every finding to its `issueNumber`.
+
+```
+{{manuscript}}
+```
+
+## Task
+
+Find the mirror self-description moments. For each one, quote a short verbatim
+anchor from the text (≤ 200 characters) so the editor can jump to it, name the
+issue number it appears in, explain why it reads as an author convenience, and
+suggest how to deliver the description (or whether it's needed at all) without the
+mirror — woven into action, noted by another character, or simply cut.
+
+Be specific and cite the text. If there are no mirror self-descriptions, return an
+empty `findings` array — do not invent problems.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no
+commentary:
+
+```json
+{
+ "findings": [
+ {
+ "severity": "high|medium|low",
+ "issueNumber": 3,
+ "location": "string — where the mirror moment is (e.g. 'Issue 3 — opening scene')",
+ "problem": "1–3 sentences naming the mirror self-description and why it reads as a convenience",
+ "suggestion": "1–3 sentences on how to deliver the description without the mirror, or to cut it",
+ "anchorQuote": "short verbatim quote from the manuscript (≤ 200 chars)"
+ }
+ ]
+}
+```
diff --git a/data.reference/prompts/stages/pipeline-editorial-opening-start.md b/data.reference/prompts/stages/pipeline-editorial-opening-start.md
new file mode 100644
index 0000000000..293ef7c9f9
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-editorial-opening-start.md
@@ -0,0 +1,65 @@
+# Pipeline — Editorial Check: Weak opening (wrong place to start)
+
+You are a developmental editor doing a single focused pass for ONE problem:
+**openings that start in the wrong place**. Read the opening of the story and of
+each chapter/issue and judge whether it begins at the moment that pulls a reader
+in. Flag these tells:
+
+- **Waking up** — the story or a scene opens with the character waking, an alarm
+ clock, getting out of bed, or surfacing from a dream. The "it was all a dream"
+ / waking-from-sleep opener is one of the most worn starts there is.
+- **Scene-setting preamble** — opening on weather, a landscape pan, a history
+ lesson, or throat-clearing description before anything happens.
+- **Starting too early** — the scene opens minutes (or pages) before the
+ interesting moment: a character commuting, making coffee, or recapping before
+ the actual inciting beat. A scene should open as late into the action as it can.
+- **A weak hook generally** — a first line/paragraph that gives a reader no
+ question, tension, voice, or image to hold onto.
+
+Do NOT flag: an opening that uses a familiar setup **freshly or pointedly** (a
+waking scene that immediately subverts the trope and carries real tension), a
+deliberate slow-burn literary opening that is clearly earned by voice, or a
+mid-book chapter opening that is a legitimate quiet beat after a high-tension one.
+The bar is an opener that costs the reader momentum, not merely a calm one.
+
+## Manuscript
+
+The manuscript is stitched from the drafted issues. Section headers attribute
+each chunk to an issue (e.g. `# Issue 3 — Title (prose)`). Use the issue number
+in each section header to attribute every finding to its `issueNumber`. Focus on
+the FIRST scene of the whole story and the opening of each chapter/issue.
+
+```
+{{manuscript}}
+```
+
+## Task
+
+Find the weak or mis-placed openings. For each one, quote a short verbatim anchor
+from the opening (≤ 200 characters) so the editor can jump to it, name the issue
+number it appears in, name which kind of weak start it is in the `location` (e.g.
+`Issue 1 — waking up`, `Issue 3 — starts too early`), explain why it costs the
+reader momentum, and suggest where the scene should actually begin.
+
+Be specific and cite the text. If the openings are strong, return an empty
+`findings` array — do not invent problems.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no
+commentary:
+
+```json
+{
+ "findings": [
+ {
+ "severity": "high|medium|low",
+ "issueNumber": 1,
+ "location": "string — the opening problem + where (e.g. 'Issue 1 — waking up')",
+ "problem": "1–3 sentences naming the weak opening and why it costs momentum",
+ "suggestion": "1–3 sentences on where the scene should begin instead",
+ "anchorQuote": "short verbatim quote from the opening (≤ 200 chars)"
+ }
+ ]
+}
+```
diff --git a/scripts/migrations/103-editorial-opening-start-stage.js b/scripts/migrations/103-editorial-opening-start-stage.js
new file mode 100644
index 0000000000..1561f8dd12
--- /dev/null
+++ b/scripts/migrations/103-editorial-opening-start-stage.js
@@ -0,0 +1,76 @@
+/**
+ * Seed the `pipeline-editorial-opening-start` stage into existing installs (#1300).
+ *
+ * Mirrors `101-editorial-dead-metaphor-stage.js`: copies the `.md` template from
+ * `data.reference/prompts/stages/` and merges the stage-config entry into
+ * `data/prompts/stage-config.json`. Boot runs migrations (server/index.js) but
+ * NOT `setup-data.js`, so an upgrade that pulls + `pm2 restart`s (rather than
+ * running `update.sh`) would otherwise leave the new opening-start stage unseeded
+ * and the `opening.wrong-start` editorial check would throw "Stage not found" the
+ * first time it runs. (The deterministic sibling `prose.italic-thoughts` needs no
+ * stage.)
+ */
+
+import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';
+import { dirname, join } from 'path';
+
+const FILENAME = 'pipeline-editorial-opening-start.md';
+const STAGE_KEY = 'pipeline-editorial-opening-start';
+
+export default {
+ async up({ rootDir }) {
+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ await mkdir(stagesDir, { recursive: true });
+
+ const dataPath = join(stagesDir, FILENAME);
+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', FILENAME);
+
+ const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);
+ if (exists) {
+ console.log(`📝 ${STAGE_KEY} prompt: already present`);
+ } else {
+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
+ if (!sampleExists) {
+ console.warn(`⚠️ ${STAGE_KEY}: sample missing for ${FILENAME} — skipping copy`);
+ } else {
+ try {
+ await copyFile(samplePath, dataPath);
+ console.log(`✅ seeded ${FILENAME}`);
+ } catch (err) {
+ console.warn(`⚠️ ${STAGE_KEY}: copy failed for ${FILENAME}: ${err.message}`);
+ }
+ }
+ }
+
+ const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);
+ if (!sampleConfigExists) {
+ console.warn(`⚠️ ${STAGE_KEY}: data.reference stage-config.json missing — cannot resolve entry; skipping config write`);
+ return;
+ }
+ try {
+ const sample = JSON.parse(await readFile(sampleConfigPath, 'utf8'));
+ const installedExists = await access(installedConfigPath, constants.F_OK).then(() => true, () => false);
+ const installed = installedExists
+ ? JSON.parse(await readFile(installedConfigPath, 'utf8'))
+ : { stages: {} };
+ installed.stages = installed.stages || {};
+ if (installed.stages[STAGE_KEY]) {
+ console.log(`📝 ${STAGE_KEY} stage-config: already present`);
+ return;
+ }
+ if (!sample?.stages?.[STAGE_KEY]) {
+ console.warn(`⚠️ ${STAGE_KEY}: sample stage-config missing ${STAGE_KEY} — skipping`);
+ return;
+ }
+ installed.stages[STAGE_KEY] = sample.stages[STAGE_KEY];
+ await mkdir(dirname(installedConfigPath), { recursive: true });
+ await writeFile(installedConfigPath, JSON.stringify(installed, null, 2) + '\n', 'utf8');
+ const action = installedExists ? 'merged' : 'created';
+ console.log(`📝 ${STAGE_KEY} stage-config (${action}): 1 added`);
+ } catch (err) {
+ console.warn(`⚠️ ${STAGE_KEY}: stage-config merge failed: ${err.message}`);
+ }
+ },
+};
diff --git a/scripts/migrations/103-editorial-opening-start-stage.test.js b/scripts/migrations/103-editorial-opening-start-stage.test.js
new file mode 100644
index 0000000000..8e57bbbb3c
--- /dev/null
+++ b/scripts/migrations/103-editorial-opening-start-stage.test.js
@@ -0,0 +1,86 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+
+import migration from './103-editorial-opening-start-stage.js';
+
+// scripts/migrations/<this> → ../.. is the repo root (matches _testHelpers.js).
+const repoRoot = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
+
+// First-shipment seed migration (mirrors 101) — no MD5 bookkeeping, so the
+// seed / no-clobber behavior is asserted directly.
+
+const FILENAME = 'pipeline-editorial-opening-start.md';
+const STAGE_KEY = 'pipeline-editorial-opening-start';
+const BODY = '# Weak opening\n\nshipped body\n';
+
+describe('migration 103 — seed editorial-opening-start stage', () => {
+ let rootDir;
+ let stagesDir;
+ let refStagesDir;
+ let installedConfigPath;
+
+ const seedReference = ({ withConfig = true } = {}) => {
+ writeFileSync(join(refStagesDir, FILENAME), BODY);
+ if (withConfig) {
+ const refConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ writeFileSync(
+ refConfigPath,
+ JSON.stringify({ stages: { [STAGE_KEY]: { name: STAGE_KEY, description: 'desc', model: 'default', returnsJson: true, variables: [] } } }, null, 2) + '\n',
+ );
+ }
+ };
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-103-'));
+ stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ refStagesDir = join(rootDir, 'data.reference', 'prompts', 'stages');
+ installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ mkdirSync(stagesDir, { recursive: true });
+ mkdirSync(refStagesDir, { recursive: true });
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ });
+
+ it('seeds the .md template and merges the stage-config entry on a fresh install', async () => {
+ seedReference();
+ await expect(migration.up({ rootDir })).resolves.not.toThrow();
+ expect(readFileSync(join(stagesDir, FILENAME), 'utf8')).toBe(BODY);
+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));
+ expect(installed.stages[STAGE_KEY]).toMatchObject({ returnsJson: true });
+ });
+
+ it('is idempotent and never clobbers a customized .md or an existing stage-config entry', async () => {
+ seedReference();
+ const customBody = '# CUSTOMIZED — do not overwrite\n';
+ writeFileSync(join(stagesDir, FILENAME), customBody);
+ writeFileSync(
+ installedConfigPath,
+ JSON.stringify({ stages: { [STAGE_KEY]: { name: 'user-tuned', model: 'custom' } } }, null, 2) + '\n',
+ );
+
+ await migration.up({ rootDir });
+
+ expect(readFileSync(join(stagesDir, FILENAME), 'utf8')).toBe(customBody);
+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));
+ expect(installed.stages[STAGE_KEY]).toEqual({ name: 'user-tuned', model: 'custom' });
+ });
+
+ it('does not throw when the data.reference samples are missing', async () => {
+ await expect(migration.up({ rootDir })).resolves.not.toThrow();
+ expect(existsSync(join(stagesDir, FILENAME))).toBe(false);
+ });
+
+ it('matches the live shipped stage-config key + prompt file (drift catch)', () => {
+ const refConfig = JSON.parse(
+ readFileSync(join(repoRoot, 'data.reference', 'prompts', 'stage-config.json'), 'utf8'),
+ );
+ expect(refConfig.stages[STAGE_KEY], `stage-config missing ${STAGE_KEY}`).toBeTruthy();
+ expect(refConfig.stages[STAGE_KEY].returnsJson).toBe(true);
+ expect(existsSync(join(repoRoot, 'data.reference', 'prompts', 'stages', FILENAME))).toBe(true);
+ });
+});
diff --git a/scripts/migrations/104-editorial-mirror-description-stage.js b/scripts/migrations/104-editorial-mirror-description-stage.js
new file mode 100644
index 0000000000..ed4b1f9ccd
--- /dev/null
+++ b/scripts/migrations/104-editorial-mirror-description-stage.js
@@ -0,0 +1,75 @@
+/**
+ * Seed the `pipeline-editorial-mirror-description` stage into existing installs (#1300).
+ *
+ * Mirrors `101-editorial-dead-metaphor-stage.js`: copies the `.md` template from
+ * `data.reference/prompts/stages/` and merges the stage-config entry into
+ * `data/prompts/stage-config.json`. Boot runs migrations (server/index.js) but
+ * NOT `setup-data.js`, so an upgrade that pulls + `pm2 restart`s (rather than
+ * running `update.sh`) would otherwise leave the new mirror-description stage
+ * unseeded and the `prose.mirror-description` editorial check would throw "Stage
+ * not found" the first time it runs.
+ */
+
+import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';
+import { dirname, join } from 'path';
+
+const FILENAME = 'pipeline-editorial-mirror-description.md';
+const STAGE_KEY = 'pipeline-editorial-mirror-description';
+
+export default {
+ async up({ rootDir }) {
+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ await mkdir(stagesDir, { recursive: true });
+
+ const dataPath = join(stagesDir, FILENAME);
+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', FILENAME);
+
+ const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);
+ if (exists) {
+ console.log(`📝 ${STAGE_KEY} prompt: already present`);
+ } else {
+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
+ if (!sampleExists) {
+ console.warn(`⚠️ ${STAGE_KEY}: sample missing for ${FILENAME} — skipping copy`);
+ } else {
+ try {
+ await copyFile(samplePath, dataPath);
+ console.log(`✅ seeded ${FILENAME}`);
+ } catch (err) {
+ console.warn(`⚠️ ${STAGE_KEY}: copy failed for ${FILENAME}: ${err.message}`);
+ }
+ }
+ }
+
+ const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);
+ if (!sampleConfigExists) {
+ console.warn(`⚠️ ${STAGE_KEY}: data.reference stage-config.json missing — cannot resolve entry; skipping config write`);
+ return;
+ }
+ try {
+ const sample = JSON.parse(await readFile(sampleConfigPath, 'utf8'));
+ const installedExists = await access(installedConfigPath, constants.F_OK).then(() => true, () => false);
+ const installed = installedExists
+ ? JSON.parse(await readFile(installedConfigPath, 'utf8'))
+ : { stages: {} };
+ installed.stages = installed.stages || {};
+ if (installed.stages[STAGE_KEY]) {
+ console.log(`📝 ${STAGE_KEY} stage-config: already present`);
+ return;
+ }
+ if (!sample?.stages?.[STAGE_KEY]) {
+ console.warn(`⚠️ ${STAGE_KEY}: sample stage-config missing ${STAGE_KEY} — skipping`);
+ return;
+ }
+ installed.stages[STAGE_KEY] = sample.stages[STAGE_KEY];
+ await mkdir(dirname(installedConfigPath), { recursive: true });
+ await writeFile(installedConfigPath, JSON.stringify(installed, null, 2) + '\n', 'utf8');
+ const action = installedExists ? 'merged' : 'created';
+ console.log(`📝 ${STAGE_KEY} stage-config (${action}): 1 added`);
+ } catch (err) {
+ console.warn(`⚠️ ${STAGE_KEY}: stage-config merge failed: ${err.message}`);
+ }
+ },
+};
diff --git a/scripts/migrations/104-editorial-mirror-description-stage.test.js b/scripts/migrations/104-editorial-mirror-description-stage.test.js
new file mode 100644
index 0000000000..424a3e49be
--- /dev/null
+++ b/scripts/migrations/104-editorial-mirror-description-stage.test.js
@@ -0,0 +1,86 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+
+import migration from './104-editorial-mirror-description-stage.js';
+
+// scripts/migrations/<this> → ../.. is the repo root (matches _testHelpers.js).
+const repoRoot = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
+
+// First-shipment seed migration (mirrors 101) — no MD5 bookkeeping, so the
+// seed / no-clobber behavior is asserted directly.
+
+const FILENAME = 'pipeline-editorial-mirror-description.md';
+const STAGE_KEY = 'pipeline-editorial-mirror-description';
+const BODY = '# Mirror self-description\n\nshipped body\n';
+
+describe('migration 104 — seed editorial-mirror-description stage', () => {
+ let rootDir;
+ let stagesDir;
+ let refStagesDir;
+ let installedConfigPath;
+
+ const seedReference = ({ withConfig = true } = {}) => {
+ writeFileSync(join(refStagesDir, FILENAME), BODY);
+ if (withConfig) {
+ const refConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ writeFileSync(
+ refConfigPath,
+ JSON.stringify({ stages: { [STAGE_KEY]: { name: STAGE_KEY, description: 'desc', model: 'default', returnsJson: true, variables: [] } } }, null, 2) + '\n',
+ );
+ }
+ };
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-104-'));
+ stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ refStagesDir = join(rootDir, 'data.reference', 'prompts', 'stages');
+ installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ mkdirSync(stagesDir, { recursive: true });
+ mkdirSync(refStagesDir, { recursive: true });
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ });
+
+ it('seeds the .md template and merges the stage-config entry on a fresh install', async () => {
+ seedReference();
+ await expect(migration.up({ rootDir })).resolves.not.toThrow();
+ expect(readFileSync(join(stagesDir, FILENAME), 'utf8')).toBe(BODY);
+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));
+ expect(installed.stages[STAGE_KEY]).toMatchObject({ returnsJson: true });
+ });
+
+ it('is idempotent and never clobbers a customized .md or an existing stage-config entry', async () => {
+ seedReference();
+ const customBody = '# CUSTOMIZED — do not overwrite\n';
+ writeFileSync(join(stagesDir, FILENAME), customBody);
+ writeFileSync(
+ installedConfigPath,
+ JSON.stringify({ stages: { [STAGE_KEY]: { name: 'user-tuned', model: 'custom' } } }, null, 2) + '\n',
+ );
+
+ await migration.up({ rootDir });
+
+ expect(readFileSync(join(stagesDir, FILENAME), 'utf8')).toBe(customBody);
+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));
+ expect(installed.stages[STAGE_KEY]).toEqual({ name: 'user-tuned', model: 'custom' });
+ });
+
+ it('does not throw when the data.reference samples are missing', async () => {
+ await expect(migration.up({ rootDir })).resolves.not.toThrow();
+ expect(existsSync(join(stagesDir, FILENAME))).toBe(false);
+ });
+
+ it('matches the live shipped stage-config key + prompt file (drift catch)', () => {
+ const refConfig = JSON.parse(
+ readFileSync(join(repoRoot, 'data.reference', 'prompts', 'stage-config.json'), 'utf8'),
+ );
+ expect(refConfig.stages[STAGE_KEY], `stage-config missing ${STAGE_KEY}`).toBeTruthy();
+ expect(refConfig.stages[STAGE_KEY].returnsJson).toBe(true);
+ expect(existsSync(join(repoRoot, 'data.reference', 'prompts', 'stages', FILENAME))).toBe(true);
+ });
+});
diff --git a/scripts/migrations/105-editorial-dialogue-pleasantries-stage.js b/scripts/migrations/105-editorial-dialogue-pleasantries-stage.js
new file mode 100644
index 0000000000..22ac012c0d
--- /dev/null
+++ b/scripts/migrations/105-editorial-dialogue-pleasantries-stage.js
@@ -0,0 +1,75 @@
+/**
+ * Seed the `pipeline-editorial-dialogue-pleasantries` stage into existing installs (#1300).
+ *
+ * Mirrors `101-editorial-dead-metaphor-stage.js`: copies the `.md` template from
+ * `data.reference/prompts/stages/` and merges the stage-config entry into
+ * `data/prompts/stage-config.json`. Boot runs migrations (server/index.js) but
+ * NOT `setup-data.js`, so an upgrade that pulls + `pm2 restart`s (rather than
+ * running `update.sh`) would otherwise leave the new dialogue-pleasantries stage
+ * unseeded and the `dialogue.pleasantries` editorial check would throw "Stage not
+ * found" the first time it runs.
+ */
+
+import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';
+import { dirname, join } from 'path';
+
+const FILENAME = 'pipeline-editorial-dialogue-pleasantries.md';
+const STAGE_KEY = 'pipeline-editorial-dialogue-pleasantries';
+
+export default {
+ async up({ rootDir }) {
+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ await mkdir(stagesDir, { recursive: true });
+
+ const dataPath = join(stagesDir, FILENAME);
+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', FILENAME);
+
+ const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);
+ if (exists) {
+ console.log(`📝 ${STAGE_KEY} prompt: already present`);
+ } else {
+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
+ if (!sampleExists) {
+ console.warn(`⚠️ ${STAGE_KEY}: sample missing for ${FILENAME} — skipping copy`);
+ } else {
+ try {
+ await copyFile(samplePath, dataPath);
+ console.log(`✅ seeded ${FILENAME}`);
+ } catch (err) {
+ console.warn(`⚠️ ${STAGE_KEY}: copy failed for ${FILENAME}: ${err.message}`);
+ }
+ }
+ }
+
+ const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);
+ if (!sampleConfigExists) {
+ console.warn(`⚠️ ${STAGE_KEY}: data.reference stage-config.json missing — cannot resolve entry; skipping config write`);
+ return;
+ }
+ try {
+ const sample = JSON.parse(await readFile(sampleConfigPath, 'utf8'));
+ const installedExists = await access(installedConfigPath, constants.F_OK).then(() => true, () => false);
+ const installed = installedExists
+ ? JSON.parse(await readFile(installedConfigPath, 'utf8'))
+ : { stages: {} };
+ installed.stages = installed.stages || {};
+ if (installed.stages[STAGE_KEY]) {
+ console.log(`📝 ${STAGE_KEY} stage-config: already present`);
+ return;
+ }
+ if (!sample?.stages?.[STAGE_KEY]) {
+ console.warn(`⚠️ ${STAGE_KEY}: sample stage-config missing ${STAGE_KEY} — skipping`);
+ return;
+ }
+ installed.stages[STAGE_KEY] = sample.stages[STAGE_KEY];
+ await mkdir(dirname(installedConfigPath), { recursive: true });
+ await writeFile(installedConfigPath, JSON.stringify(installed, null, 2) + '\n', 'utf8');
+ const action = installedExists ? 'merged' : 'created';
+ console.log(`📝 ${STAGE_KEY} stage-config (${action}): 1 added`);
+ } catch (err) {
+ console.warn(`⚠️ ${STAGE_KEY}: stage-config merge failed: ${err.message}`);
+ }
+ },
+};
diff --git a/scripts/migrations/105-editorial-dialogue-pleasantries-stage.test.js b/scripts/migrations/105-editorial-dialogue-pleasantries-stage.test.js
new file mode 100644
index 0000000000..3fd10a6196
--- /dev/null
+++ b/scripts/migrations/105-editorial-dialogue-pleasantries-stage.test.js
@@ -0,0 +1,86 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+
+import migration from './105-editorial-dialogue-pleasantries-stage.js';
+
+// scripts/migrations/<this> → ../.. is the repo root (matches _testHelpers.js).
+const repoRoot = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
+
+// First-shipment seed migration (mirrors 101) — no MD5 bookkeeping, so the
+// seed / no-clobber behavior is asserted directly.
+
+const FILENAME = 'pipeline-editorial-dialogue-pleasantries.md';
+const STAGE_KEY = 'pipeline-editorial-dialogue-pleasantries';
+const BODY = '# Empty greeting\n\nshipped body\n';
+
+describe('migration 105 — seed editorial-dialogue-pleasantries stage', () => {
+ let rootDir;
+ let stagesDir;
+ let refStagesDir;
+ let installedConfigPath;
+
+ const seedReference = ({ withConfig = true } = {}) => {
+ writeFileSync(join(refStagesDir, FILENAME), BODY);
+ if (withConfig) {
+ const refConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ writeFileSync(
+ refConfigPath,
+ JSON.stringify({ stages: { [STAGE_KEY]: { name: STAGE_KEY, description: 'desc', model: 'default', returnsJson: true, variables: [] } } }, null, 2) + '\n',
+ );
+ }
+ };
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-105-'));
+ stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ refStagesDir = join(rootDir, 'data.reference', 'prompts', 'stages');
+ installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ mkdirSync(stagesDir, { recursive: true });
+ mkdirSync(refStagesDir, { recursive: true });
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ });
+
+ it('seeds the .md template and merges the stage-config entry on a fresh install', async () => {
+ seedReference();
+ await expect(migration.up({ rootDir })).resolves.not.toThrow();
+ expect(readFileSync(join(stagesDir, FILENAME), 'utf8')).toBe(BODY);
+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));
+ expect(installed.stages[STAGE_KEY]).toMatchObject({ returnsJson: true });
+ });
+
+ it('is idempotent and never clobbers a customized .md or an existing stage-config entry', async () => {
+ seedReference();
+ const customBody = '# CUSTOMIZED — do not overwrite\n';
+ writeFileSync(join(stagesDir, FILENAME), customBody);
+ writeFileSync(
+ installedConfigPath,
+ JSON.stringify({ stages: { [STAGE_KEY]: { name: 'user-tuned', model: 'custom' } } }, null, 2) + '\n',
+ );
+
+ await migration.up({ rootDir });
+
+ expect(readFileSync(join(stagesDir, FILENAME), 'utf8')).toBe(customBody);
+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));
+ expect(installed.stages[STAGE_KEY]).toEqual({ name: 'user-tuned', model: 'custom' });
+ });
+
+ it('does not throw when the data.reference samples are missing', async () => {
+ await expect(migration.up({ rootDir })).resolves.not.toThrow();
+ expect(existsSync(join(stagesDir, FILENAME))).toBe(false);
+ });
+
+ it('matches the live shipped stage-config key + prompt file (drift catch)', () => {
+ const refConfig = JSON.parse(
+ readFileSync(join(repoRoot, 'data.reference', 'prompts', 'stage-config.json'), 'utf8'),
+ );
+ expect(refConfig.stages[STAGE_KEY], `stage-config missing ${STAGE_KEY}`).toBeTruthy();
+ expect(refConfig.stages[STAGE_KEY].returnsJson).toBe(true);
+ expect(existsSync(join(repoRoot, 'data.reference', 'prompts', 'stages', FILENAME))).toBe(true);
+ });
+});
diff --git a/scripts/migrations/106-editorial-kill-your-darlings-stage.js b/scripts/migrations/106-editorial-kill-your-darlings-stage.js
new file mode 100644
index 0000000000..4bb04e200d
--- /dev/null
+++ b/scripts/migrations/106-editorial-kill-your-darlings-stage.js
@@ -0,0 +1,75 @@
+/**
+ * Seed the `pipeline-editorial-kill-your-darlings` stage into existing installs (#1300).
+ *
+ * Mirrors `101-editorial-dead-metaphor-stage.js`: copies the `.md` template from
+ * `data.reference/prompts/stages/` and merges the stage-config entry into
+ * `data/prompts/stage-config.json`. Boot runs migrations (server/index.js) but
+ * NOT `setup-data.js`, so an upgrade that pulls + `pm2 restart`s (rather than
+ * running `update.sh`) would otherwise leave the new kill-your-darlings stage
+ * unseeded and the `prose.kill-your-darlings` editorial check would throw "Stage
+ * not found" the first time it runs.
+ */
+
+import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';
+import { dirname, join } from 'path';
+
+const FILENAME = 'pipeline-editorial-kill-your-darlings.md';
+const STAGE_KEY = 'pipeline-editorial-kill-your-darlings';
+
+export default {
+ async up({ rootDir }) {
+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ await mkdir(stagesDir, { recursive: true });
+
+ const dataPath = join(stagesDir, FILENAME);
+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', FILENAME);
+
+ const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);
+ if (exists) {
+ console.log(`📝 ${STAGE_KEY} prompt: already present`);
+ } else {
+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
+ if (!sampleExists) {
+ console.warn(`⚠️ ${STAGE_KEY}: sample missing for ${FILENAME} — skipping copy`);
+ } else {
+ try {
+ await copyFile(samplePath, dataPath);
+ console.log(`✅ seeded ${FILENAME}`);
+ } catch (err) {
+ console.warn(`⚠️ ${STAGE_KEY}: copy failed for ${FILENAME}: ${err.message}`);
+ }
+ }
+ }
+
+ const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);
+ if (!sampleConfigExists) {
+ console.warn(`⚠️ ${STAGE_KEY}: data.reference stage-config.json missing — cannot resolve entry; skipping config write`);
+ return;
+ }
+ try {
+ const sample = JSON.parse(await readFile(sampleConfigPath, 'utf8'));
+ const installedExists = await access(installedConfigPath, constants.F_OK).then(() => true, () => false);
+ const installed = installedExists
+ ? JSON.parse(await readFile(installedConfigPath, 'utf8'))
+ : { stages: {} };
+ installed.stages = installed.stages || {};
+ if (installed.stages[STAGE_KEY]) {
+ console.log(`📝 ${STAGE_KEY} stage-config: already present`);
+ return;
+ }
+ if (!sample?.stages?.[STAGE_KEY]) {
+ console.warn(`⚠️ ${STAGE_KEY}: sample stage-config missing ${STAGE_KEY} — skipping`);
+ return;
+ }
+ installed.stages[STAGE_KEY] = sample.stages[STAGE_KEY];
+ await mkdir(dirname(installedConfigPath), { recursive: true });
+ await writeFile(installedConfigPath, JSON.stringify(installed, null, 2) + '\n', 'utf8');
+ const action = installedExists ? 'merged' : 'created';
+ console.log(`📝 ${STAGE_KEY} stage-config (${action}): 1 added`);
+ } catch (err) {
+ console.warn(`⚠️ ${STAGE_KEY}: stage-config merge failed: ${err.message}`);
+ }
+ },
+};
diff --git a/scripts/migrations/106-editorial-kill-your-darlings-stage.test.js b/scripts/migrations/106-editorial-kill-your-darlings-stage.test.js
new file mode 100644
index 0000000000..5a0e412cbd
--- /dev/null
+++ b/scripts/migrations/106-editorial-kill-your-darlings-stage.test.js
@@ -0,0 +1,86 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+
+import migration from './106-editorial-kill-your-darlings-stage.js';
+
+// scripts/migrations/<this> → ../.. is the repo root (matches _testHelpers.js).
+const repoRoot = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
+
+// First-shipment seed migration (mirrors 101) — no MD5 bookkeeping, so the
+// seed / no-clobber behavior is asserted directly.
+
+const FILENAME = 'pipeline-editorial-kill-your-darlings.md';
+const STAGE_KEY = 'pipeline-editorial-kill-your-darlings';
+const BODY = '# Kill your darlings\n\nshipped body\n';
+
+describe('migration 106 — seed editorial-kill-your-darlings stage', () => {
+ let rootDir;
+ let stagesDir;
+ let refStagesDir;
+ let installedConfigPath;
+
+ const seedReference = ({ withConfig = true } = {}) => {
+ writeFileSync(join(refStagesDir, FILENAME), BODY);
+ if (withConfig) {
+ const refConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ writeFileSync(
+ refConfigPath,
+ JSON.stringify({ stages: { [STAGE_KEY]: { name: STAGE_KEY, description: 'desc', model: 'default', returnsJson: true, variables: [] } } }, null, 2) + '\n',
+ );
+ }
+ };
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-106-'));
+ stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ refStagesDir = join(rootDir, 'data.reference', 'prompts', 'stages');
+ installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ mkdirSync(stagesDir, { recursive: true });
+ mkdirSync(refStagesDir, { recursive: true });
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ });
+
+ it('seeds the .md template and merges the stage-config entry on a fresh install', async () => {
+ seedReference();
+ await expect(migration.up({ rootDir })).resolves.not.toThrow();
+ expect(readFileSync(join(stagesDir, FILENAME), 'utf8')).toBe(BODY);
+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));
+ expect(installed.stages[STAGE_KEY]).toMatchObject({ returnsJson: true });
+ });
+
+ it('is idempotent and never clobbers a customized .md or an existing stage-config entry', async () => {
+ seedReference();
+ const customBody = '# CUSTOMIZED — do not overwrite\n';
+ writeFileSync(join(stagesDir, FILENAME), customBody);
+ writeFileSync(
+ installedConfigPath,
+ JSON.stringify({ stages: { [STAGE_KEY]: { name: 'user-tuned', model: 'custom' } } }, null, 2) + '\n',
+ );
+
+ await migration.up({ rootDir });
+
+ expect(readFileSync(join(stagesDir, FILENAME), 'utf8')).toBe(customBody);
+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));
+ expect(installed.stages[STAGE_KEY]).toEqual({ name: 'user-tuned', model: 'custom' });
+ });
+
+ it('does not throw when the data.reference samples are missing', async () => {
+ await expect(migration.up({ rootDir })).resolves.not.toThrow();
+ expect(existsSync(join(stagesDir, FILENAME))).toBe(false);
+ });
+
+ it('matches the live shipped stage-config key + prompt file (drift catch)', () => {
+ const refConfig = JSON.parse(
+ readFileSync(join(repoRoot, 'data.reference', 'prompts', 'stage-config.json'), 'utf8'),
+ );
+ expect(refConfig.stages[STAGE_KEY], `stage-config missing ${STAGE_KEY}`).toBeTruthy();
+ expect(refConfig.stages[STAGE_KEY].returnsJson).toBe(true);
+ expect(existsSync(join(repoRoot, 'data.reference', 'prompts', 'stages', FILENAME))).toBe(true);
+ });
+});
diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.md
index 11fa2ed1d5..76866488e2 100644
--- a/server/lib/editorial/README.md
+++ b/server/lib/editorial/README.md
@@ -93,4 +93,5 @@ runner-injected `ctx.callInlineLLM` (an inline-prompt sibling of
| `checkRegistry.js` | `EDITORIAL_CHECKS` array + `EDITORIAL_SOURCES` (the per-check `sources` vocabulary the staleness runner fingerprints, #1387) + fail-fast guards + lookup/state helpers (`getCheck`, `getCheckById`, `getAllChecks`, `listChecks`, `resolveCheckState`, `getEnabledChecks`, `resolveCheckConfig`). User-defined-check helpers (`buildCustomCheck`, `buildCustomCheckPrompt`, `readCustomCheckDefs`, `isCustomCheckId`, `isValidCustomCheckDef`). Ships two reference checks: `naming.dissimilar-names` (deterministic) and `prose.info-dumping` (LLM). |
| `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. |
| `index.js` | Barrel re-export of the above. |
diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.js
index a00126bf07..a29054a67d 100644
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@ -28,6 +28,7 @@ import { z } from 'zod';
import { estimateTokens } from '../contextBudget.js';
import { analyzeNamePair, findFirstLetterClusters, normalizeName } from './nameSimilarity.js';
import { findCliches, findModifierStacking } from './cliches.js';
+import { findItalicThoughts } from './italicThoughts.js';
export const CHECK_SCOPES = Object.freeze(['series', 'issue', 'scene', 'noun']);
export const CHECK_KINDS = Object.freeze(['deterministic', 'llm']);
@@ -159,6 +160,17 @@ export function authoredSetupPayoffSummary(readerMap) {
// deterministic siblings (prose.cliches, prose.modifier-stacking) need no stage.
export const DEAD_METAPHOR_STAGE = 'pipeline-editorial-dead-metaphor';
+// Stage names for the four LLM prose anti-pattern checks (#1300). Each prompt
+// ships in data.reference/prompts/stages/ + stage-config.json (fresh installs via
+// setup-data.js) and migrates to existing installs via migrations 103–106 (boot
+// runs migrations but NOT setup-data, so the migration is required — see
+// scripts/migrations/103-…js … 106-…js). The deterministic sibling
+// (prose.italic-thoughts) needs no stage.
+export const OPENING_START_STAGE = 'pipeline-editorial-opening-start';
+export const MIRROR_DESCRIPTION_STAGE = 'pipeline-editorial-mirror-description';
+export const DIALOGUE_PLEASANTRIES_STAGE = 'pipeline-editorial-dialogue-pleasantries';
+export const KILL_YOUR_DARLINGS_STAGE = 'pipeline-editorial-kill-your-darlings';
+
// Render the authored reader-map cliffhangers (#1298) into a compact text block
// the chapter-ending check passes alongside the manuscript so the model
// reconciles its DETECTED endings against the issue-boundary tugs the writer
@@ -2180,6 +2192,224 @@ export const EDITORIAL_CHECKS = [
buildVars: (manuscript) => ({ manuscript }),
}),
},
+ {
+ id: 'opening.wrong-start',
+ sources: ['manuscript'],
+ label: 'Weak opening (wrong place to start)',
+ description:
+ 'LLM scan — flags clichéd or weak story/scene openers: "he wakes up" / alarm-clock / waking-from-a-dream starts, weather/scene-setting preambles, and openings that begin before the interesting moment. A scene should open as late into the action as it can.',
+ scope: 'issue',
+ kind: 'llm',
+ category: 'opening',
+ severityDefault: 'medium',
+ defaultEnabled: true,
+ needsManuscript: true,
+ configSchema: z.object({
+ // Cap findings per run so a long manuscript can't flood the review.
+ maxFindings: z.number().int().min(1).max(50).default(12),
+ }),
+ configFields: [
+ {
+ key: 'maxFindings',
+ label: 'Max findings per run',
+ type: 'number',
+ min: 1,
+ max: 50,
+ step: 1,
+ help: 'Cap findings so a long manuscript can not flood the review.',
+ },
+ ],
+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,
+ // Localized to chapter/scene openings (one finding per opener), so this stays
+ // a plain per-chunk run with no cross-chunk digest — mirrors prose.info-dumping.
+ run: (ctx) => runManuscriptLlmCheck(ctx, {
+ stage: OPENING_START_STAGE,
+ category: 'opening',
+ overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS,
+ buildVars: (manuscript) => ({ manuscript }),
+ }),
+ },
+ {
+ id: 'prose.mirror-description',
+ sources: ['manuscript'],
+ label: 'Mirror self-description',
+ description:
+ 'LLM scan — flags the "character looks at themselves in a mirror/reflection to describe their own appearance" trick, a tired device for slipping a viewpoint character\'s description onto the page.',
+ scope: 'issue',
+ kind: 'llm',
+ category: 'cliche',
+ severityDefault: 'medium',
+ defaultEnabled: true,
+ needsManuscript: true,
+ configSchema: z.object({
+ // Cap findings per run so a long manuscript can't flood the review.
+ maxFindings: z.number().int().min(1).max(50).default(12),
+ }),
+ configFields: [
+ {
+ key: 'maxFindings',
+ label: 'Max findings per run',
+ type: 'number',
+ min: 1,
+ max: 50,
+ step: 1,
+ help: 'Cap findings so a long manuscript can not flood the review.',
+ },
+ ],
+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,
+ // Each mirror moment is a localized spot — plain per-chunk run, no digest.
+ run: (ctx) => runManuscriptLlmCheck(ctx, {
+ stage: MIRROR_DESCRIPTION_STAGE,
+ category: 'cliche',
+ overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS,
+ buildVars: (manuscript) => ({ manuscript }),
+ }),
+ },
+ {
+ id: 'dialogue.pleasantries',
+ sources: ['manuscript'],
+ label: 'Empty greeting / small-talk openings',
+ description:
+ 'LLM scan — flags scenes that open on empty greeting or small-talk exchanges ("Hi." "Hi, how are you?") that carry no tension or information. Dialogue should start in the middle of the exchange that matters.',
+ scope: 'issue',
+ kind: 'llm',
+ category: 'dialogue',
+ severityDefault: 'low',
+ defaultEnabled: true,
+ needsManuscript: true,
+ configSchema: z.object({
+ // Cap findings per run so a long manuscript can't flood the review.
+ maxFindings: z.number().int().min(1).max(50).default(12),
+ }),
+ configFields: [
+ {
+ key: 'maxFindings',
+ label: 'Max findings per run',
+ type: 'number',
+ min: 1,
+ max: 50,
+ step: 1,
+ help: 'Cap findings so a long manuscript can not flood the review.',
+ },
+ ],
+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,
+ // Localized to scene openings — plain per-chunk run, no digest.
+ run: (ctx) => runManuscriptLlmCheck(ctx, {
+ stage: DIALOGUE_PLEASANTRIES_STAGE,
+ category: 'dialogue',
+ overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS,
+ buildVars: (manuscript) => ({ manuscript }),
+ }),
+ },
+ {
+ id: 'prose.kill-your-darlings',
+ sources: ['manuscript'],
+ label: 'Kill your darlings (precious / self-indulgent passages)',
+ description:
+ 'LLM scan — surfaces over-written, precious passages: a flourish, digression, or showpiece that serves the author more than the story and is a candidate to cut. Complements prose.dead-metaphor, which targets stock rather than self-indulgent prose.',
+ scope: 'issue',
+ kind: 'llm',
+ category: 'style',
+ severityDefault: 'low',
+ defaultEnabled: true,
+ needsManuscript: true,
+ configSchema: z.object({
+ // Cap findings per run so a long manuscript can't flood the review.
+ maxFindings: z.number().int().min(1).max(50).default(12),
+ }),
+ configFields: [
+ {
+ key: 'maxFindings',
+ label: 'Max findings per run',
+ type: 'number',
+ min: 1,
+ max: 50,
+ step: 1,
+ help: 'Cap findings so a long manuscript can not flood the review.',
+ },
+ ],
+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,
+ // Localized prose-level findings (one precious passage = one spot) — plain
+ // per-chunk run, no cross-chunk digest.
+ run: (ctx) => runManuscriptLlmCheck(ctx, {
+ stage: KILL_YOUR_DARLINGS_STAGE,
+ category: 'style',
+ overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS,
+ buildVars: (manuscript) => ({ manuscript }),
+ }),
+ },
+ {
+ id: 'prose.italic-thoughts',
+ sources: ['manuscript'],
+ label: 'Italicized internal thoughts',
+ description:
+ 'Deterministic scan — flags multi-word italicized internal-thought runs ("*He knows I lied.*"). The prose is already in the character\'s perspective, so italicizing a thought is a tell; the run usually reads cleaner as plain narration. Short italic spans (a stressed word, a title, a foreign term) are left alone as emphasis.',
+ scope: 'issue',
+ kind: 'deterministic',
+ category: 'style',
+ severityDefault: 'low',
+ defaultEnabled: true,
+ // Reads the stitched manuscript (per-issue sections) to anchor each run.
+ needsManuscript: true,
+ configSchema: z.object({
+ // Minimum word count for an italic span to count as a thought (vs emphasis).
+ minWords: z.number().int().min(1).max(20).default(4),
+ // Cap findings per run so a thought-italics-heavy draft can't flood the review.
+ maxFindings: z.number().int().min(1).max(50).default(20),
+ }),
+ configFields: [
+ {
+ key: 'minWords',
+ label: 'Minimum words to flag',
+ type: 'number',
+ min: 1,
+ max: 20,
+ step: 1,
+ help: 'How many words an italic span must have before it is treated as an internal thought rather than emphasis. 4 skips single stressed words, titles, and foreign terms.',
+ },
+ {
+ key: 'maxFindings',
+ label: 'Max findings per run',
+ type: 'number',
+ min: 1,
+ max: 50,
+ step: 1,
+ help: 'Cap findings so a thought-italics-heavy draft can not flood the review.',
+ },
+ ],
+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,
+ run: (ctx) => {
+ const cfg = ctx.config || {};
+ const minWords = cfg.minWords ?? 4;
+ const max = cfg.maxFindings ?? 20;
+ const sections = Array.isArray(ctx.sections) ? ctx.sections : [];
+ const findings = [];
+ // One finding per distinct thought run (anchored to the first issue it
+ // appears in) — the same italicized thought repeated is one tic to fix.
+ const seenRuns = new Set();
+ for (const s of sections) {
+ if (findings.length >= max) break;
+ const hits = findItalicThoughts(s?.content || '', { minWords });
+ for (const hit of hits) {
+ if (findings.length >= max) break;
+ const key = hit.inner.toLowerCase();
+ if (seenRuns.has(key)) continue;
+ seenRuns.add(key);
+ const issueNumber = Number.isInteger(s?.number) ? s.number : null;
+ findings.push({
+ severity: ctx.severityDefault,
+ category: 'style',
+ location: issueNumber != null ? `Issue ${issueNumber}` : 'Manuscript',
+ problem: `Italicized internal thought ("${hit.anchor}") — the prose is already in the character's perspective, so italicizing a thought is a tell that usually reads cleaner as plain narration.`,
+ suggestion: 'Drop the italics and let the thought stand as narration, or recast it as a beat of action/observation if it needs more grounding.',
+ anchorQuote: hit.anchor,
+ issueNumber,
+ });
+ }
+ }
+ return findings;
+ },
+ },
{
id: 'endings.cliffhanger',
sources: ['manuscript', 'series.arc.readerMap'],
diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.js
index b53e35e021..f0dfb67363 100644
--- a/server/lib/editorial/checkRegistry.test.js
+++ b/server/lib/editorial/checkRegistry.test.js
@@ -2132,3 +2132,104 @@ describe('prose.cliches / prose.modifier-stacking / prose.dead-metaphor (#1308)'
expect(findings[0].issueNumber).toBe(4);
});
});
+
+describe('prose anti-pattern bundle (#1300)', () => {
+ const OPENING = 'opening.wrong-start';
+ const MIRROR = 'prose.mirror-description';
+ const PLEASANTRIES = 'dialogue.pleasantries';
+ const DARLINGS = 'prose.kill-your-darlings';
+ const ITALICS = 'prose.italic-thoughts';
+
+ // The four LLM checks share the manuscript-chunk harness — assert each is a
+ // registered manuscript-scoped LLM check that forces its own category and
+ // passes the planned chunk through.
+ const LLM_CHECKS = [
+ { id: OPENING, category: 'opening' },
+ { id: MIRROR, category: 'cliche' },
+ { id: PLEASANTRIES, category: 'dialogue' },
+ { id: DARLINGS, category: 'style' },
+ ];
+
+ it('registers all five bundle checks (4 LLM + 1 deterministic)', () => {
+ const ids = listChecks().map((c) => c.id);
+ for (const { id } of LLM_CHECKS) expect(ids).toContain(id);
+ expect(ids).toContain(ITALICS);
+ });
+
+ for (const { id, category } of LLM_CHECKS) {
+ it(`${id} is a manuscript-scoped LLM check gated on prose`, () => {
+ const c = getCheck(id);
+ expect(c.kind).toBe('llm');
+ expect(c.category).toBe(category);
+ expect(c.sources).toEqual(['manuscript']);
+ expect(c.needsManuscript).toBe(true);
+ expect(c.gate({ manuscript: '' })).toBe(false);
+ expect(c.gate({ manuscript: '# Issue 1\n\nprose' })).toBeTruthy();
+ });
+
+ it(`${id} passes the planned chunk to the model and forces its category`, async () => {
+ let seen = null;
+ const findings = await getCheck(id).run({
+ manuscript: '# Issue 2\n\nSome drafted prose.',
+ config: { maxFindings: 12 },
+ severityDefault: getCheck(id).severityDefault,
+ planManuscriptChunks: async (_stage, opts) => {
+ expect(opts.overheadTokens).toBeGreaterThan(0);
+ return ['# Issue 2\n\nSome drafted prose.'];
+ },
+ callStagedLLM: async (_stage, vars) => {
+ seen = vars.manuscript;
+ return { content: { findings: [{ severity: 'medium', issueNumber: 2, problem: 'p', anchorQuote: 'a' }] } };
+ },
+ });
+ expect(seen).toBe('# Issue 2\n\nSome drafted prose.');
+ expect(findings).toHaveLength(1);
+ expect(findings[0].category).toBe(category);
+ expect(findings[0].issueNumber).toBe(2);
+ });
+ }
+
+ describe('prose.italic-thoughts — deterministic check', () => {
+ const run = (sections, config = {}) =>
+ getCheck(ITALICS).run({ sections, config, severityDefault: 'low' });
+
+ it('declares the expected scope / kind / sources', () => {
+ const c = getCheck(ITALICS);
+ expect(c.kind).toBe('deterministic');
+ expect(c.category).toBe('style');
+ expect(c.sources).toEqual(['manuscript']);
+ expect(c.needsManuscript).toBe(true);
+ });
+
+ it('flags a multi-word italicized thought and anchors it to its issue', () => {
+ const findings = run([{ number: 3, content: 'She froze. *He knows I lied to him.* Then she ran.' }]);
+ expect(findings).toHaveLength(1);
+ expect(findings[0].issueNumber).toBe(3);
+ expect(findings[0].category).toBe('style');
+ expect(findings[0].severity).toBe('low');
+ expect(findings[0].anchorQuote).toBe('*He knows I lied to him.*');
+ });
+
+ it('ignores short emphasis spans below the word threshold', () => {
+ expect(run([{ number: 1, content: 'She would *never* do that.' }])).toEqual([]);
+ });
+
+ it('dedups the same thought across issues and honors maxFindings', () => {
+ const sections = [
+ { number: 1, content: '*I have to get out of here.*' },
+ { number: 2, content: '*I have to get out of here.* again' },
+ { number: 3, content: '*A completely different worried thought.*' },
+ ];
+ const deduped = run(sections);
+ expect(deduped).toHaveLength(2); // repeated thought counted once
+ const capped = run(sections, { maxFindings: 1 });
+ expect(capped).toHaveLength(1);
+ });
+
+ it('honors a custom minWords threshold', () => {
+ const sections = [{ number: 1, content: 'He paused. *What now?* he wondered.' }];
+ expect(run(sections)).toEqual([]); // 2 words < default 4
+ expect(run(sections, { minWords: 2 })).toHaveLength(1);
+ });
+ });
+});
diff --git a/server/lib/editorial/index.js b/server/lib/editorial/index.js
index 8ce758db22..3663cc6992 100644
--- a/server/lib/editorial/index.js
+++ b/server/lib/editorial/index.js
@@ -2,4 +2,5 @@
// (#1284). See README.md for the catalog. Re-export every public module here.
export * from './checkRegistry.js';
export * from './cliches.js';
+export * from './italicThoughts.js';
export * from './nameSimilarity.js';
diff --git a/server/lib/editorial/italicThoughts.js b/server/lib/editorial/italicThoughts.js
new file mode 100644
index 0000000000..d8f8c9aedc
--- /dev/null
+++ b/server/lib/editorial/italicThoughts.js
@@ -0,0 +1,65 @@
+/**
+ * Italicized-internal-thought deterministic primitive (#1300) for the editorial
+ * check registry. Pure and dependency-free (no side-effecting imports) so it
+ * stays unit-testable in isolation — mirrors ./cliches.js and ./nameSimilarity.js.
+ *
+ * Backs the deterministic `prose.italic-thoughts` check in checkRegistry.js. The
+ * editorial rule: everything on the page is already the POV character's
+ * perspective, so setting internal thoughts in *italics* is a tell — a multi-word
+ * italic clause is almost always a narrated thought that could simply be prose.
+ *
+ * High-precision by design (favors under-flagging, like the other deterministic
+ * scanners): a SHORT italic span (a stressed word, a title, a foreign term) is
+ * emphasis, not a thought, so only runs of `minWords`+ words are flagged. The LLM
+ * siblings handle the judgment cases this can't.
+ */
+
+// Markdown italic delimiters. Asterisk italics are a single `*` NOT part of a
+// `**`/`***` bold run; underscore italics are a single `_` with non-word edges
+// (so `snake_case` and `__bold__` are never mistaken for emphasis). Each span is
+// single-line (`[^*\n]` / `[^_\n]`) — a thought run that spans a blank line is a
+// paragraph, not an inline italic clause.
+const ASTERISK_ITALIC_RE = /(?<!\*)\*(?!\*)([^*\n]+?)\*(?!\*)/g;
+const UNDERSCORE_ITALIC_RE = /(?<![\w_])_(?!_)([^_\n]+?)_(?![\w_])/g;
+
+// Count whitespace-delimited words in an italic span's inner text.
+function wordCount(text) {
+ const m = String(text).trim().match(/\S+/g);
+ return m ? m.length : 0;
+}
+
+/**
+ * Find italicized runs in `text` that read as internal-thought narration —
+ * multi-word italic spans (markdown `*…*` or `_…_`). Returns the FIRST occurrence
+ * of each distinct run (deduped on the normalized inner text — the same thought
+ * italicized twice is one tic to fix, not two), sorted by position.
+ *
+ * @param {string} text
+ * @param {{ minWords?: number }} [opts]
+ * minWords — minimum word count for an italic span to count as a thought run
+ * (default 4; a shorter span is treated as emphasis and skipped). Floored at 1.
+ * @returns {Array<{ inner: string, index: number, anchor: string, words: number }>}
+ * inner — the text between the markers; anchor — the verbatim span WITH markers.
+ */
+export function findItalicThoughts(text, opts = {}) {
+ if (typeof text !== 'string' || !text) return [];
+ const minWords = Math.max(1, Number.isInteger(opts.minWords) ? opts.minWords : 4);
+ const found = [];
+ const seen = new Set();
+ const scan = (re) => {
+ re.lastIndex = 0;
+ let m;
+ while ((m = re.exec(text)) !== null) {
+ const inner = m[1].trim();
+ const words = wordCount(inner);
+ if (words < minWords) continue;
+ const key = inner.toLowerCase();
+ if (seen.has(key)) continue;
+ seen.add(key);
+ found.push({ inner, index: m.index, anchor: m[0], words });
+ }
+ };
+ scan(ASTERISK_ITALIC_RE);
+ scan(UNDERSCORE_ITALIC_RE);
+ return found.sort((a, b) => a.index - b.index);
+}
diff --git a/server/lib/editorial/italicThoughts.test.js b/server/lib/editorial/italicThoughts.test.js
new file mode 100644
index 0000000000..590671fd69
--- /dev/null
+++ b/server/lib/editorial/italicThoughts.test.js
@@ -0,0 +1,65 @@
+import { describe, it, expect } from 'vitest';
+import { findItalicThoughts } from './italicThoughts.js';
+
+describe('findItalicThoughts', () => {
+ it('flags a multi-word asterisk-italic thought run', () => {
+ const hits = findItalicThoughts('She froze. *He knows I lied to him.* Then she ran.');
+ expect(hits).toHaveLength(1);
+ expect(hits[0].inner).toBe('He knows I lied to him.');
+ expect(hits[0].anchor).toBe('*He knows I lied to him.*');
+ expect(hits[0].words).toBe(6);
+ });
+
+ it('flags a multi-word underscore-italic thought run', () => {
+ const hits = findItalicThoughts('_This cannot be happening again._');
+ expect(hits).toHaveLength(1);
+ expect(hits[0].inner).toBe('This cannot be happening again.');
+ });
+
+ it('ignores short italic spans (emphasis, not a thought)', () => {
+ // "*never*" and "_run_" are single-word emphasis — below the default minWords.
+ expect(findItalicThoughts('She would *never* do that. He told her to _run_.')).toEqual([]);
+ });
+
+ it('does not mistake bold (** / ***) for italic thoughts', () => {
+ expect(findItalicThoughts('**This is bold and not a thought.**')).toEqual([]);
+ expect(findItalicThoughts('***This is bold italic emphasis here.***')).toEqual([]);
+ });
+
+ it('does not treat snake_case or __bold__ underscores as emphasis', () => {
+ expect(findItalicThoughts('The file my_long_variable_name was edited.')).toEqual([]);
+ expect(findItalicThoughts('__This is underscore bold not a thought.__')).toEqual([]);
+ });
+
+ it('does not span across newlines (a paragraph is not an inline thought)', () => {
+ expect(findItalicThoughts('*one line\nsecond line and more words here*')).toEqual([]);
+ });
+
+ it('dedups the same thought italicized more than once (first-wins, by position)', () => {
+ const hits = findItalicThoughts('*I have to get out.* ... later ... *I have to get out.*');
+ expect(hits).toHaveLength(1);
+ expect(hits[0].index).toBe(0);
+ });
+
+ it('honors a custom minWords threshold', () => {
+ const text = 'He paused. *What now?* he wondered.';
+ expect(findItalicThoughts(text)).toEqual([]); // "What now?" = 2 words < default 4
+ const hits = findItalicThoughts(text, { minWords: 2 });
+ expect(hits).toHaveLength(1);
+ expect(hits[0].inner).toBe('What now?');
+ });
+
+ it('returns runs sorted by position across both delimiters', () => {
+ const hits = findItalicThoughts('_The first thought arrives._ Then *the second thought lands hard.*');
+ expect(hits.map((h) => h.inner)).toEqual([
+ 'The first thought arrives.',
+ 'the second thought lands hard.',
+ ]);
+ });
+
+ it('returns [] for non-string or empty input', () => {
+ expect(findItalicThoughts(null)).toEqual([]);
+ expect(findItalicThoughts('')).toEqual([]);
+ expect(findItalicThoughts('Plain prose with no italics at all.')).toEqual([]);
+ });
+});