Skip to content

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

feat: add character-consistency / unearned-personality-shift editorial check (#1582)

[._.]/ Adam Eivy6edee2a8e337
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 81586a6473..0ae577e64a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -51,6 +51,8 @@
- **[issue-1581] A new editorial check catches timeline and canon contradictions — a dead character who reappears alive, an age that contradicts the bible, an impossible chronology.** PortOS had no editorial check for internal contradictions against canon and the story's own timeline, so a character killed in issue 3 who walks back in alive in issue 6, an age the prose contradicts (the bible says 16, the page says "in her 30s"), or a journey that takes eight days but is dated to day two could slip through to the reader — the kind of mistake that's nearly impossible to catch by eye once an arc spans months of drafting. The new **Timeline / canon contradiction** check (`continuity.timeline-contradiction`) reconciles the stitched manuscript against the **continuity-bible facts ledger** (the ground-truth ages, dates & elapsed time, locations, and world rules already extracted by the continuity bible), the canon character facts (age, role, status, description), the reverse-outline scene ordering (for chronology), and the authored per-character arcs — flagging each contradiction with the two facts that conflict and a verbatim anchor. It runs across the whole manuscript — carrying each character's last-known state (alive/dead, age, location) forward between chunks so a death-then-resurrection that spans chapters is actually visible — and degrades to a prose-only scan when no canon or outline exists. It's a default-on series check that surfaces in the existing editorial-review UI and Series Autopilot like every other check, marking plot-breaking contradictions high-severity per finding. Its findings go stale (and re-run) when any source it reads drifts — including the continuity-bible ledger — via the new `continuityBible` editorial source. (`server/lib/editorial/checkRegistry.js`, `server/services/pipeline/editorial/checkRunner.js`, `data.reference/prompts/stages/pipeline-editorial-timeline-contradiction.md`, `scripts/migrations/129-editorial-timeline-contradiction-stage.js`)
+- **[issue-1582] A new editorial check catches unearned personality shifts — a reserved character who suddenly cracks jokes, a stated fear silently ignored, knowledge that appears with no on-page learning.** PortOS's `arc.transitions` check finds *change moments* but nothing flagged a change the story never *earns*: a guarded character trading easy banter a chapter later with no beat to motivate it, an established trait (a fear, an allergy, a skill) quietly contradicted, or a POV character who acts on information they were never shown learning. These read as author slips rather than growth and are hard to catch by eye once an arc spans months of drafting. The new **Character consistency** check (`character.consistency`) reconciles the stitched manuscript against the established canon character *traits* (personality, fixed traits, mannerisms, likes/dislikes, speech), the reverse-outline scene ordering (to spot a knowledge jump within a scene), and — crucially — the **authored per-character arcs**, so an intentional, earned transition the author recorded is *not* flagged. It runs across the whole manuscript, carrying each character's established temperament forward between chunks so a baseline set in an early chapter and an unearned shift in a later one are visible together, and degrades to a prose-only scan when no canon or outline exists. It's a default-on series check that surfaces in the existing editorial-review UI and Series Autopilot like every other check, marking trait contradictions that break a plot beat high-severity per finding. (`server/lib/editorial/checkRegistry.js`, `data.reference/prompts/stages/pipeline-editorial-character-consistency.md`, `scripts/migrations/130-editorial-character-consistency-stage.js`)
+
## 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.json
index 0cbdb4ca6e..671d1e26e8 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -597,6 +597,13 @@
"returnsJson": true,
"variables": []
},
+ "pipeline-editorial-character-consistency": {
+ "name": "Pipeline — Editorial Check: Character consistency (unearned personality shift)",
+ "description": "Editorial check (#1582): flags unearned characterization changes — a reserved character who suddenly cracks jokes with no arc beat, an established trait (fear, allergy, skill) silently contradicted, or POV-character knowledge that changes mid-scene without on-page learning. Reconciles the stitched manuscript against the established canon character traits, the reverse-outline scene ordering, and the authored per-character arcs so an intentional, earned transition is NOT flagged; degrades to a prose-only scan when no canon or outline exists. 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-character-consistency.md b/data.reference/prompts/stages/pipeline-editorial-character-consistency.md
new file mode 100644
index 0000000000..738f275d87
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-editorial-character-consistency.md
@@ -0,0 +1,113 @@
+# Pipeline — Editorial Check: Character consistency (unearned personality shift)
+
+You are a characterization editor doing a single focused pass for ONE concern:
+**unearned changes in who a character is**. Readers trust a character once the
+story establishes their temperament, voice, fears, and knowledge — and a shift
+that the story never earns (a reserved figure suddenly cracking jokes, a stated
+allergy ignored, a character who "just knows" something they were never told)
+reads as an author slip, not growth. Your job is to find shifts the prose does
+NOT earn — not to police every change a character is allowed to undergo.
+
+A genuine unearned shift is one of:
+
+- **personality / voice drift** — a character whose established temperament or
+ speech pattern flips with no on-page beat to motivate it (the curt, guarded
+ character trading easy banter a chapter later; the formal speaker suddenly
+ slangy) and no authored arc that records the change.
+- **trait contradiction** — an established fixed trait the prose silently breaks:
+ a stated fear the character now ignores without confronting it, an allergy or
+ physical limit contradicted, a skill they have or lack reversed off-screen.
+- **knowledge jump** — a POV or scene character who acts on information they were
+ never shown learning: knowing a name, a secret, or an outcome with no on-page
+ moment (dialogue, discovery, deduction) that delivers it.
+
+Do NOT flag: a change the prose EARNS on the page (a beat that motivates it, a
+revelation that delivers new knowledge); a transition the authored character arc
+records (intentional growth is the point of an arc, not an error); a momentary
+mood that is in-character; ordinary range a personality is allowed to have.
+
+{{#canonTraits}}
+## Established canon traits
+
+The story bible records these character traits. Treat them as the baseline a
+shift must be measured against — flag prose that moves a character off their
+recorded personality, fixed traits, mannerisms, or voice WITHOUT earning it.
+
+```
+{{canonTraits}}
+```
+{{/canonTraits}}
+
+{{#sceneMap}}
+## Scene segmentation
+
+The reverse outline below segments the manuscript into scenes in story order
+(with the recorded setting, POV character, and characters present). Use it to
+reason about what a character could plausibly know or perceive at each point —
+and to spot knowledge that appears before any scene delivers it.
+
+```
+{{sceneMap}}
+```
+{{/sceneMap}}
+
+{{#characterArcs}}
+## Authored character arcs
+
+The author has recorded these per-character arcs (start → end state). A change
+the arc records is INTENTIONAL — do NOT flag it as an unearned shift. Use the
+arcs to suppress earned transitions and focus only on changes the story never
+set up.
+
+```
+{{characterArcs}}
+```
+{{/characterArcs}}
+
+## Manuscript
+
+The manuscript is stitched from the drafted issues. Section headers attribute
+each chunk to an issue (e.g. `# Issue 3 — Title (prose)`). Use the issue number
+in each header to attribute every finding to its `issueNumber`.
+
+```
+{{manuscript}}
+```
+
+## Task
+
+Scan the manuscript for the three unearned-shift kinds above. For each genuine
+finding:
+
+1. Name the established trait/voice/knowledge baseline and where it was set (the
+ canon fact or the earlier passage), and the passage that breaks it.
+2. Confirm the change is NOT earned on the page and NOT recorded in an authored
+ arc — say briefly why it reads as unearned.
+3. Quote a short verbatim anchor (≤ 200 chars) at the contradicting passage.
+4. Set the `location` to the character + the shift kind — one of `personality`,
+ `trait`, `knowledge` — e.g. `Mara — personality` or `Joss — knowledge`.
+
+Severity: a trait contradiction or knowledge jump that breaks a plot beat is
+high; a small, easily-reconciled tonal wobble is low. If the characterization
+holds together, return an empty `findings` array — do not invent shifts where
+the character stays consistent or the change is clearly earned.
+
+## 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 — character + shift kind (e.g. 'Mara — personality' or 'Joss — knowledge')",
+ "problem": "1–3 sentences naming the established baseline, the passage that breaks it, and why the change is unearned",
+ "suggestion": "1–3 sentences proposing how to earn the change (add a motivating beat / on-page learning) or restore consistency",
+ "anchorQuote": "short verbatim quote at the contradicting passage (≤ 200 chars)"
+ }
+ ]
+}
+```
diff --git a/scripts/migrations/130-editorial-character-consistency-stage.js b/scripts/migrations/130-editorial-character-consistency-stage.js
new file mode 100644
index 0000000000..cacc33faaf
--- /dev/null
+++ b/scripts/migrations/130-editorial-character-consistency-stage.js
@@ -0,0 +1,75 @@
+/**
+ * Seed the `pipeline-editorial-character-consistency` stage into existing installs (#1582).
+ *
+ * Mirrors `129-editorial-timeline-contradiction-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 character-consistency stage
+ * unseeded and the `character.consistency` 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-character-consistency.md';
+const STAGE_KEY = 'pipeline-editorial-character-consistency';
+
+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-character-consistency prompt: already present`);
+ } else {
+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
+ if (!sampleExists) {
+ console.warn(`⚠️ pipeline-editorial-character-consistency: sample missing for ${FILENAME} — skipping copy`);
+ } else {
+ try {
+ await copyFile(samplePath, dataPath);
+ console.log(`✅ seeded ${FILENAME}`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-editorial-character-consistency: 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-character-consistency: 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-character-consistency stage-config: already present`);
+ return;
+ }
+ if (!sample?.stages?.[STAGE_KEY]) {
+ console.warn(`⚠️ pipeline-editorial-character-consistency: 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-character-consistency stage-config (${action}): 1 added`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-editorial-character-consistency: stage-config merge failed: ${err.message}`);
+ }
+ },
+};
diff --git a/scripts/migrations/130-editorial-character-consistency-stage.test.js b/scripts/migrations/130-editorial-character-consistency-stage.test.js
new file mode 100644
index 0000000000..63ed86df57
--- /dev/null
+++ b/scripts/migrations/130-editorial-character-consistency-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 './130-editorial-character-consistency-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 129) — no MD5 bookkeeping, so the
+// seed / no-clobber behavior is asserted directly.
+
+const FILENAME = 'pipeline-editorial-character-consistency.md';
+const STAGE_KEY = 'pipeline-editorial-character-consistency';
+const BODY = '# Character consistency (unearned personality shift)\n\nshipped body\n';
+
+describe('migration 130 — seed editorial-character-consistency 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-130-'));
+ 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.js
index 2896c92e4b..d98fc13381 100644
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@ -366,6 +366,64 @@ export function canonCharacterStatesSummary(canon) {
return `Canon character facts (the established bible — reconcile the prose against these):\n${rows.join('\n')}`;
}
+// Render each canon character's PERSONALITY-relevant traits into a compact text
+// block the character-consistency check (#1582) passes alongside the manuscript,
+// so the model can flag an UNEARNED shift: a reserved character suddenly cracking
+// jokes, an established fear/allergy silently contradicted, a voice that drifts
+// off the authored speech pattern. Distinct from `canonCharacterStatesSummary`
+// (age/role/status/described-as — the contradiction-of-FACTS grounding the
+// timeline check reads) and from `characterVoiceProfiles` (speech only): this is
+// the temperament/traits grounding. Pure + deterministic so it's unit-testable
+// and its token cost can be counted into the per-chunk overhead. Type-guarded
+// throughout (canon rides peer sync, so a hand-edited / older-peer character
+// could carry a non-string field a bare `.trim()` would throw on, and
+// mannerisms/likes/dislikes are commonly arrays). Reuses `characterNameTokens` so
+// name + aliases render with the same trim/de-dup the matcher uses. Returns ''
+// when no character carries both a usable name AND a renderable trait (the
+// prompt's `{{#canonTraits}}` section then renders nothing and the check reasons
+// from the prose alone).
+const CANON_TRAIT_FACT_CHARS = 240;
+export function canonCharacterTraitsSummary(canon) {
+ const chars = Array.isArray(canon?.characters) ? canon.characters : [];
+ const cleanStr = (v) => (typeof v === 'string' ? v.trim() : '');
+ // mannerisms / likes / dislikes are commonly arrays of short strings in the
+ // bible; render the first few as a comma list. Tolerates a plain string too.
+ const cleanList = (v) => {
+ if (typeof v === 'string') return v.trim();
+ if (!Array.isArray(v)) return '';
+ return v.map((x) => (typeof x === 'string' ? x.trim() : '')).filter(Boolean).slice(0, 5).join(', ');
+ };
+ const rows = [];
+ for (const c of chars) {
+ if (!c || typeof c !== 'object') continue;
+ // Require a real name — an alias-only row isn't a named character (mirrors
+ // canonCharacterStatesSummary). characterNameTokens returns the trimmed name
+ // first, followed by de-duped aliases.
+ if (typeof c.name !== 'string' || !c.name.trim()) continue;
+ const [name, ...aliases] = characterNameTokens(c);
+ const facts = [];
+ const personality = cleanStr(c.personality).slice(0, CANON_TRAIT_FACT_CHARS);
+ if (personality) facts.push(`personality: ${personality}`);
+ const specialTraits = cleanStr(c.specialTraits).slice(0, CANON_TRAIT_FACT_CHARS);
+ if (specialTraits) facts.push(`fixed traits: ${specialTraits}`);
+ const mannerisms = cleanList(c.mannerisms);
+ if (mannerisms) facts.push(`mannerisms: ${mannerisms}`);
+ const motivations = cleanStr(c.motivations).slice(0, CANON_TRAIT_FACT_CHARS);
+ if (motivations) facts.push(`motivations: ${motivations}`);
+ const likes = cleanList(c.likes);
+ if (likes) facts.push(`likes: ${likes}`);
+ const dislikes = cleanList(c.dislikes);
+ if (dislikes) facts.push(`dislikes: ${dislikes}`);
+ const speechPattern = cleanStr(c.speechPattern);
+ if (speechPattern) facts.push(`speech: ${speechPattern}`);
+ if (!facts.length) continue;
+ const who = aliases.length ? `${name} (also: ${aliases.join(', ')})` : name;
+ rows.push(`- ${who} — ${facts.join('; ')}`);
+ }
+ if (!rows.length) return '';
+ return `Canon character traits (the established bible — a shift away from these must be earned on the page):\n${rows.join('\n')}`;
+}
+
// Human-readable labels for the continuity-bible fact categories (#1305). Inlined
// (not imported from server/services/pipeline/continuityBible.js) to keep this
// registry PURE — that module pulls in I/O + an SSE runner. Mirrors its
@@ -443,6 +501,18 @@ export const PLOT_STRUCTURE_STAGE = 'pipeline-editorial-plot-structure';
// impossible chronology.
export const TIMELINE_CONTRADICTION_STAGE = 'pipeline-editorial-timeline-contradiction';
+// Stage name for the character-consistency / unearned-personality-shift LLM check
+// (#1582). Ships in data.reference/prompts/stages/ + stage-config.json (fresh
+// installs via setup-data.js) and migrates to existing installs via migration 130
+// (boot runs migrations but NOT setup-data, so the migration is required). Reads
+// the stitched manuscript plus the established canon character TRAITS (personality,
+// fixed traits, mannerisms, speech), the reverse-outline scene ordering, and the
+// authored per-character arcs — and flags a shift the prose never earns: a reserved
+// character cracking jokes with no beat, a fear/allergy silently contradicted, or
+// POV knowledge that changes mid-scene with no on-page learning. Reconciles against
+// the authored arcs so an intentional, earned transition is NOT flagged.
+export const CHARACTER_CONSISTENCY_STAGE = 'pipeline-editorial-character-consistency';
+
// 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
@@ -3023,6 +3093,78 @@ export const EDITORIAL_CHECKS = [
});
},
},
+ {
+ id: 'character.consistency',
+ sources: ['manuscript', 'canon', 'reverseOutline', 'series.characterArcs'],
+ label: 'Character consistency (unearned personality shift)',
+ description:
+ 'LLM scan for UNEARNED characterization changes: a reserved character who suddenly cracks jokes with no arc beat, an established trait silently contradicted (a stated fear, allergy, or skill the prose breaks), or POV-character knowledge that changes mid-scene without on-page learning. Reconciles the prose against the established canon character traits (personality, fixed traits, mannerisms, speech), the reverse-outline scene ordering, and the AUTHORED per-character arcs — so an intentional, earned transition is NOT flagged. Degrades to a prose-only scan when no canon or outline exists.',
+ scope: 'series',
+ kind: 'llm',
+ category: 'character',
+ // Fallback severity when the model omits one — 'medium' to match the sibling
+ // characterization/continuity LLM checks. The prompt directs the model to mark
+ // a flat trait-contradiction that breaks a plot beat 'high' per finding, so a
+ // genuinely-jarring shift still surfaces as high.
+ severityDefault: 'medium',
+ defaultEnabled: true,
+ // Reads the stitched manuscript corpus — so the runner only pays the
+ // section-collection I/O when a manuscript-consuming check is enabled.
+ needsManuscript: true,
+ configSchema: z.object({
+ // Cap findings per run so a long manuscript can't flood the review.
+ maxFindings: z.number().int().min(1).max(50).default(12),
+ }),
+ configFields: [
+ {
+ key: 'maxFindings',
+ label: 'Max findings per run',
+ type: 'number',
+ min: 1,
+ max: 50,
+ step: 1,
+ help: 'Cap findings so a long manuscript can not flood the review.',
+ },
+ ],
+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,
+ run: (ctx) => {
+ // All three blocks are fixed per-call overhead (re-sent on each chunk) and
+ // pure context: the canon traits give the established temperament/voice/
+ // fixed-trait baseline a shift must be measured against, the scene map gives
+ // the chronology to spot a knowledge-jump within a scene, and the authored
+ // arcs let the model SUPPRESS an earned transition (a character the author
+ // intends to change). The check degrades gracefully — no canon ⇒
+ // {{#canonTraits}} renders nothing; no outline ⇒ {{#sceneMap}} renders
+ // nothing; no authored arcs ⇒ {{#characterArcs}} renders nothing and the
+ // model reasons from the prose's own internal consistency.
+ const canonTraits = canonCharacterTraitsSummary(ctx.canon);
+ const sceneMap = sceneGroundingSummary(ctx.reverseOutline);
+ const characterArcs = renderCharacterArcsForPrompt(ctx.series?.characterArcs) || '';
+ return runManuscriptLlmCheck(ctx, {
+ stage: CHARACTER_CONSISTENCY_STAGE,
+ category: 'character',
+ // canonTraits + sceneMap grow with cast/scene count; characterArcs is
+ // bounded — so largest-first trimming absorbs the cut into those.
+ context: { canonTraits, sceneMap, characterArcs },
+ buildVars: (manuscript, _meta, c) => ({
+ manuscript,
+ canonTraits: c.canonTraits,
+ sceneMap: c.sceneMap,
+ characterArcs: c.characterArcs,
+ }),
+ // A personality shift is only visible against what came BEFORE — the
+ // reserved-character baseline lives in an early chunk and the unearned
+ // joke lands in a later one. The findings digest keeps prior findings in
+ // view so a later chunk doesn't re-flag, and the clean-setup digest rolls
+ // each character's established temperament forward so a later chunk can
+ // catch a trait that silently flips.
+ crossChunkDigest: true,
+ crossChunkSetup: true,
+ setupFocus:
+ 'For each named character, note their established temperament, voice, and fixed traits (how they speak, what they fear/avoid, what they know) plus any EARNED change the prose has already paid off. Carry these forward so a later chunk can tell an unearned shift (a reserved character suddenly joking, a stated fear ignored, knowledge appearing with no on-page learning) from a transition the story has legitimately set up.',
+ });
+ },
+ },
{
id: 'arc.transitions',
sources: ['manuscript', 'reverseOutline', 'series.characterArcs'],
diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.js
index 99610209bb..c7f2db7dc0 100644
--- a/server/lib/editorial/checkRegistry.test.js
+++ b/server/lib/editorial/checkRegistry.test.js
@@ -36,6 +36,7 @@ import {
declaredThemesSummary,
canonRosterNamesSummary,
canonCharacterStatesSummary,
+ canonCharacterTraitsSummary,
continuityLedgerSummary,
} from './checkRegistry.js';
@@ -52,6 +53,7 @@ const HEAD_HOPPING = 'pov.head-hopping';
const THEME_COHERENCE = 'theme.coherence';
const UNMODELED_NAMES = 'roster.unmodeled-names';
const TIMELINE_CONTRADICTION = 'continuity.timeline-contradiction';
+const CHARACTER_CONSISTENCY = 'character.consistency';
// A minimal valid stored custom-check definition.
const customDef = (over = {}) => ({
@@ -965,6 +967,115 @@ describe('canonCharacterStatesSummary (#1581)', () => {
});
});
+describe('character.consistency — LLM check (#1582)', () => {
+ const wholeCtx = (overrides = {}) => ({
+ manuscript: '# Issue 1\n\nMara said nothing, as always.',
+ config: { maxFindings: 12 },
+ severityDefault: 'medium',
+ series: {},
+ canon: { characters: [{ name: 'Mara', personality: 'reserved and guarded', specialTraits: 'deathly afraid of fire' }] },
+ reverseOutline: [{ sequence: 0, issueNumber: 1, heading: 'The watch', setting: 'a wall', charactersPresent: ['Mara'] }],
+ planManuscriptChunks: async () => ['# Issue 1\n\nMara said nothing, as always.'],
+ callStagedLLM: async () => ({ content: { findings: [] } }),
+ ...overrides,
+ });
+
+ it('is registered as a series-scoped LLM check reading manuscript + canon + outline + arcs', () => {
+ const check = getCheck(CHARACTER_CONSISTENCY);
+ expect(check.kind).toBe('llm');
+ expect(check.scope).toBe('series');
+ expect(check.category).toBe('character');
+ expect(check.severityDefault).toBe('medium');
+ expect(check.sources).toEqual(['manuscript', 'canon', 'reverseOutline', 'series.characterArcs']);
+ expect(check.needsManuscript).toBe(true);
+ });
+
+ it('only runs when there is drafted prose to scan', () => {
+ const check = getCheck(CHARACTER_CONSISTENCY);
+ expect(check.gate({ manuscript: '' })).toBe(false);
+ expect(check.gate({ manuscript: '# Issue 1\n\nprose' })).toBeTruthy();
+ });
+
+ it('passes the manuscript, canon traits, and scene map to the model and forces the character category', async () => {
+ let seenVars = null;
+ const ctx = wholeCtx({
+ planManuscriptChunks: async (_stage, opts) => {
+ // Canon traits + scene map + character arcs all ride as trimmable context.
+ expect(opts.context).toHaveProperty('canonTraits');
+ expect(opts.context).toHaveProperty('sceneMap');
+ expect(opts.context).toHaveProperty('characterArcs');
+ expect(opts.fixedOverheadTokens).toBeGreaterThan(0);
+ return ['# Issue 6\n\nMara cracked a joke, suddenly the life of the party.'];
+ },
+ callStagedLLM: async (_stage, vars) => {
+ seenVars = vars;
+ return { content: { findings: [{ severity: 'medium', issueNumber: 6, location: 'Mara — personality', problem: 'Mara is reserved in canon but jokes freely here with no earned beat' }] } };
+ },
+ });
+ const findings = await getCheck(CHARACTER_CONSISTENCY).run(ctx);
+ expect(seenVars.manuscript).toBe('# Issue 6\n\nMara cracked a joke, suddenly the life of the party.');
+ expect(seenVars.canonTraits).toContain('Mara');
+ expect(seenVars.canonTraits).toContain('personality: reserved and guarded');
+ expect(seenVars.sceneMap).toContain('Issue 1: The watch');
+ expect(findings).toHaveLength(1);
+ expect(findings[0].category).toBe('character');
+ expect(findings[0].location).toBe('Mara — personality');
+ });
+
+ it('passes empty context vars when the series has no canon or outline', async () => {
+ let seenVars = null;
+ const ctx = wholeCtx({
+ canon: undefined,
+ reverseOutline: undefined,
+ callStagedLLM: async (_stage, vars) => { seenVars = vars; return { content: { findings: [] } }; },
+ });
+ await getCheck(CHARACTER_CONSISTENCY).run(ctx);
+ expect(seenVars.canonTraits).toBe('');
+ expect(seenVars.sceneMap).toBe('');
+ expect(seenVars.characterArcs).toBe('');
+ });
+});
+
+describe('canonCharacterTraitsSummary (#1582)', () => {
+ it('returns an empty string when there are no characters or no renderable traits', () => {
+ expect(canonCharacterTraitsSummary(null)).toBe('');
+ expect(canonCharacterTraitsSummary(undefined)).toBe('');
+ expect(canonCharacterTraitsSummary({ characters: [] })).toBe('');
+ // A named character with no trait-relevant field renders nothing (age/role/status
+ // are facts, not traits — they belong to canonCharacterStatesSummary).
+ expect(canonCharacterTraitsSummary({ characters: [{ name: 'Joss', age: 40, role: 'lead' }] })).toBe('');
+ // An alias-only row (no name) is skipped.
+ expect(canonCharacterTraitsSummary({ characters: [{ aliases: ['x'], personality: 'kind' }] })).toBe('');
+ });
+
+ it('renders each character with name + aliases and the present traits', () => {
+ const out = canonCharacterTraitsSummary({ characters: [
+ { name: 'Mara', aliases: ['The Captain'], personality: 'reserved and guarded', specialTraits: 'afraid of fire', speechPattern: 'clipped, formal' },
+ { name: 'Joss', mannerisms: ['taps the table', 'never sits still'], likes: ['chess'], dislikes: ['small talk'] },
+ ] });
+ expect(out).toContain('Canon character traits');
+ expect(out).toContain('- Mara (also: The Captain) — personality: reserved and guarded; fixed traits: afraid of fire; speech: clipped, formal');
+ expect(out).toContain('- Joss — mannerisms: taps the table, never sits still; likes: chess; dislikes: small talk');
+ });
+
+ it('renders array OR string list fields and caps the list length', () => {
+ const out = canonCharacterTraitsSummary({ characters: [
+ { name: 'A', mannerisms: 'hums constantly' },
+ { name: 'B', likes: ['a', 'b', 'c', 'd', 'e', 'f', 'g'] },
+ ] });
+ expect(out).toContain('- A — mannerisms: hums constantly');
+ // first five only
+ expect(out).toContain('- B — likes: a, b, c, d, e');
+ expect(out).not.toContain('a, b, c, d, e, f');
+ });
+
+ it('is type-guarded against hand-edited / older-peer rows', () => {
+ expect(() => canonCharacterTraitsSummary({ characters: [null, 'nope', { name: 'C', personality: 5, mannerisms: {} }] })).not.toThrow();
+ // personality is a non-string and mannerisms is a non-array object → no traits → C drops out.
+ expect(canonCharacterTraitsSummary({ characters: [{ name: 'C', personality: 5, mannerisms: {} }] })).toBe('');
+ });
+});
+
describe('theme.coherence — LLM check (#1317)', () => {
const wholeCtx = (overrides = {}) => ({
manuscript: '# Issue 1\n\nShe chose loyalty, and it cost her everything.',