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([issue-1310]): editorial plot-structure & momentum check

Adam Eivy13e640850b87
diff --git a/client/src/components/pipeline/manuscript/constants.js b/client/src/components/pipeline/manuscript/constants.js
index 87734d166d..ee7156a602 100644
--- a/client/src/components/pipeline/manuscript/constants.js
+++ b/client/src/components/pipeline/manuscript/constants.js
@@ -35,6 +35,9 @@ export const CATEGORY_LABEL = {
// flat-arc warnings from the arc.transitions editorial check.
arc: 'Character arc',
'character-gap': 'Character gap',
+ // Plot-structure findings (#1310): passive protagonist, deus ex machina, idiot
+ // plot, flat stakes, sagging middle, dropped subplots from plot.structure-momentum.
+ plot: 'Plot structure',
pacing: 'Pacing',
continuity: 'Continuity',
style: 'Style',
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index 97d5dc907b..77f2d6ee6f 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -603,6 +603,13 @@
"model": "default",
"returnsJson": true,
"variables": []
+ },
+ "pipeline-editorial-plot-structure": {
+ "name": "Pipeline — Editorial Check: Plot structure & momentum",
+ "description": "Editorial check (#1310): the macro pathologies editors flag at the manuscript/arc level — a passive protagonist, deus ex machina / convenient coincidence, idiot plot, flat or unclear stakes that never escalate, a sagging middle with no try-fail rhythm, and dropped subplots. Reads the stitched manuscript plus the reverse-outline scene map + plotline coverage (reconciling fizzled threads against tagged plotlines) and the authored reader-map hooks/payoffs; degrades to a whole-manuscript scan when no outline exists. Returns issue-anchored findings.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
}
}
}
diff --git a/data.reference/prompts/stages/pipeline-editorial-plot-structure.md b/data.reference/prompts/stages/pipeline-editorial-plot-structure.md
new file mode 100644
index 0000000000..0eebe7447d
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-editorial-plot-structure.md
@@ -0,0 +1,132 @@
+# Pipeline — Editorial Check: Plot structure & momentum
+
+You are a developmental editor doing a single focused pass for ONE concern:
+**plot structure and momentum** — the macro pathologies that make a story drag,
+cheat, or fall flat. These are arc-level problems, not line-level ones. Judge the
+story as a whole: does the protagonist drive it, are the stakes clear and rising,
+does the middle keep escalating, and does every thread the author opened get
+resolved?
+
+Flag only these pathologies (each is a distinct finding category):
+
+- **Passive protagonist** — the protagonist reacts instead of acting; events
+ happen TO them and the plot is moved by coincidence or other characters rather
+ than their choices. Flag stretches where the lead makes no meaningful decision.
+- **Deus ex machina / convenient coincidence** — a problem resolved by luck, a
+ timely rescue, or contrivance instead of earned character agency or an earlier
+ setup. Coincidences that *help* the protagonist out of trouble are far more
+ suspect than ones that complicate their life.
+- **Idiot plot** — conflict that only persists because a character fails to do or
+ say the obvious (the "idiot ball"): a misunderstanding one honest sentence
+ would end, a danger anyone would simply walk away from.
+- **Unclear or flat stakes** — it isn't clear what the protagonist stands to lose,
+ the stakes are abstract/impersonal, or they never escalate. Flag a middle that
+ plateaus where tension should rise.
+- **Sagging middle / weak try-fail rhythm** — a slack midpoint where the story
+ marks time. A strong middle runs on escalating try-fail cycles (the hero tries,
+ fails, and the failure raises the cost of the next attempt); flag a stretch with
+ no such rhythm.
+- **Dropped subplot / unresolved thread** — a plotline or promise that starts and
+ then fizzles without a resolution scene. Reconcile against the tagged plotlines
+ below: a plotline whose scenes stop partway through the story and never return
+ is a dropped subplot.
+
+Do NOT flag: line-level prose problems (other checks own those); a deliberately
+quiet/literary structure where low external stakes are the point; an unresolved
+thread that is clearly a setup for a planned later installment when the manuscript
+is mid-arc.
+
+{{#authoredSetups}}
+## Authored hooks & payoffs
+
+The author logged these reader-map hooks (questions planted) and payoffs
+(resolutions). Use them to judge stakes and dropped threads: a logged hook with
+no payoff in the prose is a candidate dropped thread; a payoff with no setup is a
+candidate deus ex machina.
+
+```
+{{authoredSetups}}
+```
+{{/authoredSetups}}
+
+{{#plotlineMap}}
+## Plotline coverage
+
+The reverse outline tags each scene to a plotline. The coverage below shows, per
+plotline, how many scenes carry it and which issues they span. A plotline whose
+scenes stop well before the end and never resume is a likely dropped subplot —
+reconcile your dropped-thread findings against this list.
+
+```
+{{plotlineMap}}
+```
+{{/plotlineMap}}
+
+{{#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 pacing and
+stakes findings to a scene and its issue; judge the structure itself from the prose.
+
+```
+{{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 genuinely sagging middle, an arc whose stakes never
+escalate, and a subplot that is dropped (opened earlier and never resolved by the
+end). The "setup so far" digest above tells you what earlier parts opened.
+{{/finalPart}}
+{{^finalPart}}
+You are seeing an EARLIER part of a long manuscript reviewed in pieces. Do NOT
+yet flag a dropped subplot, a flat-stakes arc, or a sagging middle — a later part
+may pay them off. Flag only pathologies you can judge from the text in view
+(a passive stretch, a deus-ex-machina resolution, an idiot-plot beat). The "setup
+so far" digest above carries what earlier parts opened so you don't re-flag them.
+{{/finalPart}}
+
+## Task
+
+Identify the plot-structure pathologies above. For each finding set `location` to
+the pathology + a pointer, e.g. `Passive protagonist — Issue 4`, `Deus ex machina
+— the rescue at the docks`, `Dropped subplot — the missing-brother thread`. Quote
+a short verbatim anchor (≤ 200 chars) at the relevant moment where one exists
+(omit `anchorQuote` for a whole-arc judgment like a sagging middle or a flat
+stakes arc). Severity: a passive central protagonist, a deus-ex-machina climax, or
+a dropped major subplot is high; a minor coincidence or a single slack scene is
+low. If the plot is well-structured — an active protagonist, clear escalating
+stakes, a taut middle, and every thread resolved — return an empty `findings`
+array. Do not invent structural problems where the story is sound.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no
+commentary:
+
+```json
+{
+ "findings": [
+ {
+ "severity": "high|medium|low",
+ "issueNumber": 4,
+ "location": "string — pathology + pointer (e.g. 'Passive protagonist — Issue 4' or 'Dropped subplot — the missing-brother thread')",
+ "problem": "1–3 sentences naming the structural problem and why it weakens the story",
+ "suggestion": "1–3 sentences proposing how to fix it (give the lead a decision, plant the payoff earlier, resolve or cut the thread, raise the stakes)",
+ "anchorQuote": "short verbatim quote at the moment (≤ 200 chars); omit for a whole-arc judgment"
+ }
+ ]
+}
+```
diff --git a/scripts/migrations/111-editorial-plot-structure-stage.js b/scripts/migrations/111-editorial-plot-structure-stage.js
new file mode 100644
index 0000000000..9270619791
--- /dev/null
+++ b/scripts/migrations/111-editorial-plot-structure-stage.js
@@ -0,0 +1,75 @@
+/**
+ * Seed the `pipeline-editorial-plot-structure` stage into existing installs (#1310).
+ *
+ * Mirrors `110-editorial-telling-emotion-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 plot-structure stage
+ * unseeded and the `plot.structure-momentum` 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-plot-structure.md';
+const STAGE_KEY = 'pipeline-editorial-plot-structure';
+
+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-plot-structure prompt: already present`);
+ } else {
+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
+ if (!sampleExists) {
+ console.warn(`⚠️ pipeline-editorial-plot-structure: sample missing for ${FILENAME} — skipping copy`);
+ } else {
+ try {
+ await copyFile(samplePath, dataPath);
+ console.log(`✅ seeded ${FILENAME}`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-editorial-plot-structure: 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-plot-structure: 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-plot-structure stage-config: already present`);
+ return;
+ }
+ if (!sample?.stages?.[STAGE_KEY]) {
+ console.warn(`⚠️ pipeline-editorial-plot-structure: 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-plot-structure stage-config (${action}): 1 added`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-editorial-plot-structure: stage-config merge failed: ${err.message}`);
+ }
+ },
+};
diff --git a/scripts/migrations/111-editorial-plot-structure-stage.test.js b/scripts/migrations/111-editorial-plot-structure-stage.test.js
new file mode 100644
index 0000000000..24dac9ee17
--- /dev/null
+++ b/scripts/migrations/111-editorial-plot-structure-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 './111-editorial-plot-structure-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 109/110) — no MD5 bookkeeping, so the
+// seed / no-clobber behavior is asserted directly.
+
+const FILENAME = 'pipeline-editorial-plot-structure.md';
+const STAGE_KEY = 'pipeline-editorial-plot-structure';
+const BODY = '# Plot structure & momentum\n\nshipped body\n';
+
+describe('migration 111 — seed editorial-plot-structure 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-111-'));
+ 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 adfbe42b8c..38b6342a70 100644
--- a/server/lib/editorial/README.md
+++ b/server/lib/editorial/README.md
@@ -57,12 +57,16 @@ it. To add a new built-in check, append an entry to `EDITORIAL_CHECKS` in
Declare every input the check's `run(ctx)` reads in its `sources` array (a
non-empty subset of `EDITORIAL_SOURCES`: `manuscript`, `canon`,
`series.styleGuide`, `series.arc.tickingClock`, `series.arc.readerMap`,
-`reverseOutline`, `editorialArcs`, `series.characterArcs`). The staleness
+`reverseOutline`, `reverseOutline.plotlines`, `editorialArcs`,
+`series.characterArcs`). The staleness
runner fingerprints exactly those sources, so a finding goes stale only when
content the check actually analyzed drifts — declare too few and a finding stays
falsely fresh; a `manuscript` source must pair with `needsManuscript: true`, and
`reverseOutline` makes the runner fetch the cached reverse-outline (#1286) and
-inject `ctx.reverseOutline` (the scenes array). `editorialArcs` (#1295) makes the
+inject `ctx.reverseOutline` (the scenes array); `reverseOutline.plotlines` (#1310)
+injects `ctx.reverseOutlinePlotlines` (the outline's plotline list) off that same
+fetch, so the `plot.structure-momentum` check can reconcile dropped subplots
+against the author's tagged threads. `editorialArcs` (#1295) makes the
runner fetch the series editorial aggregate and inject `ctx.editorialArcs` (the
detected per-character `{ name, arcDirection, issueCount, isProtagonist }`
projection — the coarse DETECTED arc signal) plus a derived
diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.js
index 66cb4e19ca..afd065f3dd 100644
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@ -63,6 +63,13 @@ const SEVERITIES = CHECK_SEVERITIES;
// scenes carry components/povCharacter/charactersPresent.
// The runner fetches it (gated on this source) and injects
// `ctx.reverseOutline` (the scenes array).
+// - 'reverseOutline.plotlines' — the cached reverse-outline's PLOTLINE list (#1286):
+// `[{ id, label, kind, color }]` plus the per-scene
+// `plotlineId`/`secondaryPlotlineId` tags. The runner fetches
+// the outline (gated on this source) and injects
+// `ctx.reverseOutlinePlotlines`. The plot-structure check (#1310)
+// reconciles dropped subplots against these tagged plotlines —
+// which start and then fizzle without a resolution scene.
// - 'series.arc.readerMap' — the series arc's authored reader-map (#1299): the
// writer-logged hooks (questions planted) and payoffs
// (their resolutions). The Chekhov check reconciles its
@@ -85,6 +92,7 @@ export const EDITORIAL_SOURCES = Object.freeze([
'series.arc.tickingClock',
'series.arc.readerMap',
'reverseOutline',
+ 'reverseOutline.plotlines',
'editorialArcs',
'series.characterArcs',
]);
@@ -217,6 +225,16 @@ export const ARC_TRANSITIONS_STAGE = 'pipeline-editorial-arc-transitions';
// prose.sentence-rhythm) need no stage.
export const TELLING_EMOTION_STAGE = 'pipeline-editorial-telling-emotion';
+// Stage name for the plot-structure & momentum LLM check (#1310). Ships in
+// data.reference/prompts/stages/ + stage-config.json (fresh installs via
+// setup-data.js) and migrates to existing installs via migration 111 (boot runs
+// migrations but NOT setup-data, so the migration is required). Reads the
+// stitched manuscript plus the reverse-outline scene map + plotline coverage and
+// the authored reader-map/arc to surface macro pathologies — passive protagonist,
+// deus ex machina, idiot plot, flat/unclear stakes, sagging middle, and dropped
+// subplots reconciled against the tagged plotlines.
+export const PLOT_STRUCTURE_STAGE = 'pipeline-editorial-plot-structure';
+
// 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
@@ -992,6 +1010,43 @@ export function sceneGroundingSummary(scenes) {
return `Scenes (from the reverse outline):\n${lines.join('\n')}`;
}
+// Render the reverse-outline PLOTLINES (#1286) into a compact text block the
+// plot-structure check (#1310) passes alongside the manuscript so the model can
+// reconcile dropped subplots against the author's tagged plotlines — a plotline
+// that opens early and is never returned to is a dropped subplot. For each
+// plotline we count the scenes tagged to it (primary OR secondary) and report the
+// span of issues those scenes touch, so the model sees which threads fizzle.
+// Pure + deterministic so it's unit-testable and its token cost can be counted
+// into the per-chunk overhead. Returns '' when there are no plotlines (the
+// prompt's `{{#plotlineMap}}` section then renders nothing and the check degrades
+// to reasoning about subplots from the prose alone). Type-guarded throughout —
+// the reverse outline rides peer sync (#1348), so a hand-edited / older-peer
+// plotline could carry a non-string field a bare `.trim()` would throw on.
+export function plotlineCoverageSummary(plotlines, scenes) {
+ const lines = Array.isArray(plotlines) ? plotlines : [];
+ const sceneList = Array.isArray(scenes) ? scenes : [];
+ const rows = lines.map((pl) => {
+ if (!pl || typeof pl !== 'object') return '';
+ const id = typeof pl.id === 'string' ? pl.id : '';
+ if (!id) return '';
+ const label = typeof pl.label === 'string' && pl.label.trim() ? pl.label.trim() : id;
+ const kind = typeof pl.kind === 'string' && pl.kind.trim() ? pl.kind.trim() : 'other';
+ // Scenes tagged to this plotline (primary or secondary), in outline order.
+ const tagged = sceneList.filter((s) => s && (s.plotlineId === id || s.secondaryPlotlineId === id));
+ const issues = [...new Set(
+ tagged
+ .map((s) => (Number.isInteger(s.issueNumber) ? s.issueNumber : null))
+ .filter((n) => n != null),
+ )].sort((a, b) => a - b);
+ const span = issues.length
+ ? (issues.length === 1 ? `issue ${issues[0]}` : `issues ${issues[0]}–${issues[issues.length - 1]}`)
+ : 'no tagged scenes';
+ return `- ${label} (${kind}): ${tagged.length} scene${tagged.length === 1 ? '' : 's'}, ${span}`;
+ }).filter(Boolean);
+ if (!rows.length) return '';
+ return `Plotlines (from the reverse outline — reconcile dropped subplots against these):\n${rows.join('\n')}`;
+}
+
// ---------------------------------------------------------------------------
// Registry entries.
// ---------------------------------------------------------------------------
@@ -1698,6 +1753,80 @@ export const EDITORIAL_CHECKS = [
});
},
},
+ {
+ id: 'plot.structure-momentum',
+ sources: ['manuscript', 'reverseOutline', 'reverseOutline.plotlines', 'series.arc.readerMap'],
+ label: 'Plot structure & momentum',
+ description:
+ 'LLM scan for the macro pathologies editors flag at the manuscript/arc level: a passive protagonist (events happen TO them), deus ex machina / convenient coincidence, idiot plot (conflict that only persists because characters avoid the obvious), flat or unclear stakes that never escalate, a sagging middle with no try-fail rhythm, and dropped subplots. Reads the stitched manuscript plus the reverse-outline scene map + plotline coverage (reconciling fizzled threads against tagged plotlines) and the authored reader-map hooks/payoffs; degrades to a whole-manuscript scan when no outline exists.',
+ scope: 'series',
+ kind: 'llm',
+ category: 'plot',
+ 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) => {
+ // All three blocks are fixed per-call overhead (re-sent on each chunk) and
+ // pure context: the scene map lets the model attribute pacing/stakes findings
+ // to scenes, the plotline coverage lets it reconcile dropped subplots against
+ // the author's tagged threads, and the authored hooks/payoffs ground the
+ // stakes/escalation judgment. The check degrades gracefully — no outline ⇒
+ // {{#sceneMap}}/{{#plotlineMap}} render nothing; no reader map ⇒ {{#authoredSetups}}
+ // renders nothing and the model reasons from the prose alone.
+ const sceneMap = sceneGroundingSummary(ctx.reverseOutline);
+ const plotlineMap = plotlineCoverageSummary(ctx.reverseOutlinePlotlines, ctx.reverseOutline);
+ const authoredSetups = authoredSetupPayoffSummary(ctx.series?.arc?.readerMap);
+ return runManuscriptLlmCheck(ctx, {
+ stage: PLOT_STRUCTURE_STAGE,
+ category: 'plot',
+ overheadTokens:
+ EDITORIAL_PROMPT_OVERHEAD_TOKENS
+ + estimateTokens(sceneMap)
+ + estimateTokens(plotlineMap)
+ + estimateTokens(authoredSetups),
+ // `isFinal` gates the whole-corpus judgments — a sagging middle, a never-
+ // escalating arc, and a dropped subplot can only be judged once the whole
+ // manuscript is in view; an earlier chunk can't know a thread is picked back
+ // up (or stakes rise) later, so it would false-flag. A single-chunk run is
+ // its own final part and judges the whole text.
+ buildVars: (manuscript, meta) => ({
+ manuscript,
+ sceneMap,
+ plotlineMap,
+ authoredSetups,
+ finalPart: meta?.isFinal ? 'true' : '',
+ }),
+ // Plot pathologies span the whole arc — the cross-chunk findings digest keeps
+ // prior findings in view so a later chunk doesn't re-flag, and the clean-setup
+ // digest rolls forward which subplots/stakes have been opened so a later
+ // payoff (or escalation) isn't mis-read as a dropped/flat thread.
+ crossChunkDigest: true,
+ crossChunkSetup: true,
+ setupFocus: 'Open plot threads/subplots and whether each has been resolved yet; '
+ + 'the stakes established so far and whether they have escalated; and any setup '
+ + '(a planted problem, a coincidence, a try-fail attempt) a later part should pay off, '
+ + 'so a later chunk can tell a genuinely dropped subplot or flat-stakes arc 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.js
index 2255945eb5..7256c60a7b 100644
--- a/server/lib/editorial/checkRegistry.test.js
+++ b/server/lib/editorial/checkRegistry.test.js
@@ -30,6 +30,7 @@ import {
authoredSetupPayoffSummary,
authoredCliffhangerSummary,
sceneGroundingSummary,
+ plotlineCoverageSummary,
} from './checkRegistry.js';
const NAMING = 'naming.dissimilar-names';
@@ -40,6 +41,7 @@ const ENDINGS_CLIFF = 'endings.cliffhanger';
const POV_SWITCH = 'endings.pov-switch';
const SENSORY_BALANCE = 'sensory.balance';
const WHITE_ROOM = 'scene.white-room';
+const PLOT_STRUCTURE = 'plot.structure-momentum';
// A minimal valid stored custom-check definition.
const customDef = (over = {}) => ({
@@ -556,6 +558,132 @@ describe('authoredSetupPayoffSummary (#1299)', () => {
});
});
+describe('plot.structure-momentum — LLM check (#1310)', () => {
+ const wholeCtx = (overrides = {}) => ({
+ manuscript: '# Issue 1\n\nThings happened to her, and then more things happened.',
+ config: { maxFindings: 12 },
+ severityDefault: 'medium',
+ series: {},
+ reverseOutline: [{ sequence: 0, issueNumber: 1, heading: 'Opening', setting: 'a dock', plotlineId: 'a' }],
+ reverseOutlinePlotlines: [{ id: 'a', label: 'A-plot', kind: 'main' }, { id: 'b', label: 'The missing brother', kind: 'subplot' }],
+ planManuscriptChunks: async () => [overrides.manuscript ?? '# Issue 1\n\nThings happened to her.'],
+ callStagedLLM: async () => ({ content: { findings: [] } }),
+ ...overrides,
+ });
+
+ it('is registered as a series-scoped LLM check reading manuscript + outline + plotlines + reader-map', () => {
+ const check = getCheck(PLOT_STRUCTURE);
+ expect(check.kind).toBe('llm');
+ expect(check.scope).toBe('series');
+ expect(check.category).toBe('plot');
+ expect(check.sources).toEqual(['manuscript', 'reverseOutline', 'reverseOutline.plotlines', 'series.arc.readerMap']);
+ expect(check.needsManuscript).toBe(true);
+ });
+
+ it('only runs when there is drafted prose to scan', () => {
+ const check = getCheck(PLOT_STRUCTURE);
+ expect(check.gate({ manuscript: '' })).toBe(false);
+ expect(check.gate({ manuscript: '# Issue 1\n\nprose' })).toBeTruthy();
+ });
+
+ it('passes the manuscript, scene map, plotline coverage, and authored setups to the model and forces the plot category', async () => {
+ let seenVars = null;
+ const ctx = wholeCtx({
+ series: { arc: { readerMap: { hooks: [{ label: 'Where is the brother?', note: 'planted Issue 1' }], payoffs: [] } } },
+ planManuscriptChunks: async (_stage, opts) => {
+ // Scene map + plotline coverage + authored setups all ride as fixed overhead.
+ expect(opts.overheadTokens).toBeGreaterThan(0);
+ return ['# Issue 1\n\nThe brother thread is never mentioned again.'];
+ },
+ callStagedLLM: async (_stage, vars) => {
+ seenVars = vars;
+ return { content: { findings: [{ severity: 'high', issueNumber: 1, location: 'Dropped subplot — the missing brother', problem: 'The thread fizzles' }] } };
+ },
+ });
+ const findings = await getCheck(PLOT_STRUCTURE).run(ctx);
+ expect(seenVars.manuscript).toBe('# Issue 1\n\nThe brother thread is never mentioned again.');
+ expect(seenVars.sceneMap).toContain('Issue 1: Opening');
+ expect(seenVars.plotlineMap).toContain('The missing brother');
+ expect(seenVars.authoredSetups).toContain('Where is the brother?');
+ expect(findings).toHaveLength(1);
+ expect(findings[0].category).toBe('plot');
+ expect(findings[0].location).toBe('Dropped subplot — the missing brother');
+ });
+
+ it('passes empty context vars when the series has no outline or reader-map', async () => {
+ let seenVars = null;
+ const ctx = wholeCtx({
+ reverseOutline: undefined,
+ reverseOutlinePlotlines: undefined,
+ callStagedLLM: async (_stage, vars) => { seenVars = vars; return { content: { findings: [] } }; },
+ });
+ await getCheck(PLOT_STRUCTURE).run(ctx);
+ expect(seenVars.sceneMap).toBe('');
+ expect(seenVars.plotlineMap).toBe('');
+ expect(seenVars.authoredSetups).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(PLOT_STRUCTURE).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(PLOT_STRUCTURE).run(ctx);
+ expect(finals).toEqual(['', '', 'true']);
+ });
+});
+
+describe('plotlineCoverageSummary (#1310)', () => {
+ it('returns an empty string when there are no plotlines', () => {
+ expect(plotlineCoverageSummary(null, [])).toBe('');
+ expect(plotlineCoverageSummary([], [])).toBe('');
+ expect(plotlineCoverageSummary(undefined, undefined)).toBe('');
+ });
+
+ it('renders per-plotline scene counts and the issue span the scenes touch', () => {
+ const plotlines = [
+ { id: 'a', label: 'A-plot', kind: 'main' },
+ { id: 'b', label: 'The missing brother', kind: 'subplot' },
+ ];
+ const scenes = [
+ { issueNumber: 1, plotlineId: 'a' },
+ { issueNumber: 2, plotlineId: 'a', secondaryPlotlineId: 'b' },
+ { issueNumber: 5, plotlineId: 'a' },
+ ];
+ const out = plotlineCoverageSummary(plotlines, scenes);
+ expect(out).toContain('Plotlines (from the reverse outline');
+ expect(out).toContain('- A-plot (main): 3 scenes, issues 1–5');
+ // The subplot is carried only as a secondary tag on the Issue 2 scene.
+ expect(out).toContain('- The missing brother (subplot): 1 scene, issue 2');
+ });
+
+ it('reports a plotline with no tagged scenes (a candidate dropped subplot)', () => {
+ const out = plotlineCoverageSummary([{ id: 'c', label: 'Orphan thread', kind: 'subplot' }], []);
+ expect(out).toContain('- Orphan thread (subplot): 0 scenes, no tagged scenes');
+ });
+
+ it('is type-guarded against hand-edited / older-peer plotline rows', () => {
+ const out = plotlineCoverageSummary(
+ [null, { id: '' }, { id: 'x', label: 42, kind: null }],
+ [{ issueNumber: 3, plotlineId: 'x' }],
+ );
+ // Falls back to the id for a non-string label and 'other' for a missing kind.
+ expect(out).toContain('- x (other): 1 scene, issue 3');
+ // The null and id-less rows are dropped.
+ expect(out.split('\n').filter((l) => l.startsWith('- '))).toHaveLength(1);
+ });
+});
+
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.js
index 73fd4fd0b4..731c15feb1 100644
--- a/server/services/pipeline/editorial/checkRunner.js
+++ b/server/services/pipeline/editorial/checkRunner.js
@@ -61,6 +61,12 @@ const SOURCE_RESOLVERS = {
// 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.
reverseOutline: ({ reverseOutline }) => canonicalStringify(reverseOutline ?? null),
+ // The reverse-outline PLOTLINES the plot-structure check reconciles dropped
+ // subplots against (#1310). Separate token from `reverseOutline` so a scene
+ // edit that doesn't touch the plotline list doesn't needlessly stale a
+ // plotline-only finding (and vice-versa) — same over-eager-but-safe policy.
+ 'reverseOutline.plotlines': ({ reverseOutlinePlotlines }) =>
+ canonicalStringify(reverseOutlinePlotlines ?? null),
// The detected per-character arc directions a POV check reads (#1295). The
// injected `editorialArcs` is the stable projection (name/arcDirection/issueCount/
// isProtagonist) — NOT the raw getSeriesEditorial output, which carries a
@@ -182,7 +188,12 @@ export async function runEditorialChecks(seriesId, options = {}) {
const needsManuscript = enabled.some(({ check }) => check.needsManuscript);
// Reverse-outline fetch is gated on the declared source (#1296) so a run with no
// scene-segmentation check pays no extra I/O — mirrors the needsManuscript gate.
- const needsReverseOutline = enabled.some(({ check }) => checkSources(check).includes('reverseOutline'));
+ // Either the scenes (`reverseOutline`) OR the plotline list (`reverseOutline.plotlines`,
+ // #1310) is served by the same single outline fetch.
+ const needsReverseOutline = enabled.some(({ check }) => {
+ const sources = checkSources(check);
+ return sources.includes('reverseOutline') || sources.includes('reverseOutline.plotlines');
+ });
// Editorial-arc fetch is gated on the declared source (#1295) so a run with no
// POV/arc check pays no extra snapshot I/O — mirrors the needsReverseOutline gate.
const needsEditorialArcs = enabled.some(({ check }) => checkSources(check).includes('editorialArcs'));
@@ -198,6 +209,10 @@ export async function runEditorialChecks(seriesId, options = {}) {
]);
const manuscript = sectionsCorpus(sections);
const reverseOutline = Array.isArray(outline?.scenes) ? outline.scenes : [];
+ // The outline's plotline list (#1310) — injected separately from the scenes so a
+ // plotline-reading check (plot.structure-momentum) can reconcile dropped subplots
+ // against the author's tagged threads.
+ const reverseOutlinePlotlines = Array.isArray(outline?.plotlines) ? outline.plotlines : [];
const editorialArcs = projectEditorialArcs(editorial);
// Whether every analyzable issue has been analyzed and is fresh — gates the
// pov.justified "absent from detected arcs" finding so a partially-analyzed
@@ -207,7 +222,7 @@ export async function runEditorialChecks(seriesId, options = {}) {
// Resolve every source token once — each finding's fingerprint reads from this
// so the editor flags it `stale` when the content that check actually read (its
// declared `sources`) drifts (#1345, #1387).
- const resolvedSources = resolveSources({ manuscript, canon, series, reverseOutline, editorialArcs, editorialArcsComplete });
+ const resolvedSources = resolveSources({ manuscript, canon, series, reverseOutline, reverseOutlinePlotlines, editorialArcs, editorialArcsComplete });
const baseCtx = {
seriesId,
series,
@@ -215,6 +230,7 @@ export async function runEditorialChecks(seriesId, options = {}) {
sections,
manuscript,
reverseOutline,
+ reverseOutlinePlotlines,
editorialArcs,
editorialArcsComplete,
canon,
@@ -359,7 +375,10 @@ export async function getReviewWithStaleness(seriesId) {
// a source (mirrors the run path's gate, now source-derived rather than the bare
// needsManuscript flag so it stays correct as the source vocabulary grows).
const needsManuscript = evaluable.some((c) => checkSources(checkFor(c.checkId)).includes('manuscript'));
- const needsReverseOutline = evaluable.some((c) => checkSources(checkFor(c.checkId)).includes('reverseOutline'));
+ const needsReverseOutline = evaluable.some((c) => {
+ const sources = checkSources(checkFor(c.checkId));
+ return sources.includes('reverseOutline') || sources.includes('reverseOutline.plotlines');
+ });
const needsEditorialArcs = evaluable.some((c) => checkSources(checkFor(c.checkId)).includes('editorialArcs'));
const series = await getSeries(seriesId);
const [sections, canon, outline, editorial] = await Promise.all([
@@ -370,9 +389,10 @@ export async function getReviewWithStaleness(seriesId) {
needsEditorialArcs ? getSeriesEditorial(seriesId, { series }).catch(() => null) : Promise.resolve(null),
]);
const reverseOutline = Array.isArray(outline?.scenes) ? outline.scenes : [];
+ const reverseOutlinePlotlines = Array.isArray(outline?.plotlines) ? outline.plotlines : [];
const editorialArcs = projectEditorialArcs(editorial);
const editorialArcsComplete = editorialCoverageComplete(editorial);
- const resolvedSources = resolveSources({ manuscript: sectionsCorpus(sections), canon, series, reverseOutline, editorialArcs, editorialArcsComplete });
+ const resolvedSources = resolveSources({ manuscript: sectionsCorpus(sections), canon, series, reverseOutline, reverseOutlinePlotlines, editorialArcs, editorialArcsComplete });
return {
...review,
comments: review.comments.map((c) => {