Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: editorial check for Chekhov's-gun setups & payoffs (#1299)
Adam Eivyc2a732dd43b0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 027cdabd7e..22bf175fd4 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **[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)+- **[issue-1296] Editorial check flags flat, single-mode scenes.** A new **Scene component balance** editorial check (Create → Editorial Checks) reads your reverse-outline scene segmentation and flags scenes that lean on a single mode — a wall of narration, talking heads with no action, or pure action with no interiority or voice. The craft rule is that a scene should mix at least two of **narrative, action, and dialogue**; the check names exactly which modes a flagged scene is missing and suggests how to ground it, anchoring to the issue the scene belongs to. The minimum (default 2 of 3, up to all 3) is configurable, and scenes the outline hasn't classified are left alone rather than false-flagged. Requires a generated reverse outline. (#1296)- **[issue-1294] Editorial check flags POV scenes with thin protagonist interiority.** A new **Protagonist interiority** editorial check (Create → Editorial Checks) reads your drafted manuscript and flags POV scenes that move a viewpoint character through events without ever getting us inside their head. It scores each POV scene across four distinct dimensions — **mind** (their thoughts and feelings in the moment), **objective** (what they want here and *why*), **emotional response** (to twists, betrayals, shocks), and **decision** (the reasoning behind their choices) — and surfaces the gaps: "we're in X's POV but never learn what they want," "a betrayal lands with no emotional response," "X decides but we don't see the reasoning." Each finding names which dimension is missing in its location so you can group gaps by kind, anchors a verbatim quote + issue number so you can jump straight to the spot, and scales severity by how POV-central the scene is. POV is read from the prose, so the check works even before scenes are explicitly POV-tagged. Runs on demand or as part of Series Autopilot's editorial pass; one new stage prompt (`pipeline-editorial-interiority`) ships + migrates for existing installs. (#1294)diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex f727a359bf..d9ec1b49c1 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -492,6 +492,13 @@"returnsJson": true,"variables": []},+ "pipeline-editorial-chekhov": {+ "name": "Pipeline — Editorial Check: Chekhov's guns (setups & payoffs)",+ "description": "Editorial check (#1299): flags planted elements that never pay off (weapon, clue, secret, stated fear, promise, threat, skill introduced then dropped) and payoffs that arrive with no setup. Reads the stitched manuscript across chunks with a cross-chunk setup digest, and reconciles detected setups/payoffs against the authored reader-map hooks/payoffs. 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-chekhov.md b/data.reference/prompts/stages/pipeline-editorial-chekhov.mdnew file mode 100644index 0000000000..6e1e0ee28b--- /dev/null+++ b/data.reference/prompts/stages/pipeline-editorial-chekhov.md@@ -0,0 +1,99 @@+# Pipeline — Editorial Check: Chekhov's guns (setups & payoffs)++You are a developmental editor doing a single focused pass for ONE problem:+**broken setups and payoffs** — Chekhov's-gun hygiene. The rule: *things planted+must go off; things that go off should have been planted.* Track concrete+**planted elements** across the manuscript and judge whether each is paid off.++Planted elements to track:++- **Objects / weapons / clues** — a gun on the mantel, a locked drawer, a strange+ key, a poison, a hidden letter.+- **Secrets** — something a character hides that the reader is told exists.+- **Stated fears** — a fear a character names or is shown to dread.+- **Promises / vows / oaths** — a commitment a character makes.+- **Threats** — a danger or consequence someone is warned of.+- **Notable skills / abilities** — a capability established as something a+ character can do.++A planted element is **paid off** when it later goes off: the weapon is used, the+secret spills, the fear is confronted, the promise is kept or broken on the page,+the threat lands, the skill is used at a decisive moment.++## What to flag++- **Planted, never fired** — "the locked drawer introduced in Issue 2 is never+ opened"; "Issue 1 makes a point of Mara's fear of water, but she never faces+ it." A setup the reader is primed to expect a payoff for, that the manuscript+ drops.+- **Fired, never planted** — "the antidote appears in Issue 7 with no prior+ setup"; "she suddenly picks a lock she was never shown able to pick." A payoff+ that lands unearned because nothing set it up.+- **Secret never spilled / fear never confronted / promise never resolved** —+ specific sub-cases of *planted, never fired* worth naming as such.++Do NOT flag: a deliberately unresolved thread the story clearly intends to carry+into a later installment; incidental scenery that is plainly not presented as+significant; a payoff that IS present (even if subtle) — the bar is a genuine+plant with no payoff, or a payoff with no plant.++{{#authoredSetups}}+## Reader-map the writer has already logged++The writer has logged these hooks and payoffs in the series reader-map. Reconcile+your findings against them: an authored hook with no payoff you can find in the+prose is a strong *planted-never-fired*; a strong payoff you find that is NOT in+this list may simply be unlogged (not necessarily a problem) — judge from the+prose, not the list alone. Do not invent findings just to match the list.++```+{{authoredSetups}}+```+{{/authoredSetups}}++## 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`. Because setups and payoffs+span issues, the text below may be prefixed with a short digest of elements+already planted in earlier parts — use it so you do not re-flag a setup that pays+off later, and so you can flag a setup from an earlier part that never fires.++```+{{manuscript}}+```++## Task++Find planted elements with no payoff, and payoffs with no plant. For each, quote a+short verbatim anchor from the text (≤ 200 characters) so the editor can jump to+it, name the issue number it appears in, classify the problem in the `location`+(e.g. `Issue 2 — planted, never fired`, `Issue 7 — fired, never planted`,+`Issue 1 — fear never confronted`), explain the broken setup/payoff, and suggest+the fix (plant earlier, pay off later, or cut). Set severity by how strongly the+element is foregrounded — a prominently planted gun that never fires is more+serious than a passing detail.++Be specific and cite the text. If every plant pays off and every payoff is set up,+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": 2,+ "location": "string — the classification + where (e.g. 'Issue 2 — planted, never fired')",+ "problem": "1–3 sentences naming the planted element (or unearned payoff) and what is missing",+ "suggestion": "1–3 sentences on the fix — plant earlier, pay off later, or cut",+ "anchorQuote": "short verbatim quote from the manuscript (≤ 200 chars)"+ }+ ]+}+```diff --git a/scripts/migrations/100-editorial-chekhov-stage.js b/scripts/migrations/100-editorial-chekhov-stage.jsnew file mode 100644index 0000000000..bf50c617c0--- /dev/null+++ b/scripts/migrations/100-editorial-chekhov-stage.js@@ -0,0 +1,75 @@+/**+ * Seed the `pipeline-editorial-chekhov` stage into existing installs (#1299).+ *+ * Mirrors `099-editorial-interiority-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 Chekhov-setup/payoff stage+ * unseeded and the `chekhov.setups-payoffs` 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-chekhov.md';+const STAGE_KEY = 'pipeline-editorial-chekhov';++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-chekhov prompt: already present`);+ } else {+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);+ if (!sampleExists) {+ console.warn(`⚠️ pipeline-editorial-chekhov: sample missing for ${FILENAME} — skipping copy`);+ } else {+ try {+ await copyFile(samplePath, dataPath);+ console.log(`✅ seeded ${FILENAME}`);+ } catch (err) {+ console.warn(`⚠️ pipeline-editorial-chekhov: 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-chekhov: 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-chekhov stage-config: already present`);+ return;+ }+ if (!sample?.stages?.[STAGE_KEY]) {+ console.warn(`⚠️ pipeline-editorial-chekhov: 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-chekhov stage-config (${action}): 1 added`);+ } catch (err) {+ console.warn(`⚠️ pipeline-editorial-chekhov: stage-config merge failed: ${err.message}`);+ }+ },+};diff --git a/scripts/migrations/100-editorial-chekhov-stage.test.js b/scripts/migrations/100-editorial-chekhov-stage.test.jsnew file mode 100644index 0000000000..dd2f8b3b42--- /dev/null+++ b/scripts/migrations/100-editorial-chekhov-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 './100-editorial-chekhov-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 099) — no MD5 bookkeeping, so the+// seed / no-clobber behavior is asserted directly.++const FILENAME = 'pipeline-editorial-chekhov.md';+const STAGE_KEY = 'pipeline-editorial-chekhov';+const BODY = "# Chekhov's guns\n\nshipped body\n";++describe('migration 100 — seed editorial-chekhov 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-100-'));+ stagesDir = join(rootDir, 'data', 'prompts', 'stages');+ refStagesDir = join(rootDir, 'data.reference', 'prompts', 'stages');+ installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');+ mkdirSync(stagesDir, { recursive: true });+ mkdirSync(refStagesDir, { recursive: true });+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('seeds the .md template and merges the stage-config entry on a fresh install', async () => {+ seedReference();+ await expect(migration.up({ rootDir })).resolves.not.toThrow();+ expect(readFileSync(join(stagesDir, FILENAME), 'utf8')).toBe(BODY);+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));+ expect(installed.stages[STAGE_KEY]).toMatchObject({ returnsJson: true });+ });++ it('is idempotent and never clobbers a customized .md or an existing stage-config entry', async () => {+ seedReference();+ const customBody = '# CUSTOMIZED — do not overwrite\n';+ writeFileSync(join(stagesDir, FILENAME), customBody);+ writeFileSync(+ installedConfigPath,+ JSON.stringify({ stages: { [STAGE_KEY]: { name: 'user-tuned', model: 'custom' } } }, null, 2) + '\n',+ );++ await migration.up({ rootDir });++ expect(readFileSync(join(stagesDir, FILENAME), 'utf8')).toBe(customBody);+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));+ expect(installed.stages[STAGE_KEY]).toEqual({ name: 'user-tuned', model: 'custom' });+ });++ it('does not throw when the data.reference samples are missing', async () => {+ await expect(migration.up({ rootDir })).resolves.not.toThrow();+ expect(existsSync(join(stagesDir, FILENAME))).toBe(false);+ });++ it('matches the live shipped stage-config key + prompt file (drift catch)', () => {+ const refConfig = JSON.parse(+ readFileSync(join(repoRoot, 'data.reference', 'prompts', 'stage-config.json'), 'utf8'),+ );+ expect(refConfig.stages[STAGE_KEY], `stage-config missing ${STAGE_KEY}`).toBeTruthy();+ expect(refConfig.stages[STAGE_KEY].returnsJson).toBe(true);+ expect(existsSync(join(repoRoot, 'data.reference', 'prompts', 'stages', FILENAME))).toBe(true);+ });+});diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.mdindex c08ebe9276..26d3d45896 100644--- a/server/lib/editorial/README.md+++ b/server/lib/editorial/README.md@@ -56,7 +56,8 @@ it. To add a new built-in check, append an entry to `EDITORIAL_CHECKS` inDeclare every input the check's `run(ctx)` reads in its `sources` array (anon-empty subset of `EDITORIAL_SOURCES`: `manuscript`, `canon`,-`series.styleGuide`, `series.arc.tickingClock`, `reverseOutline`). The staleness+`series.styleGuide`, `series.arc.tickingClock`, `series.arc.readerMap`,+`reverseOutline`). The stalenessrunner fingerprints exactly those sources, so a finding goes stale only whencontent the check actually analyzed drifts — declare too few and a finding staysfalsely fresh; a `manuscript` source must pair with `needsManuscript: true`, anddiff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.jsindex a474ff7c30..663f60bdeb 100644--- a/server/lib/editorial/checkRegistry.js+++ b/server/lib/editorial/checkRegistry.js@@ -48,11 +48,16 @@ const SEVERITIES = CHECK_SEVERITIES;// scenes carry components/povCharacter/charactersPresent.// The runner fetches it (gated on this source) and injects// `ctx.reverseOutline` (the scenes array).+// - 'series.arc.readerMap' — the series arc's authored reader-map (#1299): the+// writer-logged hooks (questions planted) and payoffs+// (their resolutions). The Chekhov check reconciles its+// detected setups/payoffs against these authored ones.export const EDITORIAL_SOURCES = Object.freeze(['manuscript','canon','series.styleGuide','series.arc.tickingClock',+ 'series.arc.readerMap','reverseOutline',]);@@ -98,6 +103,37 @@ export const STYLE_CONFORMANCE_STAGE = 'pipeline-editorial-style-conformance';// migrations but NOT setup-data, so the migration is required).export const INTERIORITY_STAGE = 'pipeline-editorial-interiority';+// Stage name for the Chekhov's-guns setup/payoff LLM check (#1299). Ships in+// data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 100 (boot runs+// migrations but NOT setup-data, so the migration is required).+export const CHEKHOV_STAGE = 'pipeline-editorial-chekhov';++// 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+// authored hook with no detected payoff, or a detected payoff the writer never+// logged. Pure + deterministic so it's unit-testable and so its token cost can be+// counted into the per-chunk overhead. Returns '' when nothing is authored (the+// prompt's `{{#authoredSetups}}` section then renders nothing).+export function authoredSetupPayoffSummary(readerMap) {+ const hooks = Array.isArray(readerMap?.hooks) ? readerMap.hooks : [];+ const payoffs = Array.isArray(readerMap?.payoffs) ? readerMap.payoffs : [];+ const line = (e) => {+ const label = typeof e?.label === 'string' ? e.label.trim() : '';+ const note = typeof e?.note === 'string' ? e.note.trim() : '';+ const text = label && note ? `${label} — ${note}` : (label || note);+ return text ? `- ${text}` : '';+ };+ const hookLines = hooks.map(line).filter(Boolean);+ const payoffLines = payoffs.map(line).filter(Boolean);+ if (!hookLines.length && !payoffLines.length) return '';+ const parts = [];+ if (hookLines.length) parts.push(`Authored hooks (questions the writer planted):\n${hookLines.join('\n')}`);+ if (payoffLines.length) parts.push(`Authored payoffs (resolutions the writer logged):\n${payoffLines.join('\n')}`);+ return parts.join('\n\n');+}+// ---------------------------------------------------------------------------// Character-name dissimilarity (#1291) reads cast names + aliases and respects// locked entries. The pure similarity primitives live in ./nameSimilarity.js;@@ -1675,6 +1711,57 @@ export const EDITORIAL_CHECKS = [});},},+ {+ id: 'chekhov.setups-payoffs',+ sources: ['manuscript', 'series.arc.readerMap'],+ label: "Chekhov's guns (setups & payoffs)",+ description:+ 'Flags planted elements that never pay off (a weapon, clue, secret, stated fear, promise, or threat introduced and then dropped) and payoffs that arrive with no setup (a skill, antidote, or revelation that appears unearned). Reconciles its detected setups/payoffs against the authored reader-map hooks/payoffs.',+ scope: 'series',+ kind: 'llm',+ category: 'continuity',+ 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) => {+ // Authored hooks/payoffs are fixed per-call overhead (re-sent on each chunk).+ const authoredSetups = authoredSetupPayoffSummary(ctx.series?.arc?.readerMap);+ return runManuscriptLlmCheck(ctx, {+ stage: CHEKHOV_STAGE,+ category: 'continuity',+ overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS + estimateTokens(authoredSetups),+ buildVars: (manuscript) => ({ manuscript, authoredSetups }),+ // A setup planted in chapter 2 and paid off (or NOT) in chapter 9 spans+ // chunks — the cross-chunk digest keeps prior findings in view so a later+ // chunk doesn't re-flag, and the clean-setup digest rolls forward which+ // elements have been planted-but-not-yet-paid so a payoff isn't mis-flagged+ // "no setup" and a never-fired plant is caught at the end.+ crossChunkDigest: true,+ crossChunkSetup: true,+ setupFocus: 'Planted elements that a later scene should pay off — weapons/objects/clues, '+ + 'secrets, stated fears, promises/vows, threats, and notable skills — and, for each, '+ + 'whether it has already been paid off (fired, spilled, confronted, kept) or is still open.',+ });+ },+ },];// ---------------------------------------------------------------------------diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.jsindex 9036d383be..593e4cfa0e 100644--- a/server/lib/editorial/checkRegistry.test.js+++ b/server/lib/editorial/checkRegistry.test.js@@ -27,11 +27,13 @@ import {EDITORIAL_SETUP_DIGEST_BODY_CHARS,EDITORIAL_SETUP_DIGEST_CHARS,EDITORIAL_SETUP_DIGEST_SOURCE,+ authoredSetupPayoffSummary,} from './checkRegistry.js';const NAMING = 'naming.dissimilar-names';const INFODUMP = 'prose.info-dumping';const INTERIORITY = 'interiority.protagonist';+const CHEKHOV = 'chekhov.setups-payoffs';// A minimal valid stored custom-check definition.const customDef = (over = {}) => ({@@ -332,6 +334,93 @@ describe('interiority.protagonist — LLM check (#1294)', () => {});});+describe('chekhov.setups-payoffs — LLM check (#1299)', () => {+ const wholeCtx = (overrides = {}) => ({+ manuscript: '# Issue 1\n\nHe slid the loaded revolver into the drawer and locked it.',+ config: { maxFindings: 12 },+ severityDefault: 'medium',+ series: {},+ planManuscriptChunks: async () => [overrides.manuscript ?? '# Issue 1\n\nHe slid the loaded revolver into the drawer and locked it.'],+ callStagedLLM: async () => ({ content: { findings: [] } }),+ ...overrides,+ });++ it('is registered as a series-scoped LLM check reading manuscript + reader-map', () => {+ const check = getCheck(CHEKHOV);+ expect(check.kind).toBe('llm');+ expect(check.scope).toBe('series');+ expect(check.category).toBe('continuity');+ 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(CHEKHOV);+ expect(check.gate({ manuscript: '' })).toBe(false);+ expect(check.gate({ manuscript: '# Issue 1\n\nprose' })).toBeTruthy();+ });++ it('passes the manuscript + authored reader-map setups to the model and forces the continuity category', async () => {+ let seenVars = null;+ const ctx = wholeCtx({+ series: { arc: { readerMap: { hooks: [{ label: 'The locked drawer', note: 'planted in Issue 1' }], payoffs: [] } } },+ planManuscriptChunks: async (_stage, opts) => {+ // Authored hooks/payoffs ride alongside the manuscript as fixed overhead.+ expect(opts.overheadTokens).toBeGreaterThan(0);+ return ['# Issue 1\n\nThe drawer stayed locked forever.'];+ },+ callStagedLLM: async (_stage, vars) => {+ seenVars = vars;+ return { content: { findings: [{ severity: 'high', issueNumber: 1, location: 'Issue 1 — planted, never fired', problem: 'The drawer never opens', anchorQuote: 'locked drawer' }] } };+ },+ });+ const findings = await getCheck(CHEKHOV).run(ctx);+ expect(seenVars.manuscript).toBe('# Issue 1\n\nThe drawer stayed locked forever.');+ expect(seenVars.authoredSetups).toContain('The locked drawer');+ expect(findings).toHaveLength(1);+ expect(findings[0].category).toBe('continuity');+ expect(findings[0].location).toBe('Issue 1 — planted, never fired');+ });++ it('passes an empty authoredSetups 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(CHEKHOV).run(ctx);+ expect(seenVars.authoredSetups).toBe('');+ });+});++describe('authoredSetupPayoffSummary (#1299)', () => {+ it('returns an empty string when there are no authored hooks or payoffs', () => {+ expect(authoredSetupPayoffSummary(null)).toBe('');+ expect(authoredSetupPayoffSummary({})).toBe('');+ expect(authoredSetupPayoffSummary({ hooks: [], payoffs: [] })).toBe('');+ });++ it('renders authored hooks and payoffs as labelled bullet lists', () => {+ const out = authoredSetupPayoffSummary({+ hooks: [{ label: 'Who killed the duke?', note: 'planted Issue 1' }, { label: 'The hidden heir' }],+ payoffs: [{ label: 'The butler confesses', note: 'Issue 8' }],+ });+ expect(out).toContain('Authored hooks');+ expect(out).toContain('- Who killed the duke? — planted Issue 1');+ expect(out).toContain('- The hidden heir');+ expect(out).toContain('Authored payoffs');+ expect(out).toContain('- The butler confesses — Issue 8');+ });++ it('drops entries with neither label nor note and falls back to note-only', () => {+ const out = authoredSetupPayoffSummary({+ hooks: [{ atArcPosition: 3 }, { note: 'a wordless dread' }],+ payoffs: [],+ });+ expect(out).toContain('- a wordless dread');+ expect(out).not.toContain('Authored payoffs');+ });+});+describe('naming.dissimilar-names — deterministic check', () => {const run = (characters, config = { minSharedSignals: 2 }) =>getCheck(NAMING).run({ canon: { characters }, config, severityDefault: 'low' });diff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.jsindex a3a990be29..2487aa1054 100644--- a/server/services/pipeline/editorial/checkRunner.js+++ b/server/services/pipeline/editorial/checkRunner.js@@ -54,6 +54,8 @@ const SOURCE_RESOLVERS = {canon: ({ canon }) => canonicalStringify(canon ?? null),'series.styleGuide': ({ series }) => canonicalStringify(series?.styleGuide ?? null),'series.arc.tickingClock': ({ series }) => canonicalStringify(series?.arc?.tickingClock ?? null),+ // The authored reader-map hooks/payoffs the Chekhov check reconciles against (#1299).+ 'series.arc.readerMap': ({ series }) => canonicalStringify(series?.arc?.readerMap ?? null),// The reverse-outline scenes the check reads (#1296). Fingerprinting the whole// scenes array is intentionally over-eager (any scene edit stales a finding)// rather than under: safe vs. false-fresh, and the check reads several scene fields.