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: editorial check for theme coherence / thematic throughline (#1317)
Adam Eivyf46310e8f200
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6cbdcaa45b..c3480591be 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **[issue-1317] Editorial check flags theme-coherence problems — themes stated but never dramatized, dropped after the opening, or unpaid at the climax (plus emergent-theme detection).** A new **Theme coherence / thematic throughline** LLM check (Create → Editorial Checks) asks whether the manuscript actually *delivers* the themes the story arc declares (`series.arc.themes`), not just names them. For each declared theme it builds a setup → complication → payoff coverage map and flags a theme that is **stated but never dramatized** through a character's choices or the central conflict, a theme that is **dropped** after the opening, and a climax that **resolves the plot but never lands the thematic argument** the setup promised. It also detects a strong **emergent theme** the story is really telling that isn't in the declared list — offering to add it (or reconciling it when the story drifts into a competing argument). It reads your reverse-outline scene segmentation as context so it can attribute a theme's setup/payoff to a scene + issue, and **degrades gracefully** — no authored themes ⇒ it works from the prose alone to surface emergent themes; no outline ⇒ it scans the whole manuscript. Whole-arc judgments (a dropped theme, an unpaid climax) are deferred until it has seen the final chunk, and cross-chunk findings + clean-setup digests keep a long book reviewed in pieces from false-flagging a theme whose payoff lands later. Findings render as `Theme` notes anchored to the issue + a verbatim quote. Ships a new stage prompt (`pipeline-editorial-theme-coherence`) that migrates for existing installs (115). (`server/lib/editorial/checkRegistry.js`, `server/services/pipeline/editorial/checkRunner.js`, `data.reference/prompts/stages/pipeline-editorial-theme-coherence.md`, `scripts/migrations/115-editorial-theme-coherence-stage.js`, Part of #1283, #1317)+- **[issue-1316] Editorial health score + revision-trend tracking — *manage* the draft, not just receive findings.** A new **Editorial Health** panel (Create → Editorial Checks, alongside the findings triage) turns the point-in-time manuscript-review findings into a metric you can steer by. A transparent, deterministic **health score** (0–100, per series with a per-issue drill-down) is computed from the OPEN findings weighted by severity — `100 − Σ weight(severity)` with published weights (high 12 / medium 5 / low 1), so it's never a black box; accepted (fixed) and dismissed (waived) findings cost nothing. A **revision-trend ledger** snapshots the open-finding counts (by severity + category) on each editorial-checks / completeness run — the run is the revision boundary — so the panel renders a **score sparkline** across revisions, the most-recent-revision **delta**, and per-category **regressions** (a category that got *worse* after an edit pass). A configurable **readiness gate** ("no open high findings" by default, or the stricter "no high or medium", or "none") is the convergence signal the UI shows as **Ready / Not ready** *and* that the **autopilot editorial loop** now reads as a final gate (`editorialHealthGate`): after both editorial passes seed their findings, autopilot pauses with the residual blockers if the manuscript isn't clean — catching a blocker the registry checks surface *after* the completeness loop converged. The trend ledger is install-local telemetry (`data/pipeline-editorial-health/{seriesId}.json`, not synced); the score/readiness are derived live from the synced review. Scoring is pure + unit-tested. (`server/services/pipeline/editorialScore.js`, `server/routes/pipeline/editorial.js`, `server/services/pipeline/{editorial/checkRunner,manuscriptCompletenessRunner,seriesAutopilot}.js`, `client/src/components/pipeline/editorial/EditorialHealthPanel.jsx`, `client/src/lib/editorialHealth.js`, Part of #1283, #1316)- **[issue-1315] Storyboard shots now record camera framing + screen direction, and a new editorial check catches film-grammar continuity errors before render.** Each storyboard shot gains two film-grammar fields — **shot type** (extreme-wide / wide / medium / close / extreme-close / over-the-shoulder / two-shot / POV) and **screen direction** (the side the subject faces or moves: left / right / neutral) — captured by the scene extractor (the teleplay→scenes prompt now asks the model to tag them) and carried on the shot record. A new deterministic **Storyboard shot continuity** check (Create → Editorial Checks) reads those fields and flags two classic film-grammar mistakes *before* you spend render time on a clip: a **180-degree-rule axis reversal** — a shot that continues from an earlier one but flips the subject to the opposite side of the screen, so they appear to jump sides across the cut — and **shot-type monotony**, a scene whose shots all share one framing and read as flat, slideshow coverage with no establishing wide or punch-in. Findings render as `Continuity` notes anchored to the offending issue + scene, and (being deterministic) need no LLM. Both fields are backward-compatible and default to "not captured," so older storyboards simply aren't flagged until re-extracted; the extraction-prompt change migrates for existing installs (114). Eyeline-match and appearance/prop continuity (which need a vision/LLM pass) and a hard pre-render render-gate are tracked as follow-ups. (`server/lib/shotGrammar.js`, `server/lib/sceneExtractor.js`, `server/lib/editorial/shotContinuity.js`, `server/lib/editorial/checkRegistry.js`, `server/services/pipeline/editorial/checkRunner.js`, `scripts/migrations/114-extract-scenes-shot-grammar.js`, #1315)diff --git a/client/src/components/pipeline/manuscript/constants.js b/client/src/components/pipeline/manuscript/constants.jsindex e74b7dea3b..e7dbd2751b 100644--- a/client/src/components/pipeline/manuscript/constants.js+++ b/client/src/components/pipeline/manuscript/constants.js@@ -38,6 +38,9 @@ export const CATEGORY_LABEL = {// Plot-structure findings (#1310): passive protagonist, deus ex machina, idiot// plot, flat stakes, sagging middle, dropped subplots from plot.structure-momentum.plot: 'Plot structure',+ // Theme-coherence findings (#1317): stated-but-undramatized / dropped / unpaid+ // themes and emergent-theme suggestions from the theme.coherence check.+ theme: 'Theme',pacing: 'Pacing',continuity: 'Continuity',style: 'Style',diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex 11f727e78d..6a40ac80fb 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -631,6 +631,13 @@"model": "default","returnsJson": true,"variables": []+ },+ "pipeline-editorial-theme-coherence": {+ "name": "Pipeline — Editorial Check: Theme coherence / thematic throughline",+ "description": "Editorial check (#1317): whether the manuscript actually DELIVERS its declared themes (series.arc.themes), not just states them. Builds a per-theme setup/complication/payoff coverage map, flags a theme that is stated but never dramatized or dropped after the opening, detects a strong EMERGENT theme not in the arc, and checks that the climax lands the thematic argument. Reads the stitched manuscript plus the authored arc themes and the reverse-outline scene map; degrades to a whole-manuscript scan when no outline or no themes exist. Returns issue-anchored findings.",+ "model": "default",+ "returnsJson": true,+ "variables": []}}}diff --git a/data.reference/prompts/stages/pipeline-editorial-theme-coherence.md b/data.reference/prompts/stages/pipeline-editorial-theme-coherence.mdnew file mode 100644index 0000000000..c6fd68a668--- /dev/null+++ b/data.reference/prompts/stages/pipeline-editorial-theme-coherence.md@@ -0,0 +1,120 @@+# Pipeline — Editorial Check: Theme coherence / thematic throughline++You are a developmental editor doing a single focused pass for ONE concern:+**theme coherence** — whether the story actually *dramatizes* its themes, not just+states them. A theme is delivered through what the characters choose, what the+plot tests, and what the ending argues — not by a character announcing the moral.+Judge the manuscript as a whole: is each declared theme set up, complicated, and+paid off, or is it merely named and then abandoned?++Flag only these pathologies (each is a distinct finding):++- **Stated but undramatized theme** — a declared theme that is named or gestured at+ but never enacted through a character's choices, the central conflict, or a cost+ paid. The theme floats above the story instead of being argued by it.+- **Dropped theme** — a theme that is set up early (the opening raises it) and then+ disappears: no complication, no payoff, the later chapters forget it.+- **Theme with no payoff at the climax** — the climax/resolution settles the PLOT+ (who wins, what happens) but never lands the thematic argument the setup promised.+ The reader gets an ending but not a *meaning*.+- **Strong emergent theme not declared** — the story is clearly, consistently+ dramatizing a theme that is NOT in the declared list (the work is "about" something+ the arc never recorded). Surface it as an emergent-theme suggestion so the author+ can add it to the arc, OR reconcile it against the declared themes if it+ contradicts/competes with them (the story drifts into a different argument than+ the one it set out to make).++Do NOT flag: a theme delivered through subtext and action rather than stated+aloud (that is the GOAL, not a problem); a deliberately ambiguous or open ending+where withholding a tidy thematic resolution is the point; a theme whose payoff+clearly belongs to a planned later installment when the manuscript is mid-arc.++{{#declaredThemes}}+## Declared themes++The author logged these themes on the story arc. Build a per-theme coverage map:+for EACH theme, locate where the prose sets it up, complicates it, and resolves+it, and flag the gaps (stated-but-undramatized, dropped, or unpaid at the climax).++```+{{declaredThemes}}+```+{{/declaredThemes}}+{{^declaredThemes}}+## Declared themes++No themes are declared on the story arc. Work from the prose alone: identify the+strongest theme(s) the manuscript is actually dramatizing and surface them as+emergent-theme suggestions the author could add to the arc.+{{/declaredThemes}}++{{#sceneMap}}+## Scene segmentation++The reverse outline below segments the manuscript into scenes (with the recorded+setting, POV character, and characters present). Use it to attribute a theme's+setup/complication/payoff to a scene and its issue.++```+{{sceneMap}}+```+{{/sceneMap}}++## 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 header to attribute every finding to its `issueNumber`.++```+{{manuscript}}+```++{{#finalPart}}+You are seeing the FINAL part of the manuscript, so you may now make whole-story+judgments: a theme that is set up but never paid off, a theme dropped after the+opening, and whether the climax lands each declared theme's argument. The "setup+so far" digest above tells you which themes earlier parts set up or complicated.+{{/finalPart}}+{{^finalPart}}+You are seeing an EARLIER part of a long manuscript reviewed in pieces. Do NOT yet+flag a dropped theme or a theme with no payoff — a later part may pay it off. Flag+only what you can judge from the text in view (a theme stated outright but not+dramatized in this part) and note emergent themes. The "setup so far" digest above+carries which themes earlier parts opened so you don't re-flag them.+{{/finalPart}}++## Task++Build the per-theme coverage map and identify the pathologies above. For each+finding set `location` to the pathology + a pointer, e.g.+`Undramatized theme — "the cost of loyalty"`, `Dropped theme — "forgiveness", last+seen Issue 2`, `Emergent theme — survival vs. belonging`, `Theme unpaid at climax —+"freedom"`. Quote a short verbatim anchor (≤ 200 chars) at the relevant moment+where one exists (omit `anchorQuote` for a whole-arc judgment like a theme dropped+across the back half or an unpaid climax). Severity: a declared central theme that+is never dramatized or never pays off is high; a strong undeclared emergent theme+or a secondary theme dropped late is medium; a minor thematic gap is low. If every+declared theme is set up, complicated, and paid off — and no strong competing+emergent theme is unaddressed — return an empty `findings` array. Do not invent+thematic problems where the story coheres.++## 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 — pathology + theme pointer (e.g. 'Undramatized theme — \"the cost of loyalty\"' or 'Emergent theme — survival vs. belonging')",+ "problem": "1–3 sentences naming the thematic gap (which theme, what is missing: setup / complication / payoff) and why it weakens the story",+ "suggestion": "1–3 sentences proposing how to fix it (dramatize the theme through a choice, plant a complication, land it at the climax, or add the emergent theme to the arc)",+ "anchorQuote": "short verbatim quote at the moment (≤ 200 chars); omit for a whole-arc judgment"+ }+ ]+}+```diff --git a/scripts/migrations/115-editorial-theme-coherence-stage.js b/scripts/migrations/115-editorial-theme-coherence-stage.jsnew file mode 100644index 0000000000..b75d903269--- /dev/null+++ b/scripts/migrations/115-editorial-theme-coherence-stage.js@@ -0,0 +1,75 @@+/**+ * Seed the `pipeline-editorial-theme-coherence` stage into existing installs (#1317).+ *+ * Mirrors `111-editorial-plot-structure-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 theme-coherence stage+ * unseeded and the `theme.coherence` 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-theme-coherence.md';+const STAGE_KEY = 'pipeline-editorial-theme-coherence';++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(`📝 pipeline-editorial-theme-coherence prompt: already present`);+ } else {+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);+ if (!sampleExists) {+ console.warn(`⚠️ pipeline-editorial-theme-coherence: sample missing for ${FILENAME} — skipping copy`);+ } else {+ try {+ await copyFile(samplePath, dataPath);+ console.log(`✅ seeded ${FILENAME}`);+ } catch (err) {+ console.warn(`⚠️ pipeline-editorial-theme-coherence: 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('⚠️ pipeline-editorial-theme-coherence: 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(`📝 pipeline-editorial-theme-coherence stage-config: already present`);+ return;+ }+ if (!sample?.stages?.[STAGE_KEY]) {+ console.warn(`⚠️ pipeline-editorial-theme-coherence: 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(`📝 pipeline-editorial-theme-coherence stage-config (${action}): 1 added`);+ } catch (err) {+ console.warn(`⚠️ pipeline-editorial-theme-coherence: stage-config merge failed: ${err.message}`);+ }+ },+};diff --git a/scripts/migrations/115-editorial-theme-coherence-stage.test.js b/scripts/migrations/115-editorial-theme-coherence-stage.test.jsnew file mode 100644index 0000000000..1f3cf265a4--- /dev/null+++ b/scripts/migrations/115-editorial-theme-coherence-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 './115-editorial-theme-coherence-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 111) — no MD5 bookkeeping, so the+// seed / no-clobber behavior is asserted directly.++const FILENAME = 'pipeline-editorial-theme-coherence.md';+const STAGE_KEY = 'pipeline-editorial-theme-coherence';+const BODY = '# Theme coherence / thematic throughline\n\nshipped body\n';++describe('migration 115 — seed editorial-theme-coherence 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-115-'));+ 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.mdindex 0089148f02..158afb765e 100644--- a/server/lib/editorial/README.md+++ b/server/lib/editorial/README.md@@ -57,8 +57,12 @@ it. To add a new built-in check, append an entry to `EDITORIAL_CHECKS` inDeclare every input the check's `run(ctx)` reads in its `sources` array (anon-empty subset of `EDITORIAL_SOURCES`: `manuscript`, `canon`,`series.styleGuide`, `series.arc.tickingClock`, `series.arc.readerMap`,-`reverseOutline`, `reverseOutline.plotlines`, `editorialArcs`,-`series.characterArcs`, `storyboard.shots`, `comicScript`). The staleness+`series.arc.themes`, `reverseOutline`, `reverseOutline.plotlines`,+`editorialArcs`, `series.characterArcs`, `storyboard.shots`, `comicScript`).+The `series.arc.themes` token (#1317) fingerprints the AUTHORED arc themes the+`theme.coherence` check reconciles the prose against (lives on the already-loaded+series record, no extra I/O — adding/editing a declared theme stales its findings).+The stalenessrunner fingerprints exactly those sources, so a finding goes stale only whencontent the check actually analyzed drifts — declare too few and a finding staysfalsely fresh; a `manuscript` source must pair with `needsManuscript: true`, anddiff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.jsindex 1c4a3c2e95..9d6741be6a 100644--- a/server/lib/editorial/checkRegistry.js+++ b/server/lib/editorial/checkRegistry.js@@ -115,6 +115,7 @@ export const EDITORIAL_SOURCES = Object.freeze(['series.styleGuide','series.arc.tickingClock','series.arc.readerMap',+ 'series.arc.themes','reverseOutline','reverseOutline.plotlines','editorialArcs',@@ -308,6 +309,33 @@ export const PLOT_STRUCTURE_STAGE = 'pipeline-editorial-plot-structure';// character's head or reports what the POV character can't perceive.export const HEAD_HOPPING_STAGE = 'pipeline-editorial-head-hopping';+// Stage name for the theme-coherence / thematic-throughline LLM check (#1317).+// Ships in data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 115 (boot runs+// migrations but NOT setup-data, so the migration is required). Reads the stitched+// manuscript plus the AUTHORED arc themes (series.arc.themes) and the reverse-outline+// scene map, and reconciles whether each declared theme is set up / complicated /+// paid off — surfacing stated-but-undramatized themes, dropped themes, a strong+// emergent theme not in the arc, and a climax that resolves plot but not theme.+export const THEME_COHERENCE_STAGE = 'pipeline-editorial-theme-coherence';++// Render the authored arc themes (#1317) into a compact text block the+// theme-coherence check passes alongside the manuscript, so the model reconciles+// whether the prose actually sets up / complicates / pays off each DECLARED theme+// (vs. stating it but never dramatizing it, or dropping it after the opening).+// Pure + deterministic so it's unit-testable and its token cost can be counted+// into the per-chunk overhead. Returns '' when no themes are authored (the+// prompt's `{{#declaredThemes}}` section then renders nothing and the check still+// runs to detect a strong emergent theme).+export function declaredThemesSummary(themes) {+ const lines = (Array.isArray(themes) ? themes : [])+ .map((t) => (typeof t === 'string' ? t.trim() : ''))+ .filter(Boolean)+ .map((t) => `- ${t}`);+ if (!lines.length) return '';+ return `Declared themes (authored on the story arc):\n${lines.join('\n')}`;+}+// 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@@ -2286,6 +2314,77 @@ export const EDITORIAL_CHECKS = [});},},+ {+ id: 'theme.coherence',+ sources: ['manuscript', 'series.arc.themes', 'reverseOutline'],+ label: 'Theme coherence / thematic throughline',+ description:+ 'Checks whether the manuscript actually DELIVERS its declared themes (series.arc.themes), not just states them. For each authored theme it maps where the story sets it up, complicates it, and pays it off — flagging a theme that is stated but never dramatized, or dropped after the opening. Detects a strong EMERGENT theme the story is really telling that is not in the arc (offers to add it), and checks that the climax/resolution lands the thematic argument (vs. resolving plot but not theme). Reads the reverse-outline scene map to attribute setup/payoff to scenes; degrades to a whole-manuscript scan when no outline or no themes exist.',+ scope: 'series',+ kind: 'llm',+ category: 'theme',+ severityDefault: 'medium',+ defaultEnabled: true,+ // Reads the stitched manuscript corpus — so the runner only pays the+ // section-collection I/O when a manuscript-consuming check is enabled.+ 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,+ run: (ctx) => {+ // Both blocks are fixed per-call overhead (re-sent on each chunk) and pure+ // context: the declared themes let the model build a per-theme setup/+ // complication/payoff coverage map and reconcile detected vs. authored+ // themes; the scene map lets it attribute setup/payoff to a scene + issue.+ // The check degrades gracefully — no authored themes ⇒ {{#declaredThemes}}+ // renders nothing and the check works from the prose alone to surface a+ // strong emergent theme; no outline ⇒ {{#sceneMap}} renders nothing.+ const declaredThemes = declaredThemesSummary(ctx.series?.arc?.themes);+ const sceneMap = sceneGroundingSummary(ctx.reverseOutline);+ return runManuscriptLlmCheck(ctx, {+ stage: THEME_COHERENCE_STAGE,+ category: 'theme',+ overheadTokens:+ EDITORIAL_PROMPT_OVERHEAD_TOKENS+ + estimateTokens(declaredThemes)+ + estimateTokens(sceneMap),+ // `isFinal` gates the whole-corpus judgments — a theme that is set up but+ // never paid off, a theme dropped after the opening, and whether the+ // climax lands the thematic argument can only be judged once the whole+ // manuscript is in view; an earlier chunk can't know a theme is paid off+ // later, so it would false-flag.+ buildVars: (manuscript, meta) => ({+ manuscript,+ declaredThemes,+ sceneMap,+ finalPart: meta?.isFinal ? 'true' : '',+ }),+ // Theme coverage accrues across the whole manuscript — the findings digest+ // keeps prior findings in view so a later chunk doesn't re-flag, and the+ // clean-setup digest rolls forward which themes have been set up /+ // complicated so a later payoff isn't mis-read as a dropped theme.+ crossChunkDigest: true,+ crossChunkSetup: true,+ setupFocus: 'For each declared theme, note where it has been set up or complicated so far '+ + 'and whether it has been paid off yet; and note any strong EMERGENT theme the story '+ + 'is dramatizing that is not in the declared list, so a later chunk can tell a genuinely '+ + 'dropped/undramatized theme from one whose payoff simply has not arrived yet.',+ });+ },+ },{id: 'relationships.reciprocity',sources: ['canon'],diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.jsindex 004357560e..7204197b9f 100644--- a/server/lib/editorial/checkRegistry.test.js+++ b/server/lib/editorial/checkRegistry.test.js@@ -33,6 +33,7 @@ import {characterVoiceProfiles,plotlineCoverageSummary,scenePovSummary,+ declaredThemesSummary,} from './checkRegistry.js';const NAMING = 'naming.dissimilar-names';@@ -45,6 +46,7 @@ const SENSORY_BALANCE = 'sensory.balance';const WHITE_ROOM = 'scene.white-room';const PLOT_STRUCTURE = 'plot.structure-momentum';const HEAD_HOPPING = 'pov.head-hopping';+const THEME_COHERENCE = 'theme.coherence';// A minimal valid stored custom-check definition.const customDef = (over = {}) => ({@@ -808,6 +810,109 @@ describe('plotlineCoverageSummary (#1310)', () => {});});+describe('theme.coherence — LLM check (#1317)', () => {+ const wholeCtx = (overrides = {}) => ({+ manuscript: '# Issue 1\n\nShe chose loyalty, and it cost her everything.',+ config: { maxFindings: 12 },+ severityDefault: 'medium',+ series: { arc: { themes: ['the cost of loyalty', 'forgiveness'] } },+ reverseOutline: [{ sequence: 0, issueNumber: 1, heading: 'Opening', setting: 'a war room' }],+ planManuscriptChunks: async () => ['# Issue 1\n\nShe chose loyalty.'],+ callStagedLLM: async () => ({ content: { findings: [] } }),+ ...overrides,+ });++ it('is registered as a series-scoped LLM check reading manuscript + arc themes + outline', () => {+ const check = getCheck(THEME_COHERENCE);+ expect(check.kind).toBe('llm');+ expect(check.scope).toBe('series');+ expect(check.category).toBe('theme');+ expect(check.sources).toEqual(['manuscript', 'series.arc.themes', 'reverseOutline']);+ expect(check.needsManuscript).toBe(true);+ });++ it('only runs when there is drafted prose to scan', () => {+ const check = getCheck(THEME_COHERENCE);+ expect(check.gate({ manuscript: '' })).toBe(false);+ expect(check.gate({ manuscript: '# Issue 1\n\nprose' })).toBeTruthy();+ });++ it('passes the manuscript, declared themes, and scene map to the model and forces the theme category', async () => {+ let seenVars = null;+ const ctx = wholeCtx({+ planManuscriptChunks: async (_stage, opts) => {+ // Declared themes + scene map both ride as fixed overhead.+ expect(opts.overheadTokens).toBeGreaterThan(0);+ return ['# Issue 1\n\nForgiveness is never mentioned again.'];+ },+ callStagedLLM: async (_stage, vars) => {+ seenVars = vars;+ return { content: { findings: [{ severity: 'high', issueNumber: 1, location: 'Dropped theme — "forgiveness"', problem: 'Set up then abandoned' }] } };+ },+ });+ const findings = await getCheck(THEME_COHERENCE).run(ctx);+ expect(seenVars.manuscript).toBe('# Issue 1\n\nForgiveness is never mentioned again.');+ expect(seenVars.declaredThemes).toContain('the cost of loyalty');+ expect(seenVars.declaredThemes).toContain('forgiveness');+ expect(seenVars.sceneMap).toContain('Issue 1: Opening');+ expect(findings).toHaveLength(1);+ expect(findings[0].category).toBe('theme');+ expect(findings[0].location).toBe('Dropped theme — "forgiveness"');+ });++ it('passes empty context vars when the series has no themes or outline', async () => {+ let seenVars = null;+ const ctx = wholeCtx({+ series: {},+ reverseOutline: undefined,+ callStagedLLM: async (_stage, vars) => { seenVars = vars; return { content: { findings: [] } }; },+ });+ await getCheck(THEME_COHERENCE).run(ctx);+ expect(seenVars.declaredThemes).toBe('');+ expect(seenVars.sceneMap).toBe('');+ });++ it('marks a single-chunk run as the final part so whole-arc judgments are enabled', async () => {+ let seenVars = null;+ const ctx = wholeCtx({+ callStagedLLM: async (_stage, vars) => { seenVars = vars; return { content: { findings: [] } }; },+ });+ await getCheck(THEME_COHERENCE).run(ctx);+ expect(seenVars.finalPart).toBe('true');+ });++ it('flags only the LAST part as final across a chunked manuscript', async () => {+ const finals = [];+ const ctx = wholeCtx({+ planManuscriptChunks: async () => ['# Issue 1\n\np1', '# Issue 2\n\np2', '# Issue 3\n\np3'],+ callStagedLLM: async (_stage, vars) => { finals.push(vars.finalPart); return { content: { findings: [] } }; },+ });+ await getCheck(THEME_COHERENCE).run(ctx);+ expect(finals).toEqual(['', '', 'true']);+ });+});++describe('declaredThemesSummary (#1317)', () => {+ it('returns an empty string when there are no themes', () => {+ expect(declaredThemesSummary(null)).toBe('');+ expect(declaredThemesSummary(undefined)).toBe('');+ expect(declaredThemesSummary([])).toBe('');+ expect(declaredThemesSummary(['', ' '])).toBe('');+ });++ it('renders one bullet per theme under a header', () => {+ const out = declaredThemesSummary(['the cost of loyalty', 'forgiveness']);+ expect(out).toContain('Declared themes (authored on the story arc):');+ expect(out).toContain('- the cost of loyalty');+ expect(out).toContain('- forgiveness');+ });++ it('is type-guarded against hand-edited / older-peer rows and trims whitespace', () => {+ const out = declaredThemesSummary([42, null, ' identity ', { x: 1 }]);+ expect(out.split('\n').filter((l) => l.startsWith('- '))).toEqual(['- identity']);+ });+});+describe('endings.cliffhanger — LLM check (#1298)', () => {const wholeCtx = (overrides = {}) => ({manuscript: '# Issue 1\n\nAnd so, with the war finally over, they all went home and rested.',diff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.jsindex 9ff977849b..dc74a668c8 100644--- a/server/services/pipeline/editorial/checkRunner.js+++ b/server/services/pipeline/editorial/checkRunner.js@@ -59,6 +59,10 @@ const SOURCE_RESOLVERS = {'series.arc.tickingClock': ({ series }) => canonicalStringify(series?.arc?.tickingClock ?? null),// The authored reader-map hooks/payoffs the Chekhov check reconciles against (#1299).'series.arc.readerMap': ({ series }) => canonicalStringify(series?.arc?.readerMap ?? null),+ // The authored arc themes the theme.coherence check reconciles the prose against+ // (#1317). Lives on the already-loaded series record, so no extra I/O — fingerprint+ // the whole themes array so adding/editing a declared theme stales the findings.+ 'series.arc.themes': ({ series }) => canonicalStringify(series?.arc?.themes ?? null),// The reverse-outline scenes the check reads (#1296). Fingerprinting the whole// scenes array is intentionally over-eager (any scene edit stales a finding)// rather than under: safe vs. false-fresh, and the check reads several scene fields.