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: add pacing.escalation-curve editorial check for series-wide intensity (#1618)
[._.]/ Adam Eivyd65b3ef8e589
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex f57753caa4..18fee3a6d4 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -23,6 +23,7 @@## Editorial checks+- **[issue-1618] A new editorial check scores the series-wide pacing / intensity escalation curve.** `plot.structure-momentum` flags flat stakes as one of many macro pathologies, but nothing measured the *shape* of intensity across the whole series. The new `pacing.escalation-curve` check (series-scope, default-on) scores each issue's dramatic intensity and flags a curve that fails to build — **flat intensity** (issue 1 reads as intensely as issue N), a **front-loaded climax** (the biggest beat lands early and the back half coasts), **plateaued stakes**, or a **de-escalating arc**. It reads the stitched manuscript plus the reverse-outline scene map and a new deterministic per-issue conflict-marker density tally (a mechanical intensity proxy the model treats as a hint and confirms against the prose), gates its whole-curve verdict to the final manuscript part, and degrades to a prose-only scan when no outline exists. Subsumes "conflict escalation" as one signal of the same curve. Ships the prompt + stage-config for fresh installs and a boot migration (140) so existing installs seed the stage. (`server/lib/editorial/checkRegistry.js`, `data.reference/prompts/stages/pipeline-editorial-pacing-escalation-curve.md`, `scripts/migrations/140-editorial-pacing-escalation-stage.js`)- **[issue-1697] Health-panel deep-links now honor the triage's session-local check mute.** Muting a check from the Editorial Findings triage (#1602) hid its findings group but the health panel kept advertising that check/category row as clickable — clicking it scrolled to an empty filtered view. The session mute state (`hiddenCheckIds`) was lifted from `EditorialFindingsTriage` up to `PipelineEditorialChecks`, which now subtracts muted checks from the filterable sets the health panel receives; a category stays clickable only while a non-muted check still contributes an open finding to it. (`client/src/pages/PipelineEditorialChecks.jsx`, `client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx`)- **[issue-1667] Final-part editorial verdicts no longer lose their carried setup context on a packed last chunk.** The cross-chunk "setup so far" digest normally yields to manuscript coverage — but two whole-story checks (`arc.climax-agency`, `emotion.reaction-proportionality`) gate their verdict to the final part and anchor it on a snippet carried in that digest (the climax candidate / the unprocessed event). When the final chunk packed to within a few hundred chars of the provider window, the digest was silently dropped and the final-only finding was missed. These checks now opt into a `reserveSetupDigest` guarantee that trims the final chunk's manuscript tail to make room for the digest (the inverse of the usual yield), scoped to the final chunk and opt-in checks only — every other chunk and every non-reserving check keeps full manuscript coverage. (`server/lib/editorial/checkRegistry.js`)- **[issue-1614] Series Autopilot no longer wastes an LLM call refreshing the reverse outline for a check that won't run, and never proceeds on a stale one.** The pre-checks reverse-outline refresh decided "does any enabled check consume the outline?" from declared sources alone — so a check that's enabled but whose runtime gate declines for this series (no POV-tagged scenes, a canon-less roster) could still trigger a billed regeneration nothing would read. The refresh now evaluates each consumer's gate against the current outline and skips the regen when nothing that would actually run consumes it; a never-generated outline still bootstraps unconditionally. Separately, when the regen no-ops as cached the run re-confirms staleness against the live manuscript and forces one regen if a concurrent edit moved it — so the editorial checks never read a stale outline mid-run. (`server/services/pipeline/seriesAutopilot.js`, `server/services/pipeline/editorial/checkRunner.js`)diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex 7a30429dd8..14d73d8ccb 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -743,6 +743,13 @@"model": "default","returnsJson": true,"variables": []+ },+ "pipeline-editorial-pacing-escalation-curve": {+ "name": "Pipeline — Editorial Check: Pacing / intensity escalation curve",+ "description": "Editorial check (#1618): scores each issue's dramatic intensity and flags a series-wide escalation curve that fails to build — flat intensity (issue 1 reads as intensely as issue N), a front-loaded climax (the biggest beat lands early), or stakes that plateau or de-escalate across the arc. Reads the stitched manuscript plus the reverse-outline scene map and a deterministic per-issue conflict-marker density tally (a grounding hint confirmed against the prose); 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-pacing-escalation-curve.md b/data.reference/prompts/stages/pipeline-editorial-pacing-escalation-curve.mdnew file mode 100644index 0000000000..ec6ec9ed31--- /dev/null+++ b/data.reference/prompts/stages/pipeline-editorial-pacing-escalation-curve.md@@ -0,0 +1,117 @@+# Pipeline — Editorial Check: Pacing / intensity escalation curve++You are a developmental editor doing a single focused pass for ONE concern:+**the series-wide escalation curve** — does dramatic intensity BUILD across the+issues, or does it stay flat, peak too early, or plateau and fall? This is a+whole-arc, macro problem, not a line-level one. Judge intensity as the reader+feels it: the weight of the stakes, the pressure of the conflict, and how close+the protagonist is to irreversible loss — issue by issue, in order.++Score each issue's intensity relative to the others (you do not need a numeric+scale — a clear sense of "lower / about the same / higher than the issue before"+is enough) and then judge the SHAPE of the curve across the whole series. Flag+only these pathologies (each is a distinct finding category):++- **Flat curve** — intensity barely changes from the first issue to the last;+ issue 1 reads about as tense as issue N. The reader never feels the stakes+ tightening, so the ending lands with no more weight than the opening.+- **Front-loaded climax** — the biggest reveal, set-piece, or emotional peak+ lands early (e.g. issue 2 of 6) and nothing later tops it; the back half coasts+ downhill from a peak the story already spent.+- **Plateaued stakes** — the curve rises early, then levels off: a long stretch+ of issues at the same pitch with no further escalation, so the middle-to-late+ arc marks time at one intensity.+- **De-escalating arc** — intensity actively falls across the back half (the+ stakes shrink, the conflict cools, the threat recedes) instead of converging on+ a peak — an anticlimax in slow motion.++Do NOT flag: a single quiet issue that is a deliberate breather between two+high-intensity issues (a valley inside a rising curve is healthy pacing); a+deliberately low-key / literary series where steady, low external intensity is+the point; or a mid-arc manuscript whose climax is clearly still ahead (judge+shape only once the whole series is in view — see the final-part note below).++{{#intensityTally}}+## Conflict-marker density (deterministic hint)++A mechanical per-issue tally of conflict / stakes / danger words, normalized per+1,000 words. It is a CRUDE proxy, not ground truth — a quiet-but-tense+interrogation can score low and a loud-but-inconsequential brawl can score high.+Use it as a starting hint for where intensity rises or falls, then confirm the+real curve against the prose.++```+{{intensityTally}}+```+{{/intensityTally}}++{{#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 an+escalation finding to a scene and its issue; judge the curve 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 judge the WHOLE+curve: a flat arc, a front-loaded climax, a plateau, or a de-escalation. The+"intensity so far" digest above tells you how each earlier issue scored, so you+can place the late issues on the same curve.+{{/finalPart}}+{{^finalPart}}+You are seeing an EARLIER part of a long manuscript reviewed in pieces. Do NOT+yet flag a flat curve, a front-loaded climax, a plateau, or a de-escalation — a+later part may still raise the stakes and resolve the shape. Note the intensity+of the issues in view (the "intensity so far" digest carries this forward) but+reserve every whole-curve verdict for the final part.+{{/finalPart}}++## Task++Identify the escalation-curve pathologies above. For each finding set `location`+to the pathology + a pointer, e.g. `Front-loaded climax — the reveal in Issue 2`,+`Flat curve — Issues 1–6`, `De-escalating arc — back half (Issues 4–6)`. Set+`issueNumber` to the issue the finding is anchored to (for a whole-arc verdict+like a flat curve, use the issue where the problem is clearest, or null). Quote a+short verbatim anchor (≤ 200 chars) at the relevant peak or slack moment where one+exists (omit `anchorQuote` for a whole-arc shape judgment). Severity: a flat or+de-escalating whole-series curve, or a climax that peaks in the first third, is+high; a single plateaued stretch in an otherwise rising arc is low. If the curve+builds well — intensity rising issue over issue toward a late peak, with healthy+breather valleys — return an empty `findings` array. Do not invent a pacing+problem where the escalation 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": 2,+ "location": "string — pathology + pointer (e.g. 'Front-loaded climax — the reveal in Issue 2' or 'Flat curve — Issues 1–6')",+ "problem": "1–3 sentences naming the escalation problem and why it weakens the series (where the curve flattens, peaks early, or falls)",+ "suggestion": "1–3 sentences proposing how to fix it (raise the stakes in the back half, hold the biggest reveal later, add a turn that escalates the plateaued stretch)",+ "anchorQuote": "short verbatim quote at the peak or slack moment (≤ 200 chars); omit for a whole-arc shape judgment"+ }+ ]+}+```diff --git a/scripts/migrations/140-editorial-pacing-escalation-stage.js b/scripts/migrations/140-editorial-pacing-escalation-stage.jsnew file mode 100644index 0000000000..897b86a266--- /dev/null+++ b/scripts/migrations/140-editorial-pacing-escalation-stage.js@@ -0,0 +1,76 @@+/**+ * Seed the `pipeline-editorial-pacing-escalation-curve` stage into existing+ * installs (#1618).+ *+ * 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 pacing-escalation stage+ * unseeded and the `pacing.escalation-curve` 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-pacing-escalation-curve.md';+const STAGE_KEY = 'pipeline-editorial-pacing-escalation-curve';++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-pacing-escalation-curve prompt: already present`);+ } else {+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);+ if (!sampleExists) {+ console.warn(`⚠️ pipeline-editorial-pacing-escalation-curve: sample missing for ${FILENAME} — skipping copy`);+ } else {+ try {+ await copyFile(samplePath, dataPath);+ console.log(`✅ seeded ${FILENAME}`);+ } catch (err) {+ console.warn(`⚠️ pipeline-editorial-pacing-escalation-curve: 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-pacing-escalation-curve: 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-pacing-escalation-curve stage-config: already present`);+ return;+ }+ if (!sample?.stages?.[STAGE_KEY]) {+ console.warn(`⚠️ pipeline-editorial-pacing-escalation-curve: 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-pacing-escalation-curve stage-config (${action}): 1 added`);+ } catch (err) {+ console.warn(`⚠️ pipeline-editorial-pacing-escalation-curve: stage-config merge failed: ${err.message}`);+ }+ },+};diff --git a/scripts/migrations/140-editorial-pacing-escalation-stage.test.js b/scripts/migrations/140-editorial-pacing-escalation-stage.test.jsnew file mode 100644index 0000000000..c28f2f8ca6--- /dev/null+++ b/scripts/migrations/140-editorial-pacing-escalation-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 './140-editorial-pacing-escalation-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-pacing-escalation-curve.md';+const STAGE_KEY = 'pipeline-editorial-pacing-escalation-curve';+const BODY = '# Pacing / intensity escalation curve\n\nshipped body\n';++describe('migration 140 — seed editorial-pacing-escalation-curve 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-140-'));+ 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 56118bc0ab..c0e7f87c25 100644--- a/server/lib/editorial/checkRegistry.js+++ b/server/lib/editorial/checkRegistry.js@@ -570,6 +570,18 @@ export function continuityLedgerSummary(facts) {// subplots reconciled against the tagged plotlines.export const PLOT_STRUCTURE_STAGE = 'pipeline-editorial-plot-structure';+// Stage name for the series-wide pacing / intensity escalation-curve LLM check+// (#1618). Ships in data.reference/prompts/stages/ + stage-config.json (fresh+// installs via setup-data.js) and migrates to existing installs via migration 140+// (boot runs migrations but NOT setup-data, so the migration is required). Reads+// the stitched manuscript plus the reverse-outline scene map and a deterministic+// per-issue conflict-marker density tally, and scores the per-issue dramatic+// intensity to flag a flat curve (issue 1 ≈ issue N), a front-loaded climax (the+// biggest beat lands early), or stakes that plateau / de-escalate across the arc.+// Complements plot.structure-momentum (flat stakes as one signal among many) by+// focusing the lens on the whole-series escalation shape.+export const PACING_ESCALATION_STAGE = 'pipeline-editorial-pacing-escalation-curve';+// Stage name for the timeline / canon-contradiction LLM check (#1581). Ships in// data.reference/prompts/stages/ + stage-config.json (fresh installs via// setup-data.js) and migrates to existing installs via migration 129 (boot runs@@ -1756,6 +1768,77 @@ export function plotlineCoverageSummary(plotlines, scenes) {return `Plotlines (from the reverse outline — reconcile dropped subplots against these):\n${rows.join('\n')}`;}+// Curated lexicon of conflict / stakes / high-intensity markers (#1618). A+// per-issue tally of these words is a crude-but-deterministic proxy for dramatic+// intensity: the escalation-curve check can't "feel" tension, but it CAN see+// whether the density of conflict language rises, plateaus, or falls across the+// issues. The model treats the tally as a hint (not ground truth) and confirms+// the curve against the prose — so a quiet-but-tense scene the lexicon misses is+// still caught. Word-boundary matched, case-insensitive; kept deliberately small+// and high-signal (physical conflict + danger/stakes) to limit false hits.+const CONFLICT_INTENSITY_MARKERS = Object.freeze([+ // physical conflict / violence+ 'attack', 'attacks', 'attacked', 'fight', 'fights', 'fought', 'fighting',+ 'strike', 'strikes', 'struck', 'punch', 'punched', 'stab', 'stabbed', 'shoot',+ 'shoots', 'shot', 'kill', 'kills', 'killed', 'die', 'dies', 'died', 'death',+ 'blood', 'bleeding', 'wound', 'wounded', 'scream', 'screams', 'screamed',+ 'shout', 'shouted', 'slam', 'slammed', 'crash', 'crashed',+ // danger / stakes / dread+ 'danger', 'dangerous', 'threat', 'threats', 'threaten', 'threatened', 'enemy',+ 'enemies', 'weapon', 'weapons', 'gun', 'guns', 'knife', 'fire', 'fired',+ 'fires', 'firing', 'explode', 'exploded', 'explosion', 'fear', 'terror',+ 'panic', 'desperate', 'betray',+ 'betrayed', 'betrayal', 'trap', 'trapped', 'flee', 'fled', 'chase', 'chased',+ 'escape', 'war', 'battle', 'dying', 'doom', 'doomed',+]);++// Tally the conflict-marker density per issue across the WHOLE stitched manuscript+// (#1618) so the escalation-curve check sees the complete intensity shape on every+// chunk. Splits on the `# Issue N` headers the manuscript stitcher emits, counts+// markers + words per issue, and reports markers-per-1k-words — normalizing out+// raw length so a long-but-quiet issue doesn't read as more intense than a short+// climactic one. Pure + deterministic so it's unit-testable and its token cost can+// be counted into the per-chunk overhead. Returns '' when there are no issue+// headers (the prompt's `{{#intensityTally}}` section then renders nothing and the+// check judges the curve from the prose + scene map alone). A header that repeats+// across the stitch (a chunk boundary mid-issue) sums into the same issue bucket.+export function conflictIntensityTally(manuscript) {+ const text = typeof manuscript === 'string' ? manuscript : '';+ if (!text.trim()) return '';+ const headerRe = /^#+\s*Issue\s+(\d+)\b[^\n]*$/gim;+ const sections = [];+ let match;+ let prev = null;+ while ((match = headerRe.exec(text)) !== null) {+ if (prev) prev.end = match.index;+ prev = { issue: Number(match[1]), start: headerRe.lastIndex, end: text.length };+ sections.push(prev);+ }+ if (!sections.length) return '';+ const markerRe = new RegExp(`\\b(?:${CONFLICT_INTENSITY_MARKERS.join('|')})\\b`, 'gi');+ // Sum duplicate issue numbers (a repeated header across a stitch) — keep numeric+ // order so the rendered curve reads issue 1 → N for the model.+ const byIssue = new Map();+ for (const sec of sections) {+ const body = text.slice(sec.start, sec.end);+ const words = (body.match(/\b[\w']+\b/g) || []).length;+ const markers = (body.match(markerRe) || []).length;+ const acc = byIssue.get(sec.issue) || { words: 0, markers: 0 };+ byIssue.set(sec.issue, { words: acc.words + words, markers: acc.markers + markers });+ }+ const rows = [...byIssue.entries()]+ .sort((a, b) => a[0] - b[0])+ .map(([issue, { words, markers }]) => {+ const density = words > 0 ? (markers / words) * 1000 : 0;+ return `- Issue ${issue}: ${markers} conflict marker${markers === 1 ? '' : 's'} across `+ + `${words} word${words === 1 ? '' : 's'} (${density.toFixed(1)} per 1k)`;+ });+ if (!rows.length) return '';+ return 'Conflict-marker density per issue (deterministic intensity proxy — a rising '+ + 'number suggests escalation, a flat or falling one a plateau / de-escalation; '+ + 'treat as a hint and confirm against the prose):\n' + rows.join('\n');+}+// Human-readable POV-person labels for the head-hopping check's prompt (#1311).// Inlined (not imported from styleGuide.js) to keep this registry pure — mirrors// the labels in server/lib/styleGuide.js so generation and the check describe a@@ -3988,6 +4071,76 @@ export const EDITORIAL_CHECKS = [});},},+ {+ id: 'pacing.escalation-curve',+ sources: ['manuscript', 'reverseOutline'],+ label: 'Pacing — escalation curve',+ description:+ 'LLM scan of the SERIES-WIDE escalation curve: it scores each issue\'s dramatic intensity (stakes, conflict, tension) and flags a curve that fails to build — flat intensity (issue 1 reads as intensely as issue N), a front-loaded climax (the biggest reveal / set-piece lands early and the rest coasts), or stakes that plateau or de-escalate across the arc. Reads the stitched manuscript plus the reverse-outline scene map and a deterministic per-issue conflict-marker density tally (a grounding hint the model confirms against the prose); degrades to a whole-manuscript scan when no outline exists. Subsumes "conflict escalation" as one signal of the same curve and complements plot.structure-momentum (which flags flat stakes as one of many macro pathologies) by focusing the lens on the whole-series intensity shape.',+ scope: 'series',+ kind: 'llm',+ category: 'pacing',+ 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 scene map lets the model attribute escalation findings to a+ // scene + issue, and the conflict-marker tally — computed once over the WHOLE+ // manuscript so the curve is complete on every chunk — grounds the per-issue+ // intensity scoring with a deterministic density signal. The check degrades+ // gracefully — no outline ⇒ {{#sceneMap}} renders nothing; no issue headers ⇒+ // {{#intensityTally}} renders nothing and the model scores intensity from the+ // prose alone.+ const sceneMap = sceneGroundingSummary(ctx.reverseOutline);+ const intensityTally = conflictIntensityTally(ctx.manuscript);+ return runManuscriptLlmCheck(ctx, {+ stage: PACING_ESCALATION_STAGE,+ category: 'pacing',+ // sceneMap grows unbounded with scene count; intensityTally is bounded by+ // issue count — so largest-first trimming absorbs the cut into sceneMap.+ context: { sceneMap, intensityTally },+ // `isFinal` gates the whole-curve judgments — a flat curve, a front-loaded+ // climax, and a plateaued/de-escalating arc can only be judged once the+ // whole manuscript is in view; an earlier chunk can't know intensity rises+ // later, so it would false-flag.+ buildVars: (manuscript, meta, c) => ({+ manuscript,+ sceneMap: c.sceneMap,+ intensityTally: c.intensityTally,+ finalPart: meta?.isFinal ? 'true' : '',+ }),+ // Intensity 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 the per-issue intensity seen so far so a later+ // climax isn't mis-read as a flat or front-loaded curve.+ crossChunkDigest: true,+ crossChunkSetup: true,+ setupFocus: 'For each issue/part seen so far, note the level of dramatic intensity '+ + '(stakes, conflict, tension) and whether it has been rising, holding flat, or '+ + 'falling, so a later chunk can judge the WHOLE escalation curve and tell a genuinely '+ + 'flat or front-loaded arc from one whose climax simply has not arrived yet.',+ });+ },+ },{id: 'theme.coherence',sources: ['manuscript', 'series.arc.themes', 'reverseOutline'],diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.jsindex 1bf3105c19..b56a2b3177 100644--- a/server/lib/editorial/checkRegistry.test.js+++ b/server/lib/editorial/checkRegistry.test.js@@ -39,6 +39,7 @@ import {characterVoiceProfiles,intendedVoiceSummary,plotlineCoverageSummary,+ conflictIntensityTally,scenePovSummary,secondaryCharacterPresenceSummary,declaredThemesSummary,@@ -61,6 +62,7 @@ const POV_SWITCH = 'endings.pov-switch';const SENSORY_BALANCE = 'sensory.balance';const WHITE_ROOM = 'scene.white-room';const PLOT_STRUCTURE = 'plot.structure-momentum';+const PACING_ESCALATION = 'pacing.escalation-curve';const HEAD_HOPPING = 'pov.head-hopping';const THEME_COHERENCE = 'theme.coherence';const UNMODELED_NAMES = 'roster.unmodeled-names';@@ -1045,6 +1047,133 @@ describe('plot.structure-momentum — LLM check (#1310)', () => {});});+describe('pacing.escalation-curve — LLM check (#1618)', () => {+ 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' }],+ 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', () => {+ const check = getCheck(PACING_ESCALATION);+ expect(check.kind).toBe('llm');+ expect(check.scope).toBe('series');+ expect(check.category).toBe('pacing');+ expect(check.sources).toEqual(['manuscript', 'reverseOutline']);+ expect(check.needsManuscript).toBe(true);+ });++ it('only runs when there is drafted prose to scan', () => {+ const check = getCheck(PACING_ESCALATION);+ expect(check.gate({ manuscript: '' })).toBe(false);+ expect(check.gate({ manuscript: '# Issue 1\n\nprose' })).toBeTruthy();+ });++ it('passes the manuscript, scene map, and conflict-marker tally to the model and forces the pacing category', async () => {+ let seenVars = null;+ const ctx = wholeCtx({+ manuscript: '# Issue 1\n\nThey shared tea and spoke softly.\n\n# Issue 2\n\nHe drew his knife and the gun fired; blood, screams, a desperate fight to the death.',+ planManuscriptChunks: async (_stage, opts) => {+ // Scene map + intensity tally both ride as trimmable context.+ expect(opts.context).toHaveProperty('sceneMap');+ expect(opts.context).toHaveProperty('intensityTally');+ expect(opts.fixedOverheadTokens).toBeGreaterThan(0);+ return ['# Issue 2\n\nHe drew his knife and the gun fired.'];+ },+ callStagedLLM: async (_stage, vars) => {+ seenVars = vars;+ return { content: { findings: [{ severity: 'high', issueNumber: 2, location: 'Front-loaded climax — Issue 2', problem: 'The peak lands early' }] } };+ },+ });+ const findings = await getCheck(PACING_ESCALATION).run(ctx);+ expect(seenVars.manuscript).toBe('# Issue 2\n\nHe drew his knife and the gun fired.');+ expect(seenVars.sceneMap).toContain('Issue 1: Opening');+ // Both issues land in the tally; issue 2's conflict words score higher.+ expect(seenVars.intensityTally).toContain('Issue 1');+ expect(seenVars.intensityTally).toContain('Issue 2');+ expect(findings).toHaveLength(1);+ expect(findings[0].category).toBe('pacing');+ expect(findings[0].location).toBe('Front-loaded climax — Issue 2');+ });++ it('passes empty context vars when the series has no outline and the manuscript has no issue headers', async () => {+ let seenVars = null;+ const ctx = wholeCtx({+ manuscript: 'Plain prose with no issue headers at all.',+ reverseOutline: undefined,+ callStagedLLM: async (_stage, vars) => { seenVars = vars; return { content: { findings: [] } }; },+ });+ await getCheck(PACING_ESCALATION).run(ctx);+ expect(seenVars.sceneMap).toBe('');+ expect(seenVars.intensityTally).toBe('');+ });++ it('marks a single-chunk run as the final part so whole-curve judgments are enabled', async () => {+ let seenVars = null;+ const ctx = wholeCtx({+ callStagedLLM: async (_stage, vars) => { seenVars = vars; return { content: { findings: [] } }; },+ });+ await getCheck(PACING_ESCALATION).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(PACING_ESCALATION).run(ctx);+ expect(finals).toEqual(['', '', 'true']);+ });+});++describe('conflictIntensityTally (#1618)', () => {+ it('returns an empty string for a missing, empty, or header-less manuscript', () => {+ expect(conflictIntensityTally(undefined)).toBe('');+ expect(conflictIntensityTally('')).toBe('');+ expect(conflictIntensityTally(' ')).toBe('');+ expect(conflictIntensityTally('Just prose, no issue headers anywhere.')).toBe('');+ });++ it('tallies conflict markers per issue, in numeric order, normalized per 1k words', () => {+ const manuscript = [+ '# Issue 1 — Quiet (prose)',+ 'They shared tea and spoke softly about the garden.',+ '# Issue 2 — Storm (prose)',+ 'He drew his knife and the gun fired; blood, screams, a desperate fight to the death.',+ ].join('\n\n');+ const out = conflictIntensityTally(manuscript);+ const lines = out.split('\n').filter((l) => l.startsWith('- Issue'));+ expect(lines).toHaveLength(2);+ expect(lines[0]).toContain('Issue 1');+ expect(lines[1]).toContain('Issue 2');+ // Issue 1 has no markers; Issue 2 has several (knife, gun, fired, blood, screams, desperate, fight, death).+ expect(lines[0]).toContain('0 conflict markers');+ expect(lines[1]).toMatch(/[1-9]\d* conflict markers/);+ });++ it('sums a repeated issue header (chunk boundary mid-issue) into one bucket', () => {+ const manuscript = [+ '# Issue 1',+ 'He drew his knife.',+ '# Issue 1',+ 'The gun fired and blood spilled.',+ ].join('\n\n');+ const out = conflictIntensityTally(manuscript);+ const lines = out.split('\n').filter((l) => l.startsWith('- Issue'));+ expect(lines).toHaveLength(1);+ expect(lines[0]).toContain('Issue 1');+ // knife + gun + fired + blood = 4 markers merged across the two header sections.+ expect(lines[0]).toContain('4 conflict markers');+ });+});+describe('plotlineCoverageSummary (#1310)', () => {it('returns an empty string when there are no plotlines', () => {expect(plotlineCoverageSummary(null, [])).toBe('');