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 secondary (non-POV) character-arc editorial check (#1585)
[._.]/ Adam Eivy2b2e5c7dcf9d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b0bffe88cc..a9401939b1 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -57,6 +57,8 @@- **[issue-1584] A new editorial check catches emotional beats that don't match the stakes — a trauma the story never processes, or a minor setback that triggers wildly outsized grief.** Nothing checked that reactions track event magnitude: a character could lose their brother in issue 2, the prose moves on, and the wound is never touched again — or a small disappointment could trigger a chapter of despair the story hasn't earned — and either way the emotional authenticity collapses without being flagged. The new **Emotional beat proportionality** check (`emotion.reaction-proportionality`) reads the stitched manuscript with the reverse-outline scene map to weigh each event's magnitude and flags two mismatches: an *under-reaction* (a high-magnitude event — death, trauma, betrayal, major loss or win — that draws no on-page reaction and is never processed in later issues) and an *over-reaction* (a minor setback triggering grief, rage, or despair out of all proportion). Because an unprocessed event in an early issue can stay unaddressed many issues later, the check carries every high-magnitude event still awaiting a proportionate reaction forward between manuscript chunks, so a trauma introduced early and then ignored is flagged against the later issue that should have paid it off; it degrades to a whole-manuscript scan when no outline exists, and respects characterization the story has established (a deliberately stoic or numb character isn't flagged for measured restraint). It's a default-on series check that surfaces in the existing editorial-review UI and Series Autopilot like every other check, marking a major trauma left wholly unprocessed high-severity. (`server/lib/editorial/checkRegistry.js`, `data.reference/prompts/stages/pipeline-editorial-reaction-proportionality.md`, `scripts/migrations/132-editorial-reaction-proportionality-stage.js`)+- **[issue-1585] A new editorial check catches flat secondary characters — a recurring side character who appears scene after scene but is exactly the same at the end as at the start.** The existing `pov.justified` check asks whether each *POV* character earns their viewpoint, but nothing judged the *non-POV* cast — so a recurring side character (a partner, a foil, a co-worker who shows up across half the book) could stay completely static, draining the story's texture, without ever being flagged. The new **Secondary-character arcs** check (`character.secondary-arc`) tallies the recurring non-POV cast from the reverse-outline scene map — characters present across multiple scenes who never hold the viewpoint — and judges whether each shows meaningful change, flagging a *flat arc* (the same situation, attitude, and standing at the end as the start) or a *purposeless regression* (an arc that quietly undoes itself with nothing in the story making it meaningful). It reads the stitched manuscript with the recurring-cast roster and the canon roster, deliberately ignoring genuine walk-ons (a one- or two-scene bit player owes the reader no arc) and a deliberately-static foil whose constancy is the point. Because a flat arc is a whole-story claim, it carries each recurring secondary's established state forward between manuscript chunks and gates its verdict on the final part — so a character established early whose change lands in a chapter no longer in view isn't falsely flagged — and degrades to a whole-manuscript scan when no outline exists. A configurable **recurring threshold** (default 2 scenes) tunes how prominent a character must be before it's held to an arc. It's a default-on series check that surfaces in the existing editorial-review UI and Series Autopilot like every other check, marking a prominent recurring character left wholly flat medium-severity. (`server/lib/editorial/checkRegistry.js`, `data.reference/prompts/stages/pipeline-editorial-secondary-arc.md`, `scripts/migrations/133-editorial-secondary-arc-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 5f759c7fb7..2703ecc52d 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -688,6 +688,13 @@"returnsJson": true,"variables": []},+ "pipeline-editorial-secondary-arc": {+ "name": "Pipeline — Editorial Check: Secondary-character arcs (recurring non-POV cast)",+ "description": "Editorial check (#1585): the non-POV sibling of pov.justified (#1295). Tallies recurring NON-POV characters from the reverse-outline scene map (present across multiple scenes but never holding the viewpoint) and judges whether each shows meaningful change — flagging a flat side character (same at the end as the start) or one who regresses with no purpose. Does not flag a genuine walk-on or a deliberately-static foil whose constancy is the point. Because a flat arc is a whole-story claim, the verdict lands on the final manuscript part and each recurring secondary's established state is carried across parts; degrades to a whole-manuscript scan when no outline exists. 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-secondary-arc.md b/data.reference/prompts/stages/pipeline-editorial-secondary-arc.mdnew file mode 100644index 0000000000..7417b2b4a6--- /dev/null+++ b/data.reference/prompts/stages/pipeline-editorial-secondary-arc.md@@ -0,0 +1,131 @@+# Pipeline — Editorial Check: Secondary-character arcs (recurring non-POV cast)++You are a developmental editor doing a single focused pass for ONE concern:+**do the recurring NON-POV characters change, or are they flat?** A POV character+earns their viewpoint through an arc (a separate check covers that). This pass is+about the *side* cast — the characters who appear across multiple scenes but never+hold the narrative viewpoint. A story gains texture when its supporting players+are people who want things and change; it goes flat when they are furniture —+present in scene after scene, exactly the same at the end as at the start.++A genuine finding is one of:++- **flat recurring secondary** — a character present across several scenes who+ shows no meaningful change over the whole story: their situation, attitude,+ wants, and standing are the same at the end as the start, and the prose never+ uses them to mark a shift. They function as a fixture, not a person.+- **purposeless regression** — a recurring secondary character who regresses (loses+ ground, reverts to an earlier state) with nothing in the story making that+ regression meaningful — not a tragic fall the narrative is dramatizing, just an+ arc that quietly undoes itself.++Your job is to flag the genuine gaps — NOT to demand a full arc from every name on+the page. Do NOT flag:++- a **genuine walk-on** — a character in only one or two scenes whose job is to+ deliver a line or a function; a bit player does not owe the reader an arc.+- a **deliberately static figure** whose constancy is the point — an anchor, a+ foil, or a rock the protagonist changes *against*. If the stillness is doing+ work (it throws the protagonist's change into relief, or it's the steady world+ the hero leaves), it is not a flaw.+- a character the story clearly frames as **minor texture** (a recurring shopkeeper,+ a background colleague) who is not asked to carry weight.+- a POV character — those are judged elsewhere; focus only on the non-POV cast.++{{#secondaryCast}}+## Recurring non-POV cast++The reverse outline below lists the recurring NON-POV characters — those present+across multiple scenes who never hold the viewpoint — with how many scenes each+appears in and the span of issues they touch. These are the characters to judge+for an arc; weigh how prominent each is (more scenes ⇒ more is owed). A character+NOT on this list is either a POV character or too minor to hold to an arc.++```+{{secondaryCast}}+```+{{/secondaryCast}}++{{#canonRoster}}+## Canon character roster++The established character bible — use it to tell a modeled, recurring character+(who genuinely carries weight) from an incidental name, and to ground each+character's established traits so you can judge change against a real baseline.++```+{{canonRoster}}+```+{{/canonRoster}}++## 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 a+**flat arc** ("this recurring secondary never changes") can now be judged: a+change would have appeared by now if it were coming. **The character may have been+established in an EARLIER part, not in the text below.** The "setup so far" digest+above carries forward each recurring secondary character's established state and+any change shown so far — flag each recurring secondary the whole story leaves+flat (or regresses with no purpose), attributing the finding to the issue where+their lack of change is clearest. Use a verbatim line that typifies the+character's static presence as your `anchorQuote`.+{{/finalPart}}+{{^finalPart}}+This is NOT the final part of the manuscript. Do NOT report a **flat arc** finding+here — a later part may still give the character their change, and a premature+"never changes" claim cannot be retracted. Recurring secondary characters and+their established state are carried forward in the "setup so far" digest and judged+once the final part is in view. In this part, note (do not yet flag) the recurring+secondaries and how they are introduced.+{{/finalPart}}++```+{{manuscript}}+```++## Task++Identify recurring NON-POV characters whose arc is flat or purposelessly+regressive — subject to the part gate above (flat-arc verdicts only in the final+part). For each genuine finding:++1. Name the character and how prominent they are (how many scenes / issues they+ span — they must be recurring, not a walk-on).+2. State the gap — a flat arc (same at the end as the start, with what the story+ could have moved) or a purposeless regression (what reverts, and why nothing+ makes it meaningful).+3. Quote a short verbatim anchor (≤ 200 chars) that typifies the character's+ static (or regressing) presence.+4. Set the `location` to the character + the gap kind — e.g.+ `Issue 5 — Dev — flat arc` or `Issue 3 — Reza — purposeless regression`.++Severity: a prominent recurring secondary (a near-co-lead present across much of+the story) left wholly flat is medium; a moderately-recurring side character with+no change is low; a small texture wobble is low. If every recurring secondary+either changes meaningfully or is deliberately, purposefully static, return an+empty `findings` array — do not invent an arc gap where the cast is doing its job.++## Output contract++Return ONLY valid JSON matching this shape — no prose, no markdown fence, no+commentary:++```json+{+ "findings": [+ {+ "severity": "high|medium|low",+ "issueNumber": 5,+ "location": "string — character + gap kind (e.g. 'Issue 5 — Dev — flat arc' or 'Issue 3 — Reza — purposeless regression')",+ "problem": "1–3 sentences naming the recurring secondary, how prominent they are, and the gap (flat / regressing, and what change the story could have given them)",+ "suggestion": "1–3 sentences proposing a beat — a small want, decision, or shift that would give the character an arc, or how to make a static figure's constancy purposeful",+ "anchorQuote": "short verbatim quote that typifies the character's static or regressing presence (≤ 200 chars)"+ }+ ]+}+```diff --git a/scripts/migrations/133-editorial-secondary-arc-stage.js b/scripts/migrations/133-editorial-secondary-arc-stage.jsnew file mode 100644index 0000000000..05feaecc4b--- /dev/null+++ b/scripts/migrations/133-editorial-secondary-arc-stage.js@@ -0,0 +1,75 @@+/**+ * Seed the `pipeline-editorial-secondary-arc` stage into existing installs (#1585).+ *+ * Mirrors `132-editorial-reaction-proportionality-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 secondary-arc stage unseeded+ * and the `character.secondary-arc` 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-secondary-arc.md';+const STAGE_KEY = 'pipeline-editorial-secondary-arc';++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-secondary-arc prompt: already present`);+ } else {+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);+ if (!sampleExists) {+ console.warn(`⚠️ pipeline-editorial-secondary-arc: sample missing for ${FILENAME} — skipping copy`);+ } else {+ try {+ await copyFile(samplePath, dataPath);+ console.log(`✅ seeded ${FILENAME}`);+ } catch (err) {+ console.warn(`⚠️ pipeline-editorial-secondary-arc: 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-secondary-arc: 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-secondary-arc stage-config: already present`);+ return;+ }+ if (!sample?.stages?.[STAGE_KEY]) {+ console.warn(`⚠️ pipeline-editorial-secondary-arc: 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-secondary-arc stage-config (${action}): 1 added`);+ } catch (err) {+ console.warn(`⚠️ pipeline-editorial-secondary-arc: stage-config merge failed: ${err.message}`);+ }+ },+};diff --git a/scripts/migrations/133-editorial-secondary-arc-stage.test.js b/scripts/migrations/133-editorial-secondary-arc-stage.test.jsnew file mode 100644index 0000000000..df8c6816ad--- /dev/null+++ b/scripts/migrations/133-editorial-secondary-arc-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 './133-editorial-secondary-arc-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 132) — no MD5 bookkeeping, so the+// seed / no-clobber behavior is asserted directly.++const FILENAME = 'pipeline-editorial-secondary-arc.md';+const STAGE_KEY = 'pipeline-editorial-secondary-arc';+const BODY = '# Secondary-character arcs\n\nshipped body\n';++describe('migration 133 — seed editorial-secondary-arc 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-133-'));+ 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 aacf3211ac..606155f7ad 100644--- a/server/lib/editorial/checkRegistry.js+++ b/server/lib/editorial/checkRegistry.js@@ -613,6 +613,23 @@ export const CLIMAX_AGENCY_STAGE = 'pipeline-editorial-climax-agency';// payoff; degrades to a prose-only scan when no outline exists.export const REACTION_PROPORTIONALITY_STAGE = 'pipeline-editorial-reaction-proportionality';+// Stage name for the secondary (non-POV) character-arc LLM check (#1585). Ships+// in data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 133 (boot runs+// migrations but NOT setup-data, so the migration is required). The sibling of+// pov.justified (#1295), which covers POV characters only: this check judges the+// RECURRING NON-POV cast — characters who appear in multiple scenes but never+// hold the viewpoint — and flags those who never change (a flat side character+// who is the same at the end as the start) or who regress without purpose. Reads+// the stitched manuscript plus the reverse-outline scene map (to tally which+// non-POV characters recur and weigh their presence) and the canon roster (so a+// genuinely-minor walk-on isn't held to an arc). Because a flat arc is a+// whole-story claim, the run gates its verdict on the final part (`finalPart`)+// and carries each recurring secondary character's established state forward+// across chunks (`crossChunkSetup`); degrades to a prose-only scan when no+// outline exists.+export const SECONDARY_ARC_STAGE = 'pipeline-editorial-secondary-arc';+// 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@@ -1640,6 +1657,70 @@ export function scenePovSummary(scenes) {return `POV per scene (from the reverse outline):\n${lines.join('\n')}`;}+// Render the RECURRING NON-POV cast (#1585) into a compact text block the+// secondary-arc check passes alongside the manuscript, so the model focuses on+// the side characters that actually carry weight (present across multiple scenes)+// rather than every walk-on. A "secondary" character is one who appears in+// `charactersPresent` but NEVER holds `povCharacter` in ANY scene — a character+// who ever takes the viewpoint is a POV character (covered by pov.justified). For+// each such character we count the scenes they appear in and the span of issues+// those scenes touch, keeping only those at or above `minScenes` (the recurrence+// threshold). Pure + deterministic so it's unit-testable and its token cost can+// be counted into the per-chunk overhead. Returns '' when no non-POV character+// recurs enough (the prompt's `{{#secondaryCast}}` section then renders nothing+// and the check degrades to identifying recurring side characters from the prose+// alone). Type-guarded throughout — the reverse outline rides peer sync (#1348),+// so a hand-edited / older-peer scene could carry a non-string field a bare+// `.trim()` would throw on.+export function secondaryCharacterPresenceSummary(scenes, { minScenes = 2 } = {}) {+ const list = Array.isArray(scenes) ? scenes : [];+ const threshold = Number.isInteger(minScenes) && minScenes > 0 ? minScenes : 2;++ // Every character who EVER holds the viewpoint, by normalized name — these are+ // POV characters and are excluded from the secondary cast even in scenes where+ // they happen to be present-but-not-narrating.+ const povHolders = new Set();+ for (const s of list) {+ const pov = scenePov(s);+ if (pov) povHolders.add(normalizeName(pov));+ }++ // Non-POV character → { name, sceneCount, issues } keyed by normalized name so+ // casing / spacing variants collapse. Preserves first-appearance order (scenes+ // arrive sequence-ordered) for stable output.+ const cast = new Map();+ for (const s of list) {+ if (!s || typeof s !== 'object') continue;+ const issueNumber = Number.isInteger(s.issueNumber) ? s.issueNumber : null;+ const present = Array.isArray(s.charactersPresent)+ ? s.charactersPresent.filter((n) => typeof n === 'string' && n.trim()).map((n) => n.trim())+ : [];+ // De-dup names within a single scene so a name listed twice counts once.+ const seenThisScene = new Set();+ for (const name of present) {+ const key = normalizeName(name);+ if (!key || povHolders.has(key) || seenThisScene.has(key)) continue;+ seenThisScene.add(key);+ let entry = cast.get(key);+ if (!entry) { entry = { name, sceneCount: 0, issues: new Set() }; cast.set(key, entry); }+ entry.sceneCount += 1;+ if (issueNumber != null) entry.issues.add(issueNumber);+ }+ }++ const rows = [];+ for (const entry of cast.values()) {+ if (entry.sceneCount < threshold) continue;+ const issues = [...entry.issues].sort((a, b) => a - b);+ const span = issues.length+ ? (issues.length === 1 ? `issue ${issues[0]}` : `issues ${issues[0]}–${issues[issues.length - 1]}`)+ : 'no tagged issues';+ rows.push(`- ${entry.name}: present in ${entry.sceneCount} scene${entry.sceneCount === 1 ? '' : 's'} (${span})`);+ }+ if (!rows.length) return '';+ return `Recurring non-POV characters (appear in ${threshold}+ scenes but never hold POV — judge whether each shows meaningful change):\n${rows.join('\n')}`;+}+// ---------------------------------------------------------------------------// Registry entries.// ---------------------------------------------------------------------------@@ -3218,6 +3299,93 @@ export const EDITORIAL_CHECKS = [});},},+ {+ id: 'character.secondary-arc',+ sources: ['manuscript', 'reverseOutline', 'canon'],+ label: 'Secondary-character arcs (recurring non-POV cast)',+ description:+ 'LLM scan — the non-POV sibling of pov.justified (#1295). Tallies recurring NON-POV characters from the reverse-outline scene map (present in multiple scenes but never holding the viewpoint) and judges whether each shows meaningful change across the story: a flat side character who is the same at the end as at the start, or one who regresses with no purpose. A world of flat side characters drains a story\'s texture. Does NOT flag a genuine walk-on (a one-scene minor) or a deliberately-static figure whose constancy is the point (an anchor/foil the protagonist changes against); judges only the recurring cast. Because a flat arc is a whole-story claim, the verdict lands on the final manuscript part once every scene is in view; degrades to a whole-manuscript scan when no outline exists.',+ scope: 'series',+ kind: 'llm',+ category: 'arc',+ // Fallback severity when the model omits one — 'low' to match pov.justified+ // (a secondary-cast arc gap is a texture concern, not a structural break). The+ // prompt directs the model to mark a prominent recurring character left wholly+ // flat 'medium', so a genuinely-thin co-lead still surfaces above the floor.+ severityDefault: 'low',+ 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({+ // A non-POV character must appear in at least this many scenes to count as+ // recurring (and therefore be held to an arc). 1 would judge every walk-on;+ // 2 is the smallest "recurring" threshold.+ minScenes: z.number().int().min(2).max(20).default(2),+ // Cap findings per run so a large cast can't flood the review.+ maxFindings: z.number().int().min(1).max(50).default(12),+ }),+ configFields: [+ {+ key: 'minScenes',+ label: 'Recurring threshold (min scenes)',+ type: 'number',+ min: 2,+ max: 20,+ step: 1,+ help: 'A non-POV character must appear in at least this many scenes to be judged for an arc. 2 is the smallest "recurring" threshold; raise it to focus on only the most prominent secondary characters.',+ },+ {+ key: 'maxFindings',+ label: 'Max findings per run',+ type: 'number',+ min: 1,+ max: 50,+ step: 1,+ help: 'Cap findings so a large cast can not flood the review.',+ },+ ],+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,+ run: (ctx) => {+ // Both blocks are fixed per-call overhead (re-sent on each chunk) and pure+ // context: the secondary-cast roster names which recurring non-POV+ // characters to hold to an arc (so the model focuses on the side characters+ // that carry weight, not every walk-on), and the canon roster lets the model+ // tell a modeled recurring character from an incidental name. The check+ // degrades gracefully — no outline ⇒ {{#secondaryCast}} renders nothing and+ // the model identifies the recurring side cast from the prose; no canon ⇒+ // {{#canonRoster}} renders nothing.+ const minScenes = ctx.config?.minScenes ?? 2;+ const secondaryCast = secondaryCharacterPresenceSummary(ctx.reverseOutline, { minScenes });+ const canonRoster = canonCharacterTraitsSummary(ctx.canon);+ return runManuscriptLlmCheck(ctx, {+ stage: SECONDARY_ARC_STAGE,+ category: 'arc',+ context: { secondaryCast, canonRoster },+ buildVars: (manuscript, meta, c) => ({+ manuscript,+ secondaryCast: c.secondaryCast,+ canonRoster: c.canonRoster,+ finalPart: meta?.isFinal ? 'true' : '',+ }),+ // A flat arc is only visible across the WHOLE story — a character+ // established in an early chunk who never changes by the last. The+ // findings digest keeps prior findings in view so a later chunk doesn't+ // re-flag, and the clean-setup digest rolls each recurring secondary+ // character's established state forward so the final part can tell a flat+ // arc from one that changes in a chunk it can no longer see.+ crossChunkDigest: true,+ crossChunkSetup: true,+ setupFocus: 'For each recurring NON-POV character (a character present across multiple scenes who never '+ + 'holds the viewpoint), note their established state on first appearance — their situation, attitude, '+ + 'wants, and standing — and record any CHANGE the prose has shown them undergo since (a decision, a '+ + 'shift in attitude or circumstance, a relationship that turns). Carry these forward so the final part '+ + 'can tell a genuinely flat side character (same at the end as the start) from one whose change happened '+ + 'in an earlier part no longer in view. Drop a character from the watch-list once the prose has shown '+ + 'them a meaningful arc.',+ });+ },+ },{id: 'arc.transitions',sources: ['manuscript', 'reverseOutline', 'series.characterArcs'],diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.jsindex 5ec4dd3d7d..90fa6fd02c 100644--- a/server/lib/editorial/checkRegistry.test.js+++ b/server/lib/editorial/checkRegistry.test.js@@ -34,6 +34,7 @@ import {characterVoiceProfiles,plotlineCoverageSummary,scenePovSummary,+ secondaryCharacterPresenceSummary,declaredThemesSummary,canonRosterNamesSummary,canonCharacterStatesSummary,@@ -57,6 +58,7 @@ const TIMELINE_CONTRADICTION = 'continuity.timeline-contradiction';const CHARACTER_CONSISTENCY = 'character.consistency';const CLIMAX_AGENCY = 'arc.climax-agency';const REACTION_PROPORTIONALITY = 'emotion.reaction-proportionality';+const SECONDARY_ARC = 'character.secondary-arc';// A minimal valid stored custom-check definition.const customDef = (over = {}) => ({@@ -1366,6 +1368,167 @@ describe('emotion.reaction-proportionality — LLM check (#1584)', () => {});});+describe('secondaryCharacterPresenceSummary (#1585)', () => {+ it('tallies recurring NON-POV characters, excluding anyone who ever holds POV', () => {+ const summary = secondaryCharacterPresenceSummary([+ { sequence: 0, issueNumber: 1, povCharacter: 'Mara', charactersPresent: ['Mara', 'Joss', 'Reza'] },+ { sequence: 1, issueNumber: 2, povCharacter: 'Mara', charactersPresent: ['Mara', 'Joss'] },+ { sequence: 2, issueNumber: 3, povCharacter: 'Joss', charactersPresent: ['Joss', 'Reza'] },+ ]);+ expect(summary).toContain('Recurring non-POV characters');+ // Reza is present in 2 scenes and never holds POV → recurring secondary.+ expect(summary).toContain('Reza: present in 2 scenes (issues 1–3)');+ // Joss holds POV in scene 3, so although present in 3 scenes they are a POV+ // character (judged by pov.justified) and excluded entirely.+ expect(summary).not.toContain('Joss:');+ // Mara is the POV holder throughout → never a secondary.+ expect(summary).not.toContain('Mara:');+ });++ it('drops a one-scene walk-on below the recurrence threshold', () => {+ const summary = secondaryCharacterPresenceSummary([+ { sequence: 0, issueNumber: 1, povCharacter: 'Mara', charactersPresent: ['Mara', 'Cole'] },+ ]);+ // Cole appears once → below minScenes default of 2 → no roster.+ expect(summary).toBe('');+ });++ it('respects a raised minScenes threshold', () => {+ const scenes = [+ { sequence: 0, issueNumber: 1, povCharacter: 'Mara', charactersPresent: ['Mara', 'Reza'] },+ { sequence: 1, issueNumber: 2, povCharacter: 'Mara', charactersPresent: ['Mara', 'Reza'] },+ ];+ // Reza appears in 2 scenes: surfaces at the default but not at minScenes 3.+ expect(secondaryCharacterPresenceSummary(scenes, { minScenes: 2 })).toContain('Reza');+ expect(secondaryCharacterPresenceSummary(scenes, { minScenes: 3 })).toBe('');+ });++ it('counts a character once per scene even if listed twice', () => {+ const summary = secondaryCharacterPresenceSummary([+ { sequence: 0, issueNumber: 1, povCharacter: 'Mara', charactersPresent: ['Reza', 'reza'] },+ { sequence: 1, issueNumber: 2, povCharacter: 'Mara', charactersPresent: ['Reza'] },+ ]);+ // Two scenes, not three — the in-scene duplicate collapses by normalized name.+ expect(summary).toContain('Reza: present in 2 scenes');+ });++ it('returns "" when there are no scenes', () => {+ expect(secondaryCharacterPresenceSummary([])).toBe('');+ expect(secondaryCharacterPresenceSummary(null)).toBe('');+ expect(secondaryCharacterPresenceSummary(undefined)).toBe('');+ });++ it('tolerates malformed scenes (peer-sync resilience) without throwing', () => {+ expect(() => secondaryCharacterPresenceSummary([+ null,+ { sequence: 1, povCharacter: 99, charactersPresent: 'not-an-array' },+ { sequence: 2, povCharacter: 'Mara', charactersPresent: [1, null, 'Reza'] },+ { sequence: 3, povCharacter: 'Mara', charactersPresent: ['Reza'] },+ ])).not.toThrow();+ const summary = secondaryCharacterPresenceSummary([+ { sequence: 2, povCharacter: 'Mara', charactersPresent: [1, null, 'Reza'] },+ { sequence: 3, povCharacter: 'Mara', charactersPresent: ['Reza'] },+ ]);+ expect(summary).toContain('Reza: present in 2 scenes');+ });+});++describe('character.secondary-arc — LLM check (#1585)', () => {+ const wholeCtx = (overrides = {}) => ({+ manuscript: '# Issue 1\n\nReza poured the coffee, said nothing, and left — as always.',+ config: { minScenes: 2, maxFindings: 12 },+ severityDefault: 'low',+ canon: { characters: [{ name: 'Reza', personality: 'stoic and quiet' }] },+ reverseOutline: [+ { sequence: 0, issueNumber: 1, heading: 'The diner', povCharacter: 'Mara', charactersPresent: ['Mara', 'Reza'] },+ { sequence: 1, issueNumber: 2, heading: 'The diner again', povCharacter: 'Mara', charactersPresent: ['Mara', 'Reza'] },+ ],+ planManuscriptChunks: async () => ['# Issue 1\n\nReza poured the coffee, said nothing, and left — as always.'],+ callStagedLLM: async () => ({ content: { findings: [] } }),+ ...overrides,+ });++ it('is registered as a series-scoped LLM check reading manuscript + outline + canon', () => {+ const check = getCheck(SECONDARY_ARC);+ expect(check.kind).toBe('llm');+ expect(check.scope).toBe('series');+ expect(check.category).toBe('arc');+ expect(check.severityDefault).toBe('low');+ expect(check.sources).toEqual(['manuscript', 'reverseOutline', 'canon']);+ expect(check.needsManuscript).toBe(true);+ });++ it('only runs when there is drafted prose to scan', () => {+ const check = getCheck(SECONDARY_ARC);+ expect(check.gate({ manuscript: '' })).toBe(false);+ expect(check.gate({ manuscript: '# Issue 1\n\nprose' })).toBeTruthy();+ });++ it('passes the manuscript, recurring secondary roster, and canon roster and forces the arc category', async () => {+ let seenVars = null;+ const ctx = wholeCtx({+ planManuscriptChunks: async (_stage, opts) => {+ expect(opts.context).toHaveProperty('secondaryCast');+ expect(opts.context).toHaveProperty('canonRoster');+ expect(opts.fixedOverheadTokens).toBeGreaterThan(0);+ return ['# Issue 1\n\nReza poured the coffee, said nothing, and left — as always.'];+ },+ callStagedLLM: async (_stage, vars) => {+ seenVars = vars;+ return { content: { findings: [{ severity: 'low', issueNumber: 2, location: 'Issue 2 — Reza — flat arc', problem: 'Reza never changes' }] } };+ },+ });+ const findings = await getCheck(SECONDARY_ARC).run(ctx);+ expect(seenVars.secondaryCast).toContain('Reza');+ expect(seenVars.canonRoster).toContain('Reza');+ expect(findings).toHaveLength(1);+ expect(findings[0].category).toBe('arc');+ expect(findings[0].location).toBe('Issue 2 — Reza — flat arc');+ });++ it('honors the minScenes config when building the secondary roster', async () => {+ let seenVars = null;+ const ctx = wholeCtx({+ config: { minScenes: 3, maxFindings: 12 },+ callStagedLLM: async (_stage, vars) => { seenVars = vars; return { content: { findings: [] } }; },+ });+ await getCheck(SECONDARY_ARC).run(ctx);+ // Reza appears in only 2 scenes → excluded at minScenes 3 → empty roster.+ expect(seenVars.secondaryCast).toBe('');+ });++ it('passes empty context vars when there is no outline or canon', async () => {+ let seenVars = null;+ const ctx = wholeCtx({+ canon: undefined,+ reverseOutline: undefined,+ callStagedLLM: async (_stage, vars) => { seenVars = vars; return { content: { findings: [] } }; },+ });+ await getCheck(SECONDARY_ARC).run(ctx);+ expect(seenVars.secondaryCast).toBe('');+ expect(seenVars.canonRoster).toBe('');+ });++ it('marks a single-chunk run as the final part so the flat-arc verdict is enabled', async () => {+ let seenVars = null;+ const ctx = wholeCtx({+ callStagedLLM: async (_stage, vars) => { seenVars = vars; return { content: { findings: [] } }; },+ });+ await getCheck(SECONDARY_ARC).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(SECONDARY_ARC).run(ctx);+ expect(finals).toEqual(['', '', 'true']);+ });+});+describe('declaredThemesSummary (#1317)', () => {it('returns an empty string when there are no themes', () => {expect(declaredThemesSummary(null)).toBe('');