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 climax / resolution-power editorial check (#1583)
[._.]/ Adam Eivy06f741df2935
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0ae577e64a..76f3917a8a 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -53,6 +53,8 @@- **[issue-1582] A new editorial check catches unearned personality shifts — a reserved character who suddenly cracks jokes, a stated fear silently ignored, knowledge that appears with no on-page learning.** PortOS's `arc.transitions` check finds *change moments* but nothing flagged a change the story never *earns*: a guarded character trading easy banter a chapter later with no beat to motivate it, an established trait (a fear, an allergy, a skill) quietly contradicted, or a POV character who acts on information they were never shown learning. These read as author slips rather than growth and are hard to catch by eye once an arc spans months of drafting. The new **Character consistency** check (`character.consistency`) reconciles the stitched manuscript against the established canon character *traits* (personality, fixed traits, mannerisms, likes/dislikes, speech), the reverse-outline scene ordering (to spot a knowledge jump within a scene), and — crucially — the **authored per-character arcs**, so an intentional, earned transition the author recorded is *not* flagged. It runs across the whole manuscript, carrying each character's established temperament forward between chunks so a baseline set in an early chapter and an unearned shift in a later one are visible together, and degrades to a prose-only scan when no canon or outline exists. It's a default-on series check that surfaces in the existing editorial-review UI and Series Autopilot like every other check, marking trait contradictions that break a plot beat high-severity per finding. (`server/lib/editorial/checkRegistry.js`, `data.reference/prompts/stages/pipeline-editorial-character-consistency.md`, `scripts/migrations/130-editorial-character-consistency-stage.js`)+- **[issue-1583] A new editorial check catches a weak climax — a protagonist who is rescued at the payoff scene, or a climax that wins the plot but never lands the story's emotional/thematic core.** Nothing checked that the climax is the protagonist's *hardest, most active* moment: a finale where an ally swoops in to resolve the conflict, the antagonist conveniently self-destructs, or a coincidence settles things — or a climax that lands the action but leaves the theme the story has been building unanswered — could ship unflagged, even though a passive climax is story-breaking for the reader who invested in the whole arc. The new **Climax / resolution power** check (`arc.climax-agency`) identifies the climax scene and judges two things: *agency* (does the protagonist drive the resolution through a hard, costly choice, vs. being a spectator at their own climax) and *resolution power* (does the climax resolve the core problem and land the emotional/thematic argument, not just the surface plot). It reconciles the prose against the authored reader-map payoffs (what the reader was promised) and the declared themes, using the reverse-outline scene map to locate the climax, and gates its verdict on the final manuscript part — the climax can only be judged once the whole story is in view — degrading to a whole-manuscript scan when no reader-map, themes, or outline exists. It's a default-on series check that surfaces in the existing editorial-review UI and Series Autopilot like every other check, marking a fully passive climax high-severity; it complements `plot.structure-momentum` (which flags a passive protagonist arc-wide) by focusing the lens on the single payoff scene. (`server/lib/editorial/checkRegistry.js`, `data.reference/prompts/stages/pipeline-editorial-climax-agency.md`, `scripts/migrations/131-editorial-climax-agency-stage.js`)+## Series Autopilot- **[issue-1510] Series Autopilot now catches whole-book continuity problems at the cheap beat stage, before it generates full scripts.** The autopilot reviewed continuity at two altitudes — the cross-volume synopsis pass (before beats exist) and the full-text editorial pass (after every issue's script is written, the most expensive stage) — leaving a gap in between. So structural defects spanning the whole book (a cliffhanger raised in one issue and never resolved, a finale that drifts onto a new subplot instead of landing the arc's intended ending, a promised through-line that never pays off, an event staged as the "first" in two different issues, a broken volume-to-volume hand-off) were only caught *after* all the scripts already existed — or not until a human read it. The autopilot now runs a **whole-manuscript beat-continuity pass over every issue's beat sheet, between beat generation and script generation**. Blocking findings are auto-resolved by rewriting just the affected issues' beats and re-checking (bounded, then it pauses for review with the residual findings), so the fix lands before any script is generated. The full-text editorial pass is unchanged and still catches what only the verbatim script can show (pacing, repeated/looping passages, dialogue craft). A new **Beat continuity rounds** control in the autopilot Options tunes how many auto-resolve rounds it attempts (0 skips the pass), saved as a per-install default like the existing Arc-verify and Editorial round knobs.diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex 671d1e26e8..f3d8de9a43 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -674,6 +674,13 @@"returnsJson": true,"variables": []},+ "pipeline-editorial-climax-agency": {+ "name": "Pipeline — Editorial Check: Climax / resolution power (passive protagonist at the climax)",+ "description": "Editorial check (#1583): judges whether the CLIMAX is the protagonist's hardest, most active choice (not a passive climax where an ally rescues them, the antagonist self-destructs, or a coincidence resolves the conflict) AND whether it resolves the story's core problem and lands the emotional/thematic argument (not just the surface plot). Reconciles the prose against the authored reader-map payoffs (series.arc.readerMap) and the declared themes (series.arc.themes), using the reverse-outline scene map to locate the climax; gates its verdict on the final manuscript part and degrades to a whole-manuscript scan when no reader-map, themes, or outline exists. Complements plot.structure-momentum. Returns issue-anchored findings.",+ "model": "default",+ "returnsJson": true,+ "variables": []+ },"pipeline-editorial-theme-coherence": {"name": "Pipeline — Editorial Check: Theme coherence / thematic throughline","description": "Editorial check (#1317): whether the manuscript actually DELIVERS its declared themes (series.arc.themes), not just states them. Builds a per-theme setup/complication/payoff coverage map, flags a theme that is stated but never dramatized or dropped after the opening, detects a strong EMERGENT theme not in the arc, and checks that the climax lands the thematic argument. Reads the stitched manuscript plus the authored arc themes and the reverse-outline scene map; degrades to a whole-manuscript scan when no outline or no themes exist. Returns issue-anchored findings.",diff --git a/data.reference/prompts/stages/pipeline-editorial-climax-agency.md b/data.reference/prompts/stages/pipeline-editorial-climax-agency.mdnew file mode 100644index 0000000000..ec65aa4f27--- /dev/null+++ b/data.reference/prompts/stages/pipeline-editorial-climax-agency.md@@ -0,0 +1,133 @@+# Pipeline — Editorial Check: Climax / resolution power (passive protagonist at the climax)++You are a developmental editor doing a single focused pass for ONE concern:+**does the climax land its power?** The climax is the payoff for the reader's+whole investment, and it works only when two things are true:++1. **Agency** — the climax is the PROTAGONIST'S hardest, most ACTIVE choice. They+ drive the resolution through a decision or action that costs them something —+ not a moment where an ally rescues them, the antagonist conveniently+ self-destructs, a coincidence resolves the conflict, or events simply happen+ TO them while they watch.+2. **Resolution power** — the climax resolves the story's CORE problem and lands+ its emotional/thematic argument — not just the surface plot. A climax that+ wins the fight but leaves the emotional/thematic core the story set up+ unanswered is a hollow climax.++Your job is to identify the climax scene and flag it ONLY when it fails one of+these. Do NOT police every scene — find the single payoff moment and judge it.++A genuine finding is one of:++- **passive climax** — the protagonist does not make the decisive choice: they+ are rescued, the obstacle removes itself, a coincidence or a minor character+ resolves the central conflict, or the protagonist is a spectator at their own+ climax.+- **thematic miss** — the climax resolves the plot but not the emotional/thematic+ core: the declared theme (or the question the story has been asking) is left+ unanswered, or the protagonist's internal arc does not pay off at the moment+ the external one does.++Do NOT flag: a climax where the protagonist makes the hard, active, costly choice+and it lands the core; a deliberate downbeat/ambiguous ending the story has+earned; an ensemble climax where the protagonist still drives their share; a+quiet (non-action) climax that is nonetheless the protagonist's decisive choice.++{{#authoredPayoffs}}+## Authored reader-map payoffs++The writer logged these payoffs — the resolutions the reader was PROMISED. Treat+them as what the climax is expected to deliver: a promised payoff the climax never+lands, or a climax that resolves something the story never set up, is a finding.++```+{{authoredPayoffs}}+```+{{/authoredPayoffs}}++{{#declaredThemes}}+## Declared themes++The story arc declares these themes. The climax should land the thematic+argument, not just the plot — a climax that resolves the action but leaves the+declared theme unanswered is a thematic miss.++```+{{declaredThemes}}+```+{{/declaredThemes}}++{{#sceneMap}}+## Scene segmentation++The reverse outline below segments the manuscript into scenes in story order+(with the recorded setting, POV character, and characters present). Use it to+LOCATE the climax (typically the latest, highest-stakes turning scene) and to+attribute your finding to the right `issueNumber`.++```+{{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`.++{{#finalPart}}+This is the FINAL part of the manuscript — the whole story is now in view, so the+climax can be identified and judged. Make your climax verdict here.+{{/finalPart}}+{{^finalPart}}+This is NOT the final part of the manuscript — the climax has likely not arrived+yet. Do NOT flag a climax verdict in this part; an earlier scene that looks like+a turning point may be set up to be eclipsed by the real climax later. Return an+empty `findings` array unless you can already see a clearly-completed climax in+this chunk.+{{/finalPart}}++```+{{manuscript}}+```++## Task++Identify the climax — the latest, highest-stakes scene where the central conflict+is resolved. Judge it for AGENCY and RESOLUTION POWER. For a genuine finding:++1. Name the climax scene (issue + a short description) and the central+ problem/theme it should resolve.+2. State which failure it is — a passive climax (who/what actually resolves it+ instead of the protagonist) or a thematic miss (which declared theme or+ emotional question is left unanswered) — and why.+3. Quote a short verbatim anchor (≤ 200 chars) at the climax passage.+4. Set the `location` to the climax scene + the failure kind — one of `agency`,+ `theme` — e.g. `Issue 6 climax — agency` or `Issue 6 climax — theme`.++Severity: a fully passive climax (the protagonist is rescued / a coincidence+resolves the core conflict) is high; a climax that lands the plot but misses the+theme is medium; a small thematic underweighting is low. If the climax is the+protagonist's hard, active choice AND lands the core, return an empty `findings`+array — do not invent a weakness where the climax works.++## Output contract++Return ONLY valid JSON matching this shape — no prose, no markdown fence, no+commentary:++```json+{+ "findings": [+ {+ "severity": "high|medium|low",+ "issueNumber": 6,+ "location": "string — climax scene + failure kind (e.g. 'Issue 6 climax — agency' or 'Issue 6 climax — theme')",+ "problem": "1–3 sentences naming the climax, the central problem/theme it should resolve, and why it fails on agency or resolution power",+ "suggestion": "1–3 sentences proposing how to give the protagonist the decisive active choice, or how to land the emotional/thematic core at the climax",+ "anchorQuote": "short verbatim quote at the climax passage (≤ 200 chars)"+ }+ ]+}+```diff --git a/scripts/migrations/131-editorial-climax-agency-stage.js b/scripts/migrations/131-editorial-climax-agency-stage.jsnew file mode 100644index 0000000000..c4955fb31d--- /dev/null+++ b/scripts/migrations/131-editorial-climax-agency-stage.js@@ -0,0 +1,75 @@+/**+ * Seed the `pipeline-editorial-climax-agency` stage into existing installs (#1583).+ *+ * Mirrors `130-editorial-character-consistency-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 climax-agency stage unseeded+ * and the `arc.climax-agency` 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-climax-agency.md';+const STAGE_KEY = 'pipeline-editorial-climax-agency';++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-climax-agency prompt: already present`);+ } else {+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);+ if (!sampleExists) {+ console.warn(`⚠️ pipeline-editorial-climax-agency: sample missing for ${FILENAME} — skipping copy`);+ } else {+ try {+ await copyFile(samplePath, dataPath);+ console.log(`✅ seeded ${FILENAME}`);+ } catch (err) {+ console.warn(`⚠️ pipeline-editorial-climax-agency: 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-climax-agency: 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-climax-agency stage-config: already present`);+ return;+ }+ if (!sample?.stages?.[STAGE_KEY]) {+ console.warn(`⚠️ pipeline-editorial-climax-agency: 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-climax-agency stage-config (${action}): 1 added`);+ } catch (err) {+ console.warn(`⚠️ pipeline-editorial-climax-agency: stage-config merge failed: ${err.message}`);+ }+ },+};diff --git a/scripts/migrations/131-editorial-climax-agency-stage.test.js b/scripts/migrations/131-editorial-climax-agency-stage.test.jsnew file mode 100644index 0000000000..b9456a8a57--- /dev/null+++ b/scripts/migrations/131-editorial-climax-agency-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 './131-editorial-climax-agency-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 130) — no MD5 bookkeeping, so the+// seed / no-clobber behavior is asserted directly.++const FILENAME = 'pipeline-editorial-climax-agency.md';+const STAGE_KEY = 'pipeline-editorial-climax-agency';+const BODY = '# Climax / resolution power\n\nshipped body\n';++describe('migration 131 — seed editorial-climax-agency 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-131-'));+ 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 d98fc13381..c2033b9c34 100644--- a/server/lib/editorial/checkRegistry.js+++ b/server/lib/editorial/checkRegistry.js@@ -560,6 +560,23 @@ export function declaredThemesSummary(themes) {return `Declared themes (authored on the story arc):\n${lines.join('\n')}`;}+// Stage name for the climax / resolution-power LLM check (#1583). Ships in+// data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 131 (boot runs+// migrations but NOT setup-data, so the migration is required). Reads the stitched+// manuscript plus the authored reader-map payoffs (series.arc.readerMap) and the+// declared themes (series.arc.themes) and the reverse-outline scene ordering, and+// judges whether the CLIMAX is the protagonist's hardest, most active choice (vs.+// a passive climax where an ally rescues them or events simply resolve around+// them) AND whether it resolves the story's core problem/theme (vs. a plot climax+// that lands the action but leaves the emotional/thematic core unanswered).+// Complements plot.structure-momentum (which flags a passive protagonist arc-wide;+// this one focuses the lens on the single payoff scene). The climax can only be+// judged once the whole manuscript is in view, so the run gates its verdict on the+// final part (`finalPart`); degrades to a prose-only scan when no reader-map,+// themes, or outline exist.+export const CLIMAX_AGENCY_STAGE = 'pipeline-editorial-climax-agency';+// Stage name for the unmodeled-proper-nouns LLM check (#1412). Ships in// data.reference/prompts/stages/ + stage-config.json (fresh installs via// setup-data.js) and migrates to existing installs via migration 116 (boot runs@@ -3363,6 +3380,84 @@ export const EDITORIAL_CHECKS = [});},},+ {+ id: 'arc.climax-agency',+ sources: ['manuscript', 'reverseOutline', 'series.arc.readerMap', 'series.arc.themes'],+ label: 'Climax / resolution power (passive protagonist at the climax)',+ description:+ 'LLM scan for a weak climax: the story\'s payoff scene should be the protagonist\'s HARDEST, most ACTIVE choice — the moment they drive the resolution. Flags a passive climax (an ally rescues them, the antagonist self-destructs, a coincidence resolves it, or events simply happen TO the protagonist) and a climax that resolves the PLOT but not the emotional/thematic core the story set up. Reconciles the prose against the authored reader-map payoffs (what the reader was promised) and the declared themes, using the reverse-outline scene map to locate the climax; degrades to a whole-manuscript scan when no reader-map, themes, or outline exists. Complements plot.structure-momentum (passive protagonist arc-wide) by focusing the lens on the single climax scene.',+ scope: 'series',+ kind: 'llm',+ category: 'arc',+ 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 authored payoffs name what the reader was PROMISED the+ // climax would resolve, the declared themes name the thematic core the+ // resolution must land, and the scene map lets the model LOCATE the climax+ // scene and attribute the finding to its issue. The check degrades+ // gracefully — no reader map ⇒ {{#authoredPayoffs}} renders nothing; no+ // themes ⇒ {{#declaredThemes}} renders nothing; no outline ⇒ {{#sceneMap}}+ // renders nothing and the model reasons from the prose's own shape.+ const authoredPayoffs = authoredSetupPayoffSummary(ctx.series?.arc?.readerMap);+ const declaredThemes = declaredThemesSummary(ctx.series?.arc?.themes);+ const sceneMap = sceneGroundingSummary(ctx.reverseOutline);+ return runManuscriptLlmCheck(ctx, {+ stage: CLIMAX_AGENCY_STAGE,+ category: 'arc',+ // sceneMap grows unbounded with scene count; authoredPayoffs and+ // declaredThemes are bounded — so largest-first trimming absorbs the cut+ // into sceneMap.+ context: { authoredPayoffs, declaredThemes, sceneMap },+ // `isFinal` gates the verdict — the climax is the END of the arc, so it+ // can only be identified and judged once the whole manuscript is in view.+ // An earlier chunk can't know which scene is the climax (or whether a+ // later beat is the real payoff), so it would false-flag. A single-chunk+ // run is its own final part and judges the whole text.+ buildVars: (manuscript, meta, c) => ({+ manuscript,+ authoredPayoffs: c.authoredPayoffs,+ declaredThemes: c.declaredThemes,+ sceneMap: c.sceneMap,+ finalPart: meta?.isFinal ? 'true' : '',+ }),+ // The climax's agency is judged against the whole arc's setup — the+ // protagonist's tries/failures and the problem they must personally+ // resolve accrue across the manuscript. The findings digest keeps prior+ // findings in view so a non-final chunk doesn't pre-flag, and the+ // clean-setup digest rolls forward the central problem + the protagonist's+ // pattern of agency so the final chunk can judge whether the climax is+ // their hardest active choice.+ crossChunkDigest: true,+ crossChunkSetup: true,+ setupFocus: 'Note the central problem/conflict the protagonist must personally resolve, '+ + 'the thematic question the story is asking, and the protagonist\'s pattern of agency so far '+ + '(do they drive events or do events happen to them) — so the final chunk can judge whether '+ + 'the climax is the protagonist\'s hardest, most active choice and whether it lands the '+ + 'emotional/thematic core, not just the plot.',+ });+ },+ },{id: 'relationships.reciprocity',sources: ['canon'],diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.jsindex c7f2db7dc0..b7fa397a22 100644--- a/server/lib/editorial/checkRegistry.test.js+++ b/server/lib/editorial/checkRegistry.test.js@@ -54,6 +54,7 @@ const THEME_COHERENCE = 'theme.coherence';const UNMODELED_NAMES = 'roster.unmodeled-names';const TIMELINE_CONTRADICTION = 'continuity.timeline-contradiction';const CHARACTER_CONSISTENCY = 'character.consistency';+const CLIMAX_AGENCY = 'arc.climax-agency';// A minimal valid stored custom-check definition.const customDef = (over = {}) => ({@@ -1160,6 +1161,96 @@ describe('theme.coherence — LLM check (#1317)', () => {});});+describe('arc.climax-agency — LLM check (#1583)', () => {+ const wholeCtx = (overrides = {}) => ({+ manuscript: '# Issue 1\n\nThe hero waited as the cavalry arrived.',+ config: { maxFindings: 12 },+ severityDefault: 'medium',+ series: { arc: {+ themes: ['earning forgiveness'],+ readerMap: { payoffs: [{ label: 'the debt is repaid', note: 'by the protagonist' }] },+ } },+ reverseOutline: [{ sequence: 0, issueNumber: 1, heading: 'The siege', setting: 'the gate', charactersPresent: ['Hero'] }],+ planManuscriptChunks: async () => ['# Issue 1\n\nThe hero waited as the cavalry arrived.'],+ callStagedLLM: async () => ({ content: { findings: [] } }),+ ...overrides,+ });++ it('is registered as a series-scoped LLM check reading manuscript + outline + reader-map + themes', () => {+ const check = getCheck(CLIMAX_AGENCY);+ expect(check.kind).toBe('llm');+ expect(check.scope).toBe('series');+ expect(check.category).toBe('arc');+ expect(check.severityDefault).toBe('medium');+ expect(check.sources).toEqual(['manuscript', 'reverseOutline', 'series.arc.readerMap', 'series.arc.themes']);+ expect(check.needsManuscript).toBe(true);+ });++ it('only runs when there is drafted prose to scan', () => {+ const check = getCheck(CLIMAX_AGENCY);+ expect(check.gate({ manuscript: '' })).toBe(false);+ expect(check.gate({ manuscript: '# Issue 1\n\nprose' })).toBeTruthy();+ });++ it('passes the manuscript, authored payoffs, declared themes, and scene map and forces the arc category', async () => {+ let seenVars = null;+ const ctx = wholeCtx({+ planManuscriptChunks: async (_stage, opts) => {+ // Authored payoffs + declared themes + scene map all ride as trimmable context.+ expect(opts.context).toHaveProperty('authoredPayoffs');+ expect(opts.context).toHaveProperty('declaredThemes');+ expect(opts.context).toHaveProperty('sceneMap');+ expect(opts.fixedOverheadTokens).toBeGreaterThan(0);+ return ['# Issue 1\n\nThe hero waited as the cavalry arrived and won the day.'];+ },+ callStagedLLM: async (_stage, vars) => {+ seenVars = vars;+ return { content: { findings: [{ severity: 'high', issueNumber: 1, location: 'Issue 1 climax — agency', problem: 'The cavalry, not the hero, resolves the conflict' }] } };+ },+ });+ const findings = await getCheck(CLIMAX_AGENCY).run(ctx);+ expect(seenVars.manuscript).toBe('# Issue 1\n\nThe hero waited as the cavalry arrived and won the day.');+ expect(seenVars.authoredPayoffs).toContain('the debt is repaid');+ expect(seenVars.declaredThemes).toContain('earning forgiveness');+ expect(seenVars.sceneMap).toContain('Issue 1: The siege');+ expect(findings).toHaveLength(1);+ expect(findings[0].category).toBe('arc');+ expect(findings[0].location).toBe('Issue 1 climax — agency');+ });++ it('passes empty context vars when the series has no reader-map, themes, or outline', async () => {+ let seenVars = null;+ const ctx = wholeCtx({+ series: {},+ reverseOutline: undefined,+ callStagedLLM: async (_stage, vars) => { seenVars = vars; return { content: { findings: [] } }; },+ });+ await getCheck(CLIMAX_AGENCY).run(ctx);+ expect(seenVars.authoredPayoffs).toBe('');+ expect(seenVars.declaredThemes).toBe('');+ expect(seenVars.sceneMap).toBe('');+ });++ it('marks a single-chunk run as the final part so the climax verdict is enabled', async () => {+ let seenVars = null;+ const ctx = wholeCtx({+ callStagedLLM: async (_stage, vars) => { seenVars = vars; return { content: { findings: [] } }; },+ });+ await getCheck(CLIMAX_AGENCY).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(CLIMAX_AGENCY).run(ctx);+ expect(finals).toEqual(['', '', 'true']);+ });+});+describe('declaredThemesSummary (#1317)', () => {it('returns an empty string when there are no themes', () => {expect(declaredThemesSummary(null)).toBe('');