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 checks for chapter-ending cliffhangers + POV switch (#1298)
Adam Eivy9ac1f81aced6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 2962a2fd96..ae63a0d6b0 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **[issue-1298] Editorial checks flag soft chapter endings and missed POV cut-aways.** Two new pacing checks (Create → Editorial Checks) enforce the serial-fiction rule that *every chapter is an episode*. **Chapter-ending cliffhangers** (LLM) reads your drafted manuscript and flags chapter/issue endings that resolve and settle — "soft landings" that tie everything off mid-story instead of ending on an unresolved beat that pulls the reader forward — escalating severity when a mid-story chapter fully closes the very question that should carry the reader on, while leaving a clearly terminal final chapter alone. It reconciles detected endings against the **authored reader-map cliffhangers** you've logged on the series arc. **Cliffhanger POV switch** (deterministic) reads your reverse-outline POV map: in a multi-POV story, when a chapter ends on an authored cliffhanger the next chapter should cut to a *different* POV character to sustain the tension — so it flags each authored cliffhanger whose following chapter keeps the same viewpoint. It no-ops for single-POV series and when no cliffhangers are authored. One new stage prompt (`pipeline-editorial-endings-cliffhanger`) ships + migrates for existing installs. (#1298)+- **[issue-1295] Editorial check flags point-of-view characters who don't earn their viewpoint.** A new **POV justification** editorial check (Create → Editorial Checks) reads your reverse-outline scene segmentation — which already tags who holds POV in each scene — and surfaces two viewpoint problems. First, a **POV without an arc**: a character we spend scenes inside who has no detected character arc (their arc reads flat, or they don't show up in the story's detected arcs at all) — a viewpoint that exists only to deliver information, with no arc and no stakes, should be cut or folded into another POV. Second, the inverse — a **drive-by POV**: a character who holds the viewpoint in only a single scene, a one-off head-hop that reads as a structural seam. Each finding names the character and anchors to the scene where their viewpoint begins. The drive-by threshold and whether to run the no-arc check are configurable, and the no-arc check **degrades gracefully** — when there's no arc information yet (no analysis has run, or the series is only partially analyzed), it stays silent rather than guessing, while the structural drive-by check keeps working. Requires a generated reverse outline. (#1295)- **[issue-1299] Editorial check flags broken setups and payoffs (Chekhov's guns).** A new **Chekhov's guns (setups & payoffs)** editorial check (Create → Editorial Checks) reads your drafted manuscript across the whole series and enforces the craft rule *things planted must go off; things that go off should have been planted.* It tracks concrete planted elements — weapons/objects/clues, secrets, stated fears, promises/vows, threats, and notable skills — and flags the two failure modes: **planted, never fired** ("the locked drawer in Issue 2 is never opened," "Mara's fear of water is set up but never confronted") and **fired, never planted** ("the antidote appears in Issue 7 with no prior setup"). Because a setup and its payoff can sit chapters apart, the check carries a rolling cross-chunk digest of what's been planted-but-not-yet-paid so a late payoff isn't mis-flagged "no setup" and a never-fired plant is still caught at the end. It also reconciles its detected setups/payoffs against the **authored reader-map hooks/payoffs** you've logged on the series arc, so an authored hook with no payoff in the prose surfaces as a strong finding. Each finding classifies the problem in its location, anchors a verbatim quote + issue number, and suggests the fix (plant earlier, pay off later, or cut). Runs on demand or as part of Series Autopilot's editorial pass; one new stage prompt (`pipeline-editorial-chekhov`) ships + migrates for existing installs. (#1299)diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex 160a21a05d..4b850b16f6 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -506,6 +506,13 @@"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.",+ "model": "default",+ "returnsJson": true,+ "variables": []+ },"pipeline-editorial-object-motivation": {"name": "Pipeline — Editorial Check: Unmotivated object interaction","description": "Editorial check (#1288): flags moments where a character treats an object as significant without earned motivation — no recorded attachment and no on-page setup. Reads the stitched manuscript plus the canon object↔character attachments. Returns issue-anchored findings.",diff --git a/data.reference/prompts/stages/pipeline-editorial-endings-cliffhanger.md b/data.reference/prompts/stages/pipeline-editorial-endings-cliffhanger.mdnew file mode 100644index 0000000000..a3547949d1--- /dev/null+++ b/data.reference/prompts/stages/pipeline-editorial-endings-cliffhanger.md@@ -0,0 +1,87 @@+# Pipeline — Editorial Check: Chapter-ending cliffhangers++You are a developmental editor doing a single focused pass for ONE problem:+**soft chapter endings**. The rule: *every chapter is an episode* — it should end+on a mini-cliffhanger that leaves something unresolved and pulls the reader into+the next chapter. A chapter that resolves and settles ("soft landing") bleeds the+momentum the serial form depends on.++## What to flag++For each chapter / issue ending, judge whether it leaves a question open or ties+things off and settles:++- **Soft landing** — the chapter wraps its tension, answers its open question, and+ ends on a calm or conclusive beat with nothing pulling the reader forward.+- **Premature resolution** — a mid-story chapter fully resolves a thread that the+ arc still needs open, so the cut has no tension to carry.++Flag these endings and suggest an unresolved beat to end on instead (a question+raised, a threat introduced, a reversal, a decision left hanging).++Severity: a chapter that simply winds down quietly is a **low** note; a mid-story+chapter that fully resolves and settles — closing the very question that should+carry the reader on — is **medium**.++Do NOT flag:++- The **final** chapter / issue of the whole story — a terminal ending is allowed+ (and expected) to resolve. If the manuscript below clearly ends the series, leave+ its last chapter alone.+- A chapter that already ends on an open beat, a turn, or an unanswered question —+ that is exactly what the rule wants.+- A deliberate quiet "breather" beat that still leaves a larger thread open.++{{#authoredCliffhangers}}+## Cliffhangers the writer has already planned++The writer logged these issue-boundary cliffhangers in the series reader-map.+Reconcile your findings against them: an authored cliffhanger whose chapter ending+you find actually settles (the prose doesn't deliver the planned tug) is a strong+soft-landing finding; a chapter that already ends on tension you find is fine even+if it isn't in this list. Judge from the prose, not the list alone — do not invent+findings just to match it.++```+{{authoredCliffhangers}}+```+{{/authoredCliffhangers}}++## 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`, and to find each chapter's+ending (the prose just before the next issue header, or the end of the text).++```+{{manuscript}}+```++## Task++For each chapter ending that lands soft, quote a short verbatim anchor from the+closing lines (≤ 200 characters) so the editor can jump to it, name the issue+number, explain how the ending settles instead of pulling forward, and suggest the+unresolved beat to end on. If every chapter ends on an open beat (and only the+terminal chapter resolves), return an empty `findings` array — do not invent issues.++## 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 (e.g. 'Issue 3 — ending')",+ "problem": "1–3 sentences naming how the chapter ending settles instead of leaving something open",+ "suggestion": "1–3 sentences on the unresolved beat to end on instead",+ "anchorQuote": "short verbatim quote from the chapter's closing lines (≤ 200 chars)"+ }+ ]+}+```diff --git a/scripts/migrations/102-editorial-endings-cliffhanger-stage.js b/scripts/migrations/102-editorial-endings-cliffhanger-stage.jsnew file mode 100644index 0000000000..0db6b926fa--- /dev/null+++ b/scripts/migrations/102-editorial-endings-cliffhanger-stage.js@@ -0,0 +1,79 @@+/**+ * Seed the `pipeline-editorial-endings-cliffhanger` stage into existing installs (#1298).+ *+ * Mirrors `100-editorial-chekhov-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 chapter-ending cliffhanger+ * stage unseeded and the `endings.cliffhanger` editorial check would throw+ * "Stage not found" the first time it runs.+ *+ * First-shipment seed (no MD5 bookkeeping). Any FUTURE edit to this `.md` MUST add+ * an `ACCEPTED_OLD_MD5`/`NEW_SHIPPED_MD5` pair (migration 003 pattern) so+ * `setup-data.js#buildPromptDriftTables` can auto-upgrade other installs.+ */++import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';+import { dirname, join } from 'path';++const FILENAME = 'pipeline-editorial-endings-cliffhanger.md';+const STAGE_KEY = 'pipeline-editorial-endings-cliffhanger';++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-endings-cliffhanger prompt: already present`);+ } else {+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);+ if (!sampleExists) {+ console.warn(`⚠️ pipeline-editorial-endings-cliffhanger: sample missing for ${FILENAME} — skipping copy`);+ } else {+ try {+ await copyFile(samplePath, dataPath);+ console.log(`✅ seeded ${FILENAME}`);+ } catch (err) {+ console.warn(`⚠️ pipeline-editorial-endings-cliffhanger: 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-endings-cliffhanger: 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-endings-cliffhanger stage-config: already present`);+ return;+ }+ if (!sample?.stages?.[STAGE_KEY]) {+ console.warn(`⚠️ pipeline-editorial-endings-cliffhanger: 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-endings-cliffhanger stage-config (${action}): 1 added`);+ } catch (err) {+ console.warn(`⚠️ pipeline-editorial-endings-cliffhanger: stage-config merge failed: ${err.message}`);+ }+ },+};diff --git a/scripts/migrations/102-editorial-endings-cliffhanger-stage.test.js b/scripts/migrations/102-editorial-endings-cliffhanger-stage.test.jsnew file mode 100644index 0000000000..ede9b3341f--- /dev/null+++ b/scripts/migrations/102-editorial-endings-cliffhanger-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 './102-editorial-endings-cliffhanger-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 100) — no MD5 bookkeeping, so the+// seed / no-clobber behavior is asserted directly.++const FILENAME = 'pipeline-editorial-endings-cliffhanger.md';+const STAGE_KEY = 'pipeline-editorial-endings-cliffhanger';+const BODY = '# Chapter-ending cliffhangers\n\nshipped body\n';++describe('migration 102 — seed editorial-endings-cliffhanger 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-102-'));+ 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/checkRegistry.js b/server/lib/editorial/checkRegistry.jsindex 53ebc10c4c..c97469e80d 100644--- a/server/lib/editorial/checkRegistry.js+++ b/server/lib/editorial/checkRegistry.js@@ -117,6 +117,12 @@ export const INTERIORITY_STAGE = 'pipeline-editorial-interiority';// migrations but NOT setup-data, so the migration is required).export const CHEKHOV_STAGE = 'pipeline-editorial-chekhov';+// Stage name for the chapter-ending cliffhanger LLM check (#1298). Ships in+// data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 102 (boot runs+// migrations but NOT setup-data, so the migration is required).+export const ENDINGS_CLIFFHANGER_STAGE = 'pipeline-editorial-endings-cliffhanger';+// Render the authored reader-map hooks/payoffs (#1299) into a compact text block// the Chekhov check passes alongside the manuscript so the model reconciles its// DETECTED setups/payoffs against what the writer has already LOGGED — e.g. an@@ -153,6 +159,73 @@ export function authoredSetupPayoffSummary(readerMap) {// deterministic siblings (prose.cliches, prose.modifier-stacking) need no stage.export const DEAD_METAPHOR_STAGE = 'pipeline-editorial-dead-metaphor';+// 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+// already LOGGED — an authored cliffhanger the prose doesn't deliver, or a+// settled ending where the writer planned one. Pure + deterministic so it's+// unit-testable and its token cost can be counted into the per-chunk overhead.+// Returns '' when nothing is authored (the prompt's `{{#authoredCliffhangers}}`+// section then renders nothing). `atIssueBoundary` is the issue the cliffhanger+// caps (the cut falls between it and the next), so it's surfaced as a location hint.+export function authoredCliffhangerSummary(readerMap) {+ const cliffs = Array.isArray(readerMap?.cliffhangers) ? readerMap.cliffhangers : [];+ const lines = cliffs.map((c) => {+ const note = typeof c?.note === 'string' ? c.note.trim() : '';+ if (!note) return '';+ const at = Number.isFinite(c?.atIssueBoundary) ? ` (ending issue ${c.atIssueBoundary})` : '';+ return `- ${note}${at}`;+ }).filter(Boolean);+ if (!lines.length) return '';+ return `Authored cliffhangers (issue-boundary tugs the writer planned):\n${lines.join('\n')}`;+}++// ---------------------------------------------------------------------------+// Chapter-ending POV switch (#1298) — deterministic over the reverse-outline POV+// map + the authored reader-map cliffhangers. The editorial rule: in a multi-POV+// story, after a chapter ends on a cliffhanger, the NEXT chapter should cut to a+// DIFFERENT POV character (the cut sustains tension across the break). The LLM+// cliffhanger check above judges WHICH endings are cliffhangers; this check uses+// the writer's AUTHORED cliffhangers as the deterministic trigger so it never+// needs the model. No authored cliffhangers ⇒ nothing to reconcile (no-op);+// single-POV series ⇒ no-op (there's no other POV to cut to).+// ---------------------------------------------------------------------------++// Group POV-tagged scenes by issue number, preserving outline (sequence) order+// within each issue and first-seen story order across issues. Scenes without an+// integer issueNumber can't be mapped to a chapter boundary and are dropped.+function scenesByIssue(scenes) {+ const byIssue = new Map();+ for (const s of scenes) {+ if (!s || typeof s !== 'object') continue;+ const n = Number.isInteger(s.issueNumber) ? s.issueNumber : null;+ if (n == null) continue;+ if (!byIssue.has(n)) byIssue.set(n, []);+ byIssue.get(n).push(s);+ }+ return byIssue;+}++// The POV holder of a scene, trimmed, or '' when untagged.+const scenePov = (s) => (typeof s?.povCharacter === 'string' ? s.povCharacter.trim() : '');++// The last / first POV-tagged scene of an issue's scene list (sequence-ordered),+// as { name, scene }, or null when no scene in the issue carries a POV.+function lastPovScene(list) {+ for (let i = list.length - 1; i >= 0; i -= 1) {+ const name = scenePov(list[i]);+ if (name) return { name, scene: list[i] };+ }+ return null;+}+function firstPovScene(list) {+ for (const s of list) {+ const name = scenePov(s);+ if (name) return { name, scene: s };+ }+ return null;+}+// ---------------------------------------------------------------------------// Character-name dissimilarity (#1291) reads cast names + aliases and respects// locked entries. The pure similarity primitives live in ./nameSimilarity.js;@@ -2107,6 +2180,119 @@ export const EDITORIAL_CHECKS = [buildVars: (manuscript) => ({ manuscript }),}),},+ {+ id: 'endings.cliffhanger',+ sources: ['manuscript', 'series.arc.readerMap'],+ label: 'Chapter-ending cliffhangers (soft landings)',+ description:+ 'LLM scan — flags chapter/issue endings that resolve and settle instead of leaving a question open. Every chapter is an episode and should end on an unresolved beat that pulls the reader forward; a "soft landing" that ties everything off mid-story bleeds momentum. Reconciles detected endings against the authored reader-map cliffhangers, and leaves a clearly terminal final-chapter ending alone.',+ scope: 'series',+ kind: 'llm',+ category: 'pacing',+ // A soft landing is advisory by default; the prompt tells the model to return+ // medium when a mid-story chapter fully resolves and settles (mapLlmFindings+ // keeps a valid model severity and only falls back to this default for an+ // invalid/absent one).+ 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,+ run: (ctx) => {+ // Authored cliffhangers are fixed per-call overhead (re-sent on each chunk).+ const authoredCliffhangers = authoredCliffhangerSummary(ctx.series?.arc?.readerMap);+ return runManuscriptLlmCheck(ctx, {+ stage: ENDINGS_CLIFFHANGER_STAGE,+ category: 'pacing',+ overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS + estimateTokens(authoredCliffhangers),+ buildVars: (manuscript) => ({ manuscript, authoredCliffhangers }),+ });+ },+ },+ {+ id: 'endings.pov-switch',+ sources: ['reverseOutline', 'series.arc.readerMap'],+ label: 'Cliffhanger POV switch (multi-POV)',+ description:+ 'Deterministic check over the reverse-outline POV map. In a multi-POV story, when a chapter ends on an authored cliffhanger the next chapter should cut to a DIFFERENT POV character — staying with the same viewpoint releases the tension just built. Flags each authored cliffhanger whose following chapter keeps the same POV. No-op for single-POV series and when no cliffhangers are authored.',+ scope: 'series',+ kind: 'deterministic',+ category: 'pacing',+ severityDefault: 'low',+ defaultEnabled: true,+ configSchema: z.object({}),+ // Needs a reverse outline with POV-tagged scenes AND at least one authored+ // cliffhanger to reconcile against — the multi-POV no-op is decided in run().+ gate: (ctx) => Array.isArray(ctx.reverseOutline)+ && ctx.reverseOutline.some((s) => s && typeof s.povCharacter === 'string' && s.povCharacter.trim())+ && Array.isArray(ctx.series?.arc?.readerMap?.cliffhangers)+ && ctx.series.arc.readerMap.cliffhangers.length > 0,+ run: (ctx) => {+ const scenes = Array.isArray(ctx.reverseOutline) ? ctx.reverseOutline : [];+ const cliffs = Array.isArray(ctx.series?.arc?.readerMap?.cliffhangers)+ ? ctx.series.arc.readerMap.cliffhangers : [];+ if (!scenes.length || !cliffs.length) return [];++ // Multi-POV gate: a single-POV story has no other viewpoint to cut to, so+ // the "switch after a cliffhanger" rule doesn't apply — no-op (per spec).+ const povKeys = new Set();+ for (const s of scenes) {+ const key = normalizeName(scenePov(s));+ if (key) povKeys.add(key);+ }+ if (povKeys.size <= 1) return [];++ const byIssue = scenesByIssue(scenes);+ // Issue numbers in story order (Map preserves first-seen order; scenes arrive+ // sequence-ordered, so this is the chapter sequence).+ const orderedIssues = [...byIssue.keys()];+ const findings = [];+ // One finding per ending issue even if the writer logged several cliffhangers+ // at the same boundary.+ const flagged = new Set();+ for (const c of cliffs) {+ const endIssue = Number.isInteger(c?.atIssueBoundary) ? c.atIssueBoundary : null;+ if (endIssue == null || flagged.has(endIssue)) continue;+ const idx = orderedIssues.indexOf(endIssue);+ // Skip a boundary we can't resolve to an outlined issue, or one with no+ // following chapter (a cliffhanger on the last drafted chapter has nowhere+ // to cut to — and the final chapter is allowed to resolve).+ if (idx === -1 || idx === orderedIssues.length - 1) continue;+ const nextIssue = orderedIssues[idx + 1];+ const ending = lastPovScene(byIssue.get(endIssue));+ const opening = firstPovScene(byIssue.get(nextIssue));+ if (!ending || !opening) continue;+ // POV switched across the cut — exactly what the rule wants. Nothing to flag.+ if (normalizeName(ending.name) !== normalizeName(opening.name)) continue;+ flagged.add(endIssue);+ const note = typeof c?.note === 'string' && c.note.trim() ? ` ("${c.note.trim()}")` : '';+ findings.push({+ severity: ctx.severityDefault,+ category: 'pacing',+ location: `Issue ${endIssue} → Issue ${nextIssue}`,+ problem: `Issue ${endIssue} ends on a cliffhanger${note} but Issue ${nextIssue} stays with the same POV character (${opening.name}). In a multi-POV story, holding the viewpoint straight through a cliffhanger releases the tension the cut is meant to sustain.`,+ suggestion: `Open Issue ${nextIssue} from a different POV character and return to ${opening.name}'s thread a chapter later — cutting away holds the reader on the unresolved beat.`,+ anchorQuote: typeof opening.scene?.anchorQuote === 'string' ? opening.scene.anchorQuote : '',+ issueNumber: nextIssue,+ });+ }+ return findings;+ },+ },];// ---------------------------------------------------------------------------diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.jsindex d272753fcd..bff2f663c9 100644--- a/server/lib/editorial/checkRegistry.test.js+++ b/server/lib/editorial/checkRegistry.test.js@@ -28,12 +28,15 @@ import {EDITORIAL_SETUP_DIGEST_CHARS,EDITORIAL_SETUP_DIGEST_SOURCE,authoredSetupPayoffSummary,+ authoredCliffhangerSummary,} from './checkRegistry.js';const NAMING = 'naming.dissimilar-names';const INFODUMP = 'prose.info-dumping';const INTERIORITY = 'interiority.protagonist';const CHEKHOV = 'chekhov.setups-payoffs';+const ENDINGS_CLIFF = 'endings.cliffhanger';+const POV_SWITCH = 'endings.pov-switch';// A minimal valid stored custom-check definition.const customDef = (over = {}) => ({@@ -443,6 +446,175 @@ describe('authoredSetupPayoffSummary (#1299)', () => {});});+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.',+ config: { maxFindings: 12 },+ severityDefault: 'low',+ series: {},+ planManuscriptChunks: async () => [overrides.manuscript ?? '# Issue 1\n\nThey all went home and rested.'],+ callStagedLLM: async () => ({ content: { findings: [] } }),+ ...overrides,+ });++ it('is registered as a series-scoped LLM pacing check reading manuscript + reader-map', () => {+ const check = getCheck(ENDINGS_CLIFF);+ expect(check.kind).toBe('llm');+ expect(check.scope).toBe('series');+ expect(check.category).toBe('pacing');+ expect(check.sources).toEqual(['manuscript', 'series.arc.readerMap']);+ expect(check.needsManuscript).toBe(true);+ });++ it('only runs when there is drafted prose to scan', () => {+ const check = getCheck(ENDINGS_CLIFF);+ expect(check.gate({ manuscript: '' })).toBe(false);+ expect(check.gate({ manuscript: '# Issue 1\n\nprose' })).toBeTruthy();+ });++ it('passes the manuscript + authored cliffhangers and forces the pacing category', async () => {+ let seenVars = null;+ const ctx = wholeCtx({+ series: { arc: { readerMap: { cliffhangers: [{ note: 'the door opens', atIssueBoundary: 1 }] } } },+ planManuscriptChunks: async (_stage, opts) => {+ // Authored cliffhangers ride alongside the manuscript as fixed overhead.+ expect(opts.overheadTokens).toBeGreaterThan(0);+ return ['# Issue 1\n\nThe war ended and everyone went home.'];+ },+ callStagedLLM: async (_stage, vars) => {+ seenVars = vars;+ return { content: { findings: [{ severity: 'medium', issueNumber: 1, location: 'Issue 1 — ending', problem: 'The chapter fully resolves', anchorQuote: 'went home' }] } };+ },+ });+ const findings = await getCheck(ENDINGS_CLIFF).run(ctx);+ expect(seenVars.manuscript).toBe('# Issue 1\n\nThe war ended and everyone went home.');+ expect(seenVars.authoredCliffhangers).toContain('the door opens');+ expect(findings).toHaveLength(1);+ expect(findings[0].category).toBe('pacing');+ expect(findings[0].severity).toBe('medium');+ });++ it('passes an empty authoredCliffhangers var when the series has no reader-map', async () => {+ let seenVars = null;+ const ctx = wholeCtx({+ callStagedLLM: async (_stage, vars) => { seenVars = vars; return { content: { findings: [] } }; },+ });+ await getCheck(ENDINGS_CLIFF).run(ctx);+ expect(seenVars.authoredCliffhangers).toBe('');+ });+});++describe('authoredCliffhangerSummary (#1298)', () => {+ it('returns an empty string when there are no authored cliffhangers', () => {+ expect(authoredCliffhangerSummary(null)).toBe('');+ expect(authoredCliffhangerSummary({})).toBe('');+ expect(authoredCliffhangerSummary({ cliffhangers: [] })).toBe('');+ });++ it('renders cliffhangers as a bullet list with an ending-issue hint when present', () => {+ const out = authoredCliffhangerSummary({+ cliffhangers: [{ note: 'the door opens', atIssueBoundary: 2 }, { note: 'a scream cuts off' }],+ });+ expect(out).toContain('Authored cliffhangers');+ expect(out).toContain('- the door opens (ending issue 2)');+ // No boundary hint when atIssueBoundary is absent.+ expect(out).toContain('- a scream cuts off');+ expect(out).not.toContain('a scream cuts off (ending issue');+ });++ it('drops cliffhangers with no note', () => {+ expect(authoredCliffhangerSummary({ cliffhangers: [{ atIssueBoundary: 1 }, { note: '' }] })).toBe('');+ });+});++describe('endings.pov-switch — deterministic check (#1298)', () => {+ // scene helper: pov + the issue it belongs to (sequence-ordered by array order).+ const scene = (pov, issueNumber, over = {}) => ({+ heading: `${pov || 'no'}-pov scene`, issueNumber, anchorQuote: `q-${issueNumber}`, povCharacter: pov, ...over,+ });+ const runSwitch = (scenes, cliffhangers) =>+ getCheck(POV_SWITCH).run({+ reverseOutline: scenes,+ series: { arc: { readerMap: { cliffhangers } } },+ config: {},+ severityDefault: 'low',+ });++ it('declares reverseOutline + reader-map sources and is series-scoped deterministic', () => {+ const c = getCheck(POV_SWITCH);+ expect(c.scope).toBe('series');+ expect(c.kind).toBe('deterministic');+ expect(c.category).toBe('pacing');+ expect(c.sources).toEqual(['reverseOutline', 'series.arc.readerMap']);+ });++ it('gate requires a POV-tagged scene AND at least one authored cliffhanger', () => {+ const c = getCheck(POV_SWITCH);+ const scenes = [scene('Aria', 1), scene('Bram', 2)];+ expect(c.gate({ reverseOutline: scenes, series: { arc: { readerMap: { cliffhangers: [] } } } })).toBeFalsy();+ expect(c.gate({ reverseOutline: [scene('', 1)], series: { arc: { readerMap: { cliffhangers: [{ atIssueBoundary: 1 }] } } } })).toBe(false);+ expect(c.gate({ reverseOutline: scenes, series: { arc: { readerMap: { cliffhangers: [{ atIssueBoundary: 1 }] } } } })).toBeTruthy();+ });++ it('flags a cliffhanger whose next chapter keeps the same POV (multi-POV series)', () => {+ const scenes = [+ scene('Aria', 1), scene('Aria', 1), // issue 1 ends on Aria+ scene('Aria', 2), // issue 2 opens on Aria — no switch+ scene('Bram', 3), // a second POV makes the series multi-POV+ ];+ const findings = runSwitch(scenes, [{ note: 'the door opens', atIssueBoundary: 1 }]);+ expect(findings).toHaveLength(1);+ const f = findings[0];+ expect(f.category).toBe('pacing');+ expect(f.location).toBe('Issue 1 → Issue 2');+ expect(f.problem).toMatch(/same POV character \(Aria\)/);+ expect(f.problem).toMatch(/the door opens/);+ expect(f.issueNumber).toBe(2);+ expect(f.anchorQuote).toBe('q-2');+ });++ it('does not flag when the next chapter switches POV', () => {+ const scenes = [scene('Aria', 1), scene('Bram', 2)];+ expect(runSwitch(scenes, [{ atIssueBoundary: 1 }])).toEqual([]);+ });++ it('no-ops on a single-POV series even with an authored cliffhanger', () => {+ const scenes = [scene('Aria', 1), scene('Aria', 2)];+ expect(runSwitch(scenes, [{ atIssueBoundary: 1 }])).toEqual([]);+ });++ it('no-ops when no cliffhangers are authored', () => {+ const scenes = [scene('Aria', 1), scene('Aria', 2), scene('Bram', 3)];+ expect(runSwitch(scenes, [])).toEqual([]);+ });++ it('skips a cliffhanger on the last drafted chapter (nowhere to cut to)', () => {+ const scenes = [scene('Aria', 1), scene('Bram', 2)];+ // Boundary 2 is the final chapter — no next issue, so no finding.+ expect(runSwitch(scenes, [{ atIssueBoundary: 2 }])).toEqual([]);+ });++ it('emits one finding per ending issue even if multiple cliffhangers share the boundary', () => {+ const scenes = [scene('Aria', 1), scene('Aria', 2), scene('Bram', 3)];+ const findings = runSwitch(scenes, [+ { note: 'first', atIssueBoundary: 1 },+ { note: 'second', atIssueBoundary: 1 },+ ]);+ expect(findings).toHaveLength(1);+ });++ it('treats casing/spacing variants of the POV name as the same holder', () => {+ const scenes = [scene('Aria Vance', 1), scene('aria vance', 2), scene('Bram', 3)];+ const findings = runSwitch(scenes, [{ atIssueBoundary: 1 }]);+ expect(findings).toHaveLength(1);+ });++ it('tolerates an empty / malformed outline', () => {+ expect(runSwitch([], [{ atIssueBoundary: 1 }])).toEqual([]);+ expect(runSwitch([null, 'x', {}], [{ atIssueBoundary: 1 }])).toEqual([]);+ });+});+describe('naming.dissimilar-names — deterministic check', () => {const run = (characters, config = { minSharedSignals: 2 }) =>getCheck(NAMING).run({ canon: { characters }, config, severityDefault: 'low' });