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 timeline / canon contradiction editorial check (#1581)

Adam Eivy1cddafa328f7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index b70fa62848..8e86321f3e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -47,6 +47,10 @@
- **[issue-1511] Per-issue prose and comic-script generation now sees only the characters that issue involves.** Generating an issue used to load the entire series character bible into every prose and comic-script prompt — on a large-cast series that's tens of thousands of tokens of character detail (including one-off bit players from unrelated issues) re-sent on every issue and every stage. Generation now sends full character records only for the cast named in that issue's beats, synopsis, and source material, with a compact one-line roster of everyone else kept for continuity. This sharply cuts token cost on big-cast series and, on context-bounded providers, leaves more room for the actual draft. The series' lead/recurring characters stay in context for every issue, so the core cast is never dropped — generation just stops carrying the full record of every bit player from unrelated issues.
- **[issue-1529] A character whose name is a common word (Will, May, Grace) is no longer pulled into a prompt by an incidental word.** When scoping an issue's character bible, an ordinary phrase like "the team **will** regroup" could be mistaken for naming a cast member called "Will" — incidentally scoping the prompt down to that one character. A single-word character name now only counts as named when it appears capitalized as a proper noun ("Will entered"), so common-word names match the same way every other name does. Multi-word names and nicknames are unaffected.
+## Editorial checks
+
+- **[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 established 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. (`server/lib/editorial/checkRegistry.js`, `data.reference/prompts/stages/pipeline-editorial-timeline-contradiction.md`, `scripts/migrations/129-editorial-timeline-contradiction-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 e3cc7041e7..0cbdb4ca6e 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -590,6 +590,13 @@
"returnsJson": true,
"variables": []
},
+ "pipeline-editorial-timeline-contradiction": {
+ "name": "Pipeline — Editorial Check: Timeline / canon contradiction",
+ "description": "Editorial check (#1581): scans for internal contradictions against canon and chronology — a character who dies and reappears alive without explanation, an age contradiction (the bible says 16, the prose says 'in her 30s'), or an impossible timeline. Reconciles the stitched manuscript against the established canon character facts, the reverse-outline scene ordering, and the authored per-character arcs; 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-timeline-contradiction.md b/data.reference/prompts/stages/pipeline-editorial-timeline-contradiction.md
new file mode 100644
index 0000000000..7036677903
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-editorial-timeline-contradiction.md
@@ -0,0 +1,109 @@
+# Pipeline — Editorial Check: Timeline / canon contradiction
+
+You are a continuity editor doing a single focused pass for ONE concern:
+**internal contradictions against canon and chronology**. Serialized work lives
+or dies on consistency — a reader who catches a dead character walking around, an
+age that swings a decade, or a journey that takes both two days and two weeks
+loses trust in the whole story. Your job is to find genuine contradictions, not
+to police style.
+
+A genuine contradiction is one of:
+
+- **resurrection / status** — a character established as dead (or gone, or
+ permanently changed) who reappears in their old state with no in-story
+ explanation.
+- **age / identity** — a character's stated or implied age, identity, or fixed
+ trait contradicting the canon bible or an earlier passage (the bible says 16,
+ the prose calls her "a woman in her thirties").
+- **chronology** — an impossible timeline: an event dated or sequenced in a way
+ the established elapsed time cannot support (a journey of eight days completed
+ by day two), or two events that cannot both be true in the given order.
+
+Do NOT flag: deliberate, in-story explanations (a resurrection the plot
+accounts for, a flashback clearly marked as such, an unreliable narrator the
+story signals); ordinary changes a character is allowed to undergo; a fact the
+prose never actually contradicts.
+
+{{#canonStates}}
+## Established canon facts
+
+The story bible records these character facts. Treat them as the ground truth the
+prose must stay consistent with — flag a passage that contradicts one (age,
+role, status, or a fixed described trait).
+
+```
+{{canonStates}}
+```
+{{/canonStates}}
+
+{{#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 chronology — who is present where, and in what sequence — when
+judging whether the timeline holds.
+
+```
+{{sceneMap}}
+```
+{{/sceneMap}}
+
+{{#characterArcs}}
+## Authored character arcs
+
+The author has recorded these per-character arcs (start → end state). A
+character's intended state at a point in the story is a consistency anchor — flag
+prose that contradicts the recorded start or end state without earning the change.
+
+```
+{{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 contradiction kinds above. For each genuine
+contradiction:
+
+1. Name the two facts that conflict and where each appears (the canon fact or the
+ earlier passage, and the contradicting passage).
+2. Quote a short verbatim anchor (≤ 200 chars) at the contradicting passage.
+3. Set the `location` to the character or event + the contradiction kind — one of
+ `resurrection`, `age`, `identity`, `chronology` — e.g.
+ `Mara — resurrection` or `the crossing — chronology`.
+
+Severity: a resurrection or an impossible timeline that breaks the plot is high;
+a minor, easily-reconciled age slip is low. If the manuscript is internally
+consistent, return an empty `findings` array — do not invent contradictions where
+the story holds together.
+
+## 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 — subject + contradiction kind (e.g. 'Mara — resurrection' or 'the crossing — chronology')",
+ "problem": "1–3 sentences naming the two facts that conflict and why it matters",
+ "suggestion": "1–3 sentences proposing how to reconcile or explain the contradiction",
+ "anchorQuote": "short verbatim quote at the contradicting passage (≤ 200 chars)"
+ }
+ ]
+}
+```
diff --git a/scripts/migrations/129-editorial-timeline-contradiction-stage.js b/scripts/migrations/129-editorial-timeline-contradiction-stage.js
new file mode 100644
index 0000000000..8dd401978c
--- /dev/null
+++ b/scripts/migrations/129-editorial-timeline-contradiction-stage.js
@@ -0,0 +1,75 @@
+/**
+ * Seed the `pipeline-editorial-timeline-contradiction` stage into existing installs (#1581).
+ *
+ * Mirrors `109-editorial-arc-transitions-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 timeline-contradiction stage
+ * unseeded and the `continuity.timeline-contradiction` 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-timeline-contradiction.md';
+const STAGE_KEY = 'pipeline-editorial-timeline-contradiction';
+
+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-timeline-contradiction prompt: already present`);
+ } else {
+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
+ if (!sampleExists) {
+ console.warn(`⚠️ pipeline-editorial-timeline-contradiction: sample missing for ${FILENAME} — skipping copy`);
+ } else {
+ try {
+ await copyFile(samplePath, dataPath);
+ console.log(`✅ seeded ${FILENAME}`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-editorial-timeline-contradiction: 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-timeline-contradiction: 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-timeline-contradiction stage-config: already present`);
+ return;
+ }
+ if (!sample?.stages?.[STAGE_KEY]) {
+ console.warn(`⚠️ pipeline-editorial-timeline-contradiction: 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-timeline-contradiction stage-config (${action}): 1 added`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-editorial-timeline-contradiction: stage-config merge failed: ${err.message}`);
+ }
+ },
+};
diff --git a/scripts/migrations/129-editorial-timeline-contradiction-stage.test.js b/scripts/migrations/129-editorial-timeline-contradiction-stage.test.js
new file mode 100644
index 0000000000..34b289d69f
--- /dev/null
+++ b/scripts/migrations/129-editorial-timeline-contradiction-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 './129-editorial-timeline-contradiction-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 109) — no MD5 bookkeeping, so the
+// seed / no-clobber behavior is asserted directly.
+
+const FILENAME = 'pipeline-editorial-timeline-contradiction.md';
+const STAGE_KEY = 'pipeline-editorial-timeline-contradiction';
+const BODY = '# Timeline / canon contradiction\n\nshipped body\n';
+
+describe('migration 129 — seed editorial-timeline-contradiction 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-129-'));
+ 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 89c53a997f..675373f4a3 100644
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@ -313,6 +313,50 @@ export function characterVoiceProfiles(canon) {
return `Authored character voices (canon speechPattern / speechAccent):\n${lines.join('\n')}`;
}
+// Render each canon character's contradiction-relevant FACTS into a compact text
+// block the timeline / canon-contradiction check (#1581) passes alongside the
+// manuscript, so the model can reconcile the prose against the established bible:
+// a character the bible records at age 16 who reads "in her 30s" on the page, a
+// role/status the prose contradicts, or a description the prose breaks. 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 `age` is commonly stored as a number). 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 fact (the prompt's `{{#canonStates}}` section then renders nothing
+// and the check reasons from the prose + scene map alone).
+const CANON_STATE_FACT_CHARS = 240;
+export function canonCharacterStatesSummary(canon) {
+ const chars = Array.isArray(canon?.characters) ? canon.characters : [];
+ const cleanStr = (v) => (typeof v === 'string' ? v.trim() : '');
+ 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
+ // canonRosterNamesSummary, which skips nameless rows). characterNameTokens then
+ // 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 = [];
+ // `age` is often a number in the bible — accept a finite number or a non-empty string.
+ const age = typeof c.age === 'number' && Number.isFinite(c.age) ? String(c.age) : cleanStr(c.age);
+ if (age) facts.push(`age ${age}`);
+ const role = cleanStr(c.role);
+ if (role) facts.push(`role: ${role}`);
+ const status = cleanStr(c.status);
+ if (status) facts.push(`status: ${status}`);
+ // physicalDescription is the richer bible field; fall back to a generic description.
+ const description = (cleanStr(c.physicalDescription) || cleanStr(c.description)).slice(0, CANON_STATE_FACT_CHARS);
+ if (description) facts.push(`described as: ${description}`);
+ 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 facts (the established bible — reconcile the prose against these):\n${rows.join('\n')}`;
+}
+
// Stage name for the plot-structure & momentum LLM check (#1310). Ships in
// data.reference/prompts/stages/ + stage-config.json (fresh installs via
// setup-data.js) and migrates to existing installs via migration 111 (boot runs
@@ -323,6 +367,16 @@ export function characterVoiceProfiles(canon) {
// subplots reconciled against the tagged plotlines.
export const PLOT_STRUCTURE_STAGE = 'pipeline-editorial-plot-structure';
+// Stage name for the timeline / canon-contradiction LLM check (#1581). Ships in
+// data.reference/prompts/stages/ + stage-config.json (fresh installs via
+// setup-data.js) and migrates to existing installs via migration 129 (boot runs
+// migrations but NOT setup-data, so the migration is required). Reads the stitched
+// manuscript plus the established canon character facts, the reverse-outline scene
+// ordering, and the authored per-character arcs to surface internal contradictions
+// — a dead character who reappears alive, an age that contradicts the bible, or an
+// impossible chronology.
+export const TIMELINE_CONTRADICTION_STAGE = 'pipeline-editorial-timeline-contradiction';
+
// 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
@@ -2829,6 +2883,76 @@ export const EDITORIAL_CHECKS = [
});
},
},
+ {
+ id: 'continuity.timeline-contradiction',
+ sources: ['manuscript', 'canon', 'reverseOutline', 'series.characterArcs'],
+ label: 'Timeline / canon contradiction',
+ description:
+ 'LLM scan for internal contradictions against canon and chronology: a character who dies and later reappears alive without explanation, an age contradiction (the bible says 16, the prose says "in her 30s"), or an impossible timeline (an event dated day 2 that characters needed 8 days to reach). Reconciles the prose against the established canon character facts, the reverse-outline scene ordering, and the authored per-character arc start/end states; degrades to a prose-only scan when no canon or outline exists.',
+ scope: 'series',
+ kind: 'llm',
+ category: 'continuity',
+ // Fallback severity when the model omits one — kept 'medium' to match the
+ // sibling continuity/narrative LLM checks. The prompt directs the model to
+ // mark a plot-breaking resurrection or impossible timeline 'high' per finding,
+ // so genuinely-fatal contradictions still surface 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 facts let the model catch age/status/identity
+ // contradictions, the scene map gives the chronology to catch impossible
+ // timelines and resurrection-without-explanation, and the authored arcs give
+ // each character's intended start → end state. The check degrades
+ // gracefully — no canon ⇒ {{#canonStates}} renders nothing; no outline ⇒
+ // {{#sceneMap}} renders nothing; no authored arcs ⇒ {{#characterArcs}}
+ // renders nothing and the model reasons from the prose alone.
+ const canonStates = canonCharacterStatesSummary(ctx.canon);
+ const sceneMap = sceneGroundingSummary(ctx.reverseOutline);
+ const characterArcs = renderCharacterArcsForPrompt(ctx.series?.characterArcs) || '';
+ return runManuscriptLlmCheck(ctx, {
+ stage: TIMELINE_CONTRADICTION_STAGE,
+ category: 'continuity',
+ // canonStates + sceneMap grow with cast/scene count; characterArcs is
+ // bounded — so largest-first trimming absorbs the cut into those.
+ context: { canonStates, sceneMap, characterArcs },
+ buildVars: (manuscript, _meta, c) => ({
+ manuscript,
+ canonStates: c.canonStates,
+ sceneMap: c.sceneMap,
+ characterArcs: c.characterArcs,
+ }),
+ // A contradiction spans the manuscript — a death in an early chunk and a
+ // resurrection in a later one are only visible together. 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 last-known state
+ // forward so a later chunk can catch a state that silently flips.
+ crossChunkDigest: true,
+ crossChunkSetup: true,
+ setupFocus:
+ 'For each named character, note their last-established state a later part must stay consistent with: alive or dead (and how/when), stated or implied age, and current location — plus any dated events and the elapsed time between them. Carry these forward so a later chunk can catch a character who reappears alive after dying, an age that contradicts an earlier one, or an impossible chronology.',
+ });
+ },
+ },
{
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 09b823d066..5ed4551765 100644
--- a/server/lib/editorial/checkRegistry.test.js
+++ b/server/lib/editorial/checkRegistry.test.js
@@ -35,6 +35,7 @@ import {
scenePovSummary,
declaredThemesSummary,
canonRosterNamesSummary,
+ canonCharacterStatesSummary,
} from './checkRegistry.js';
const NAMING = 'naming.dissimilar-names';
@@ -49,6 +50,7 @@ const PLOT_STRUCTURE = 'plot.structure-momentum';
const HEAD_HOPPING = 'pov.head-hopping';
const THEME_COHERENCE = 'theme.coherence';
const UNMODELED_NAMES = 'roster.unmodeled-names';
+const TIMELINE_CONTRADICTION = 'continuity.timeline-contradiction';
// A minimal valid stored custom-check definition.
const customDef = (over = {}) => ({
@@ -822,6 +824,113 @@ describe('plotlineCoverageSummary (#1310)', () => {
});
});
+describe('continuity.timeline-contradiction — LLM check (#1581)', () => {
+ const wholeCtx = (overrides = {}) => ({
+ manuscript: '# Issue 1\n\nMara died on the bridge.',
+ config: { maxFindings: 12 },
+ severityDefault: 'medium',
+ series: {},
+ canon: { characters: [{ name: 'Mara', age: 16, status: 'deceased after Issue 3' }] },
+ reverseOutline: [{ sequence: 0, issueNumber: 1, heading: 'The bridge', setting: 'a bridge', charactersPresent: ['Mara'] }],
+ planManuscriptChunks: async () => ['# Issue 1\n\nMara died on the bridge.'],
+ callStagedLLM: async () => ({ content: { findings: [] } }),
+ ...overrides,
+ });
+
+ it('is registered as a series-scoped LLM check reading manuscript + canon + outline + arcs', () => {
+ const check = getCheck(TIMELINE_CONTRADICTION);
+ expect(check.kind).toBe('llm');
+ expect(check.scope).toBe('series');
+ expect(check.category).toBe('continuity');
+ 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(TIMELINE_CONTRADICTION);
+ expect(check.gate({ manuscript: '' })).toBe(false);
+ expect(check.gate({ manuscript: '# Issue 1\n\nprose' })).toBeTruthy();
+ });
+
+ it('passes the manuscript, canon facts, and scene map to the model and forces the continuity category', async () => {
+ let seenVars = null;
+ const ctx = wholeCtx({
+ planManuscriptChunks: async (_stage, opts) => {
+ // Canon states + scene map + character arcs all ride as trimmable context.
+ expect(opts.context).toHaveProperty('canonStates');
+ expect(opts.context).toHaveProperty('sceneMap');
+ expect(opts.context).toHaveProperty('characterArcs');
+ expect(opts.fixedOverheadTokens).toBeGreaterThan(0);
+ return ['# Issue 6\n\nMara walked back into the room, very much alive.'];
+ },
+ callStagedLLM: async (_stage, vars) => {
+ seenVars = vars;
+ return { content: { findings: [{ severity: 'high', issueNumber: 6, location: 'Mara — resurrection', problem: 'Mara died in Issue 3 but is alive here' }] } };
+ },
+ });
+ const findings = await getCheck(TIMELINE_CONTRADICTION).run(ctx);
+ expect(seenVars.manuscript).toBe('# Issue 6\n\nMara walked back into the room, very much alive.');
+ expect(seenVars.canonStates).toContain('Mara');
+ expect(seenVars.canonStates).toContain('age 16');
+ expect(seenVars.sceneMap).toContain('Issue 1: The bridge');
+ expect(findings).toHaveLength(1);
+ expect(findings[0].category).toBe('continuity');
+ expect(findings[0].location).toBe('Mara — resurrection');
+ });
+
+ 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(TIMELINE_CONTRADICTION).run(ctx);
+ expect(seenVars.canonStates).toBe('');
+ expect(seenVars.sceneMap).toBe('');
+ expect(seenVars.characterArcs).toBe('');
+ });
+});
+
+describe('canonCharacterStatesSummary (#1581)', () => {
+ it('returns an empty string when there are no characters or no renderable facts', () => {
+ expect(canonCharacterStatesSummary(null)).toBe('');
+ expect(canonCharacterStatesSummary(undefined)).toBe('');
+ expect(canonCharacterStatesSummary({ characters: [] })).toBe('');
+ // A named character with no contradiction-relevant fact renders nothing.
+ expect(canonCharacterStatesSummary({ characters: [{ name: 'Joss' }] })).toBe('');
+ // An alias-only row (no name) is skipped.
+ expect(canonCharacterStatesSummary({ characters: [{ aliases: ['x'], age: 40 }] })).toBe('');
+ });
+
+ it('renders each character with name + aliases and the present facts', () => {
+ const out = canonCharacterStatesSummary({ characters: [
+ { name: 'Mara', aliases: ['The Captain'], age: 16, status: 'deceased after Issue 3', role: 'protagonist' },
+ { name: 'Joss', description: 'a tall man with a scar' },
+ ] });
+ expect(out).toContain('Canon character facts');
+ expect(out).toContain('- Mara (also: The Captain) — age 16; role: protagonist; status: deceased after Issue 3');
+ expect(out).toContain('- Joss — described as: a tall man with a scar');
+ });
+
+ it('accepts a numeric or string age and prefers physicalDescription over description', () => {
+ const out = canonCharacterStatesSummary({ characters: [
+ { name: 'A', age: '30s' },
+ { name: 'B', physicalDescription: 'rich', description: 'poor' },
+ ] });
+ expect(out).toContain('- A — age 30s');
+ expect(out).toContain('- B — described as: rich');
+ expect(out).not.toContain('poor');
+ });
+
+ it('is type-guarded against hand-edited / older-peer rows', () => {
+ expect(() => canonCharacterStatesSummary({ characters: [null, 'nope', { name: 'C', role: 5, age: {} }] })).not.toThrow();
+ // role is a non-string and age is a non-finite object → no facts → C drops out.
+ expect(canonCharacterStatesSummary({ characters: [{ name: 'C', role: 5, age: {} }] })).toBe('');
+ });
+});
+
describe('theme.coherence — LLM check (#1317)', () => {
const wholeCtx = (overrides = {}) => ({
manuscript: '# Issue 1\n\nShe chose loyalty, and it cost her everything.',