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 head-hopping / POV discipline within scenes (#1311)
Adam Eivy3e642f7c5bc4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 92c698fa1f..2b1035965e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -3,6 +3,7 @@## Added- **[issue-1310] Editorial check flags plot-structure & momentum problems — passive protagonist, deus ex machina, idiot plot, flat stakes, sagging middle, dropped subplots.** A new **Plot structure & momentum** check (Create → Editorial Checks) reads your drafted manuscript and surfaces the macro pathologies a developmental editor flags at the arc level: a **passive protagonist** (events happen *to* them instead of being driven by their choices), a **deus ex machina / convenient coincidence** that resolves a problem by luck rather than setup, an **idiot plot** that only holds together because someone won't say the obvious, **flat or unclear stakes** that never escalate, a **sagging middle** with no try-fail rhythm, and **dropped subplots** — threads that open and then fizzle. It reconciles dropped threads against your reverse-outline plotline tags and your authored reader-map hooks/payoffs, and defers whole-arc judgments (a sagging middle, a never-resolved thread) until it has seen the whole manuscript so a long book reviewed in chunks isn't false-flagged. Findings render as `Plot structure` notes in the manuscript editor, anchored to the issue and (where one exists) a verbatim quote. Ships a new stage prompt (`pipeline-editorial-plot-structure`) that migrates for existing installs (111). (#1310)+- **[issue-1311] Editorial check flags head-hopping / POV-discipline breaks within a scene.** A new **Head-hopping / POV discipline** LLM check (Create → Editorial Checks) polices viewpoint discipline in limited-POV prose — distinct from the existing **POV justification** check (#1295, which asks whether each viewpoint *character* earns an arc). For each limited-POV scene it flags narration that enters another character's head (reports interior thoughts/feelings the POV character can't know), reports knowledge or perception the POV character couldn't have (offstage events, things behind them), or switches POV mid-scene with no break — and suggests re-anchoring to the POV character's perception or inserting a proper scene break. It reads your reverse-outline scene segmentation as context (each scene's anchored POV character + the other characters on-stage, the candidate heads a hop slips into) and **degrades gracefully** to a whole-issue manuscript scan when no outline exists yet. It **no-ops when the series style guide sets third-person omniscient** — there the roaming viewpoint is intentional — and surfaces the configured POV person (first / third-limited / second) to the model so it judges against the discipline actually in force. Each finding anchors a verbatim quote + issue number and names whose head was entered. Ships a new stage prompt (`pipeline-editorial-head-hopping`) that migrates for existing installs (112). (`server/lib/editorial/checkRegistry.js`, `scripts/migrations/112-editorial-head-hopping-stage.js`, #1311)- **[issue-1306] Line-edit / copy-edit pass — eight prose-tic editorial checks.** A bundle of deterministic copy-edit checks (Create → Editorial Checks) that catch the most common reader pet peeves and editorial red ink, each independently toggleable + configurable: **Filter words** (distancing verbs — saw/felt/noticed/began-to), **Crutch / filler words** (just/really/very/suddenly/"in order to"; bare "that" behind a toggle so grammatical "that" doesn't swamp the count), **Adverb overuse** (`-ly` adverbs, with adverb-laden dialogue tags — "said angrily" — flagged at higher severity), **Passive voice** (be-verb + past-participle heuristic, advisory), **Repeated gestures / body-part autonomy** (a gesture tally across the manuscript — nodded/smiled/shrugged — plus detached body parts that act on their own, "her eyes followed him across the room"), **Word repetition / echoes** (a distinctive word repeated within a window, plus repeated sentence openers — "He… He… He…"), and **Sentence rhythm & variety** (monotonous, uniform-length sentences). All are density-scaled — one "just" is fine, forty is a tic — with house-style allow/extra word lists and per-check thresholds, and ship sensible defaults so they don't drown the author. A ninth, LLM-judged sibling — **Telling-not-showing emotion** ("she was sad" → dramatize) — handles the false-positive-prone case a keyword scan can't, via a new stage prompt (`pipeline-editorial-telling-emotion`) that migrates for existing installs (110). The pure scanners live in `server/lib/editorial/proseTics.js` + `repetition.js` (no new deps). Reading-grade level is already covered by the existing `style.reading-level` check. (`server/lib/editorial/{proseTics,repetition,checkRegistry}.js`, `scripts/migrations/110-editorial-telling-emotion-stage.js`, #1306)diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex 77f2d6ee6f..a4d30d0923 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -610,6 +610,13 @@"model": "default","returnsJson": true,"variables": []+ },+ "pipeline-editorial-head-hopping": {+ "name": "Pipeline — Editorial Check: Head-hopping / POV discipline",+ "description": "Editorial check (#1311): in a limited-POV scene, flags narration that enters another character's head, reports knowledge/perception the POV character couldn't have, or switches POV mid-scene without a break. Reads the stitched manuscript plus the reverse-outline POV-per-scene map (degrading to a whole-issue scan when absent) and the series style guide's POV person; no-ops for third-person omniscient. Returns issue-anchored findings.",+ "model": "default",+ "returnsJson": true,+ "variables": []}}}diff --git a/data.reference/prompts/stages/pipeline-editorial-head-hopping.md b/data.reference/prompts/stages/pipeline-editorial-head-hopping.mdnew file mode 100644index 0000000000..ecdfee25c7--- /dev/null+++ b/data.reference/prompts/stages/pipeline-editorial-head-hopping.md@@ -0,0 +1,96 @@+# Pipeline — Editorial Check: Head-hopping / POV discipline++You are a developmental editor doing a single focused pass for ONE problem:+**head-hopping / POV-discipline breaks within a scene**. In a limited point of+view, the narration is anchored to ONE character per scene — the reader perceives+only what that character can see, hear, and know. A discipline break is when the+prose slips out of that anchor without a scene break.++The point of view in force for this story is **{{povPerson}}**. Judge every scene+against that limited anchor.++For each limited-POV scene, flag:++- **Entering another head** — the narration reports another character's interior+ thoughts, feelings, or motives the POV character has no way to know (e.g. "*she+ could tell he was secretly relieved*" stated as fact, not inference; "*he+ wondered if she'd noticed*" while anchored to her).+- **Impossible knowledge / perception** — the narration reports events offstage,+ things physically behind or out of sight of the POV character, or facts the POV+ character couldn't yet have learned.+- **Mid-scene POV switch** — the anchor silently shifts from one character to+ another partway through a scene with no scene break or section divider to mark+ the change.++Distinguish a genuine head-hop from legitimately-anchored interiority: the POV+character may freely think, feel, and *infer* about others from observable cues+("*his jaw tightened — he was angry*" is fine; "*he was angry, though he hid it+perfectly*" is a head-hop). Reporting what the POV character plausibly deduces is+in-bounds; asserting another character's private interior as narrated fact is not.++Do NOT flag: a deliberate, marked POV switch at a scene/section break (that's+structure, not head-hopping); a first-person or close-third narrator reasoning+about others from what they observe; dialogue or free indirect discourse that+stays inside the POV character's read of a situation. When in doubt about whether+a perception is a reasonable inference, do not flag — favor under-flagging.++{{#povMap}}+## POV per scene++The reverse outline below records each scene's anchored POV character and the+other characters on-stage (the candidate heads a head-hop would slip into). A+scene whose narration reports the interior of an "others present" character is a+strong head-hop candidate — confirm it against the prose. Judge the POV anchor+from the prose itself, not from this list alone.++```+{{povMap}}+```+{{/povMap}}++## 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`. If no POV map is+provided above, infer each scene's anchor from the prose and scan issue by issue.++```+{{manuscript}}+```++## Task++Find the passages where the narration breaks POV discipline. 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 break in the `location`+(e.g. `Issue 3 — entered Mara's head`, `Issue 4 — impossible knowledge`,+`Issue 2 — mid-scene POV switch`), explain whose head was entered or what the POV+character couldn't know, and suggest a concrete fix — re-anchor to the POV+character's perception (convert the asserted interior into an observable cue the+POV character reads), or insert a proper scene break if the switch is intentional.+Set severity by how jarring the break is — a sustained slip into another+character's running thoughts is more serious than a single stray line.++Be specific and cite the text. If every scene holds its POV anchor cleanly,+return an empty `findings` array — do not invent issues.++## Output contract++Return ONLY valid JSON matching this shape — no prose, no markdown fence, no+commentary:++```json+{+ "findings": [+ {+ "severity": "high|medium|low",+ "issueNumber": 3,+ "location": "string — the break type + whose head / where (e.g. 'Issue 3 — entered Mara's head')",+ "problem": "1–3 sentences naming the POV-discipline break and whose head was entered or what the POV character couldn't know",+ "suggestion": "1–3 sentences proposing a concrete re-anchor or a scene break",+ "anchorQuote": "short verbatim quote from the manuscript (≤ 200 chars)"+ }+ ]+}+```diff --git a/scripts/migrations/112-editorial-head-hopping-stage.js b/scripts/migrations/112-editorial-head-hopping-stage.jsnew file mode 100644index 0000000000..e8203f175b--- /dev/null+++ b/scripts/migrations/112-editorial-head-hopping-stage.js@@ -0,0 +1,75 @@+/**+ * Seed the `pipeline-editorial-head-hopping` stage into existing installs (#1311).+ *+ * Mirrors `110-editorial-telling-emotion-stage.js`: copies the `.md` template+ * from `data.reference/prompts/stages/` and merges the stage-config entry into+ * `data/prompts/stage-config.json`. Boot runs migrations (server/index.js) but+ * NOT `setup-data.js`, so an upgrade that pulls + `pm2 restart`s (rather than+ * running `update.sh`) would otherwise leave the new head-hopping stage unseeded+ * and the `pov.head-hopping` 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-head-hopping.md';+const STAGE_KEY = 'pipeline-editorial-head-hopping';++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-head-hopping prompt: already present`);+ } else {+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);+ if (!sampleExists) {+ console.warn(`⚠️ pipeline-editorial-head-hopping: sample missing for ${FILENAME} — skipping copy`);+ } else {+ try {+ await copyFile(samplePath, dataPath);+ console.log(`✅ seeded ${FILENAME}`);+ } catch (err) {+ console.warn(`⚠️ pipeline-editorial-head-hopping: 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-head-hopping: 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-head-hopping stage-config: already present`);+ return;+ }+ if (!sample?.stages?.[STAGE_KEY]) {+ console.warn(`⚠️ pipeline-editorial-head-hopping: 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-head-hopping stage-config (${action}): 1 added`);+ } catch (err) {+ console.warn(`⚠️ pipeline-editorial-head-hopping: stage-config merge failed: ${err.message}`);+ }+ },+};diff --git a/scripts/migrations/112-editorial-head-hopping-stage.test.js b/scripts/migrations/112-editorial-head-hopping-stage.test.jsnew file mode 100644index 0000000000..3c785baeb2--- /dev/null+++ b/scripts/migrations/112-editorial-head-hopping-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 './112-editorial-head-hopping-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 110) — no MD5 bookkeeping, so the+// seed / no-clobber behavior is asserted directly.++const FILENAME = 'pipeline-editorial-head-hopping.md';+const STAGE_KEY = 'pipeline-editorial-head-hopping';+const BODY = '# Head-hopping / POV discipline\n\nshipped body\n';++describe('migration 112 — seed editorial-head-hopping 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-112-'));+ 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 afd065f3dd..217d9fb7c9 100644--- a/server/lib/editorial/checkRegistry.js+++ b/server/lib/editorial/checkRegistry.js@@ -235,6 +235,15 @@ export const TELLING_EMOTION_STAGE = 'pipeline-editorial-telling-emotion';// subplots reconciled against the tagged plotlines.export const PLOT_STRUCTURE_STAGE = 'pipeline-editorial-plot-structure';+// Stage name for the head-hopping / POV-discipline LLM check (#1311). Ships in+// data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 112 (boot runs+// migrations but NOT setup-data, so the migration is required). Distinct from+// pov.justified (#1295, which asks whether each POV character earns an arc); this+// check polices POV *discipline* within a scene — narration that enters another+// character's head or reports what the POV character can't perceive.+export const HEAD_HOPPING_STAGE = 'pipeline-editorial-head-hopping';+// Render the authored reader-map cliffhangers (#1298) into a compact text block// the chapter-ending check passes alongside the manuscript so the model// reconciles its DETECTED endings against the issue-boundary tugs the writer@@ -1047,6 +1056,52 @@ export function plotlineCoverageSummary(plotlines, scenes) {return `Plotlines (from the reverse outline — reconcile dropped subplots against these):\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+// POV person identically. An omniscient style guide no-ops via the check's gate,+// so it's intentionally absent here.+const POV_PERSON_LABELS = Object.freeze({+ first: 'first person',+ 'third-limited': 'third-person limited',+ second: 'second person',+});++// Render the reverse-outline scenes into a compact POV-focused block the+// head-hopping check (#1311) passes alongside the manuscript so the model knows+// WHOSE head each limited-POV scene is anchored to — and which other characters+// are on-stage (candidate heads a head-hop would slip into). Pure + deterministic+// so it's unit-testable and its token cost can be counted into the per-chunk+// overhead. Returns '' when no scene carries a POV character (the prompt's+// `{{#povMap}}` section then renders nothing and the check degrades to a plain+// whole-issue scan). Type-guarded throughout — the reverse outline rides peer+// sync (#1348), so a hand-edited / older-peer scene could carry a non-string+// field that a bare `.trim()` would throw on.+export function scenePovSummary(scenes) {+ const list = Array.isArray(scenes) ? scenes : [];+ const lines = list.map((s) => {+ if (!s || typeof s !== 'object') return '';+ const pov = scenePov(s);+ if (!pov) return '';+ const label = sceneLabel(s);+ const issueNumber = Number.isInteger(s.issueNumber) ? s.issueNumber : null;+ const where = issueNumber != null ? `Issue ${issueNumber}` : 'Scene';+ // Other on-stage characters are the candidate heads a head-hop slips into —+ // exclude the POV holder themselves so the list names only "other" heads.+ const povKey = normalizeName(pov);+ const others = Array.isArray(s.charactersPresent)+ ? s.charactersPresent+ .filter((n) => typeof n === 'string' && n.trim() && normalizeName(n) !== povKey)+ .map((n) => n.trim())+ : [];+ const parts = [`- ${where}: ${label} — POV: ${pov}`];+ if (others.length) parts.push(`others present: ${others.join(', ')}`);+ return parts.join(' — ');+ }).filter(Boolean);+ if (!lines.length) return '';+ return `POV per scene (from the reverse outline):\n${lines.join('\n')}`;+}+// ---------------------------------------------------------------------------// Registry entries.// ---------------------------------------------------------------------------@@ -1696,6 +1751,60 @@ export const EDITORIAL_CHECKS = [return findings;},},+ {+ id: 'pov.head-hopping',+ sources: ['manuscript', 'reverseOutline', 'series.styleGuide'],+ label: 'Head-hopping / POV discipline within scenes',+ description:+ 'LLM scan — in a limited-POV scene, flags narration that enters another character\'s head (reports interior thoughts/feelings the POV character can\'t know), reports knowledge or perception the POV character couldn\'t have (offstage events, things behind them), or switches POV mid-scene without a break. Anchors each finding to the POV character and names whose head was entered. Distinct from pov.justified (which asks whether each viewpoint earns an arc). No-op when the style guide sets third-person omniscient — there the wandering viewpoint is intentional.',+ scope: 'scene',+ kind: 'llm',+ category: 'style',+ 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.',+ },+ ],+ // Skip when there's no prose, OR when the style guide declares third-person+ // omniscient — an omniscient narrator may freely roam between heads, so+ // "head-hopping" is intentional and there's nothing to police (#1311).+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0+ && ctx.series?.styleGuide?.povPerson !== 'third-omniscient',+ run: (ctx) => {+ // The POV-per-scene map is fixed per-call overhead (re-sent on each chunk).+ // It's context only — the check degrades gracefully to a whole-issue scan+ // when no reverse outline exists (the prompt's {{#povMap}} renders nothing).+ const povMap = scenePovSummary(ctx.reverseOutline);+ // Surface the configured POV person so the prompt names the discipline in+ // force (first / third-limited / second). Falls back to a neutral default+ // when unset — the check still runs (head-hopping is a problem in any+ // limited POV); only an explicit omniscient style guide no-ops via the gate.+ const povPerson = POV_PERSON_LABELS[ctx.series?.styleGuide?.povPerson]+ || 'a limited point of view';+ return runManuscriptLlmCheck(ctx, {+ stage: HEAD_HOPPING_STAGE,+ category: 'style',+ overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS+ + estimateTokens(povMap) + estimateTokens(povPerson),+ buildVars: (manuscript) => ({ manuscript, povMap, povPerson }),+ });+ },+ },{id: 'arc.transitions',sources: ['manuscript', 'reverseOutline', 'series.characterArcs'],diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.jsindex 7256c60a7b..7d51ef7eb3 100644--- a/server/lib/editorial/checkRegistry.test.js+++ b/server/lib/editorial/checkRegistry.test.js@@ -31,6 +31,7 @@ import {authoredCliffhangerSummary,sceneGroundingSummary,plotlineCoverageSummary,+ scenePovSummary,} from './checkRegistry.js';const NAMING = 'naming.dissimilar-names';@@ -42,6 +43,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 HEAD_HOPPING = 'pov.head-hopping';// A minimal valid stored custom-check definition.const customDef = (over = {}) => ({@@ -315,6 +317,123 @@ describe('sceneGroundingSummary (#1309)', () => {});});+describe('scenePovSummary (#1311)', () => {+ it('renders each POV-tagged scene with its POV holder and the OTHER characters present', () => {+ const summary = scenePovSummary([+ { sequence: 0, issueNumber: 1, heading: 'The kitchen', povCharacter: 'Mara', charactersPresent: ['Mara', 'Joss'] },+ { sequence: 1, issueNumber: 2, heading: 'Alone', povCharacter: 'Joss', charactersPresent: ['Joss'] },+ ]);+ expect(summary).toContain('POV per scene (from the reverse outline):');+ // The POV holder is excluded from "others present" — only candidate other heads remain.+ expect(summary).toContain('Issue 1: The kitchen — POV: Mara — others present: Joss');+ // A scene where only the POV holder is present lists no others.+ expect(summary).toContain('Issue 2: Alone — POV: Joss');+ expect(summary).not.toContain('Issue 2: Alone — POV: Joss — others present');+ });++ it('drops scenes with no POV character (nothing to police) and returns "" when none are tagged', () => {+ expect(scenePovSummary([{ sequence: 0, issueNumber: 1, heading: 'Untagged', charactersPresent: ['Mara'] }])).toBe('');+ expect(scenePovSummary([])).toBe('');+ expect(scenePovSummary(null)).toBe('');+ expect(scenePovSummary(undefined)).toBe('');+ });++ it('tolerates malformed scenes (peer-sync resilience) without throwing', () => {+ expect(() => scenePovSummary([+ null,+ { sequence: 2, povCharacter: 99, charactersPresent: 'not-an-array' },+ { sequence: 3, povCharacter: 'Mara', charactersPresent: [1, 2, null, 'Joss'] },+ ])).not.toThrow();+ const summary = scenePovSummary([{ sequence: 3, povCharacter: 'Mara', charactersPresent: [1, 2, null, 'Joss'] }]);+ // Non-string entries in charactersPresent are filtered out; the real other head survives.+ expect(summary).toContain('POV: Mara — others present: Joss');+ });+});++describe('pov.head-hopping — LLM check (#1311)', () => {+ const wholeCtx = (overrides = {}) => ({+ manuscript: '# Issue 1\n\nShe watched him. He was secretly relieved, though he hid it.',+ reverseOutline: [{ sequence: 0, issueNumber: 1, heading: 'The room', povCharacter: 'Mara', charactersPresent: ['Mara', 'Joss'] }],+ series: { styleGuide: { povPerson: 'third-limited' } },+ config: { maxFindings: 12 },+ severityDefault: 'medium',+ planManuscriptChunks: async () => [overrides.manuscript ?? '# Issue 1\n\nprose'],+ callStagedLLM: async () => ({ content: { findings: [] } }),+ ...overrides,+ });++ it('is registered as a manuscript+reverseOutline+styleGuide LLM check with category style', () => {+ const check = getCheck(HEAD_HOPPING);+ expect(check.kind).toBe('llm');+ expect(check.scope).toBe('scene');+ expect(check.category).toBe('style');+ expect(check.needsManuscript).toBe(true);+ expect(check.sources).toEqual(expect.arrayContaining(['manuscript', 'reverseOutline', 'series.styleGuide']));+ expect(check.severityDefault).toBe('medium');+ });++ it('gates on a non-empty manuscript', () => {+ const check = getCheck(HEAD_HOPPING);+ expect(check.gate({ manuscript: '' })).toBe(false);+ expect(check.gate({ manuscript: '# Issue 1\n\nprose' })).toBeTruthy();+ });++ it('no-ops (gate false) when the style guide is third-person omniscient', () => {+ const check = getCheck(HEAD_HOPPING);+ expect(check.gate({ manuscript: '# Issue 1\n\nprose', series: { styleGuide: { povPerson: 'third-omniscient' } } })).toBe(false);+ // Any other (limited) POV person — or none — still runs.+ expect(check.gate({ manuscript: '# Issue 1\n\nprose', series: { styleGuide: { povPerson: 'first' } } })).toBeTruthy();+ expect(check.gate({ manuscript: '# Issue 1\n\nprose', series: {} })).toBeTruthy();+ });++ it('injects the POV map + POV person into the prompt vars and counts them into the chunk overhead', async () => {+ let seenVars = null;+ let seenOverhead = 0;+ const ctx = wholeCtx({+ planManuscriptChunks: async (_stage, opts) => {+ seenOverhead = opts.overheadTokens;+ return ['# Issue 1\n\nchunk'];+ },+ callStagedLLM: async (_stage, vars) => {+ seenVars = vars;+ return { content: { findings: [{ severity: 'high', issueNumber: 1, problem: "entered Joss's head", anchorQuote: 'secretly relieved' }] } };+ },+ });+ const findings = await getCheck(HEAD_HOPPING).run(ctx);+ expect(seenVars.povMap).toContain('Issue 1: The room — POV: Mara — others present: Joss');+ expect(seenVars.povPerson).toBe('third-person limited');+ expect(seenOverhead).toBeGreaterThan(0);+ expect(findings).toHaveLength(1);+ expect(findings[0].category).toBe('style');+ expect(findings[0].issueNumber).toBe(1);+ });++ it('degrades to a whole-issue scan (empty POV map) and a neutral POV label when no outline / style guide exists', async () => {+ let seenVars = null;+ const ctx = wholeCtx({+ reverseOutline: undefined,+ series: {},+ callStagedLLM: async (_stage, vars) => {+ seenVars = vars;+ return { content: { findings: [] } };+ },+ });+ await getCheck(HEAD_HOPPING).run(ctx);+ expect(seenVars.povMap).toBe('');+ expect(seenVars.povPerson).toBe('a limited point of view');+ });++ it('respects maxFindings as a whole-run cap', async () => {+ const many = Array.from({ length: 30 }, (_, i) => ({ severity: 'medium', problem: `p${i}`, anchorQuote: `a${i}` }));+ const ctx = wholeCtx({+ config: { maxFindings: 4 },+ callStagedLLM: async () => ({ content: { findings: many } }),+ });+ const findings = await getCheck(HEAD_HOPPING).run(ctx);+ expect(findings).toHaveLength(4);+ });+});+describe.each([{ id: SENSORY_BALANCE, severityDefault: 'low', label: 'sensory.balance' },{ id: WHITE_ROOM, severityDefault: 'medium', label: 'scene.white-room' },