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: editorial check for real-world fact accuracy (opt-in, fact-grounded series) (#1588)

[._.]/ Adam Eivyfe02b65ee4de
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index cb442bbc8c..f2a1a6b269 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -63,6 +63,8 @@
- **[issue-1586] A new editorial check catches narrator-voice whiplash — narration that's witty in issue 1, grim in issue 3, then witty again in issue 5.** The existing `dialogue.voice-distinctiveness` check guards each *character's* dialogue voice, but nothing watched the *narrator's* voice across a series — so the storytelling tone could lurch from issue to issue (a wry, ironic narrator turning flat and clinical, a spare hard-boiled voice going lush and lyrical) with no one flagging the inconsistency, even though voice consistency is part of the promise to the reader. The new **Narrative voice / tone consistency** check (`style.voice-consistency`) fingerprints each issue's narrative tone — diction, register, humor, emotional temperature, sentence rhythm — and flags two problems: a *cross-issue tonal shift* the story never earns, and *drift from the series style guide's intended voice* (the declared `tone` words) when one is set. It reads the stitched manuscript with the style guide's intended tone, deliberately ignoring a purposeful modulation the events justify (a grim chapter because the plot took a grim turn) and judging the narration only, not character dialogue. Because the comparison spans issues, it carries each issue's tone fingerprint forward between manuscript chunks, so a later issue's narration is judged against the voice the series established earlier; it degrades to a pure cross-issue consistency scan when no style guide tone is declared. It's a default-on series check that surfaces in the existing editorial-review UI and Series Autopilot like every other check, marking a sharp, unexplained whiplash medium-severity. (`server/lib/editorial/checkRegistry.js`, `data.reference/prompts/stages/pipeline-editorial-voice-consistency.md`, `scripts/migrations/134-editorial-voice-consistency-stage.js`)
+- **[issue-1588] A new opt-in editorial check catches contradictions to real-world facts — Paris placed in Germany, an anachronistic technology, a physiologically impossible feat.** Distinct from the internal timeline/canon check (#1581), nothing reconciled grounded fiction against *external* truth, so a checkable howler in a historical or hard-SF series — a city in the wrong country, an event dated before the war it belongs to, a survivable injury that isn't — could ship and quietly torch the story's credibility. The new **Research / fact accuracy** check (`research.fact-accuracy`) scans the stitched manuscript against an **author-supplied fact reference** and flags geography, history/chronology, and science/physiology claims that contradict it. It is deliberately **opt-in and gated**: it runs only when a series is marked **fact-critical** *and* a non-empty fact reference is supplied, so it never second-guesses deliberate invention in pure fantasy. A new **Fact accuracy** section in the series bible (Pipeline → series) carries the toggle + reference textarea; the reference is a fingerprinted editorial source (`series.factReference`), so editing it re-runs the check, and findings surface in the existing editorial-review UI and Series Autopilot under a new **Fact accuracy** category. Both new series fields (`factCritical`, `factReference`) are wire-gated (pipelineSeries schema v7) so an older federated peer can't strip-then-LWW the loss. (`server/lib/editorial/checkRegistry.js`, `server/services/pipeline/series.js`, `client/src/pages/PipelineSeries.jsx`, `data.reference/prompts/stages/pipeline-editorial-fact-accuracy.md`, `scripts/migrations/135-editorial-fact-accuracy-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/client/src/components/pipeline/manuscript/constants.js b/client/src/components/pipeline/manuscript/constants.js
index 07aec3cf3f..a8c618ca14 100644
--- a/client/src/components/pipeline/manuscript/constants.js
+++ b/client/src/components/pipeline/manuscript/constants.js
@@ -46,6 +46,10 @@ export const CATEGORY_LABEL = {
casting: 'Casting',
pacing: 'Pacing',
continuity: 'Continuity',
+ // Real-world fact-accuracy findings (#1588): prose claims that contradict an
+ // author-supplied fact reference, from the opt-in research.fact-accuracy check.
+ // Distinct from `continuity` (internal contradiction) — this is external truth.
+ accuracy: 'Fact accuracy',
style: 'Style',
exposition: 'Exposition',
// Comic lettering-density findings (#1313): over-stuffed balloons/panels/pages
diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsx
index bef0b87bdd..b590de69dd 100644
--- a/client/src/pages/PipelineSeries.jsx
+++ b/client/src/pages/PipelineSeries.jsx
@@ -50,7 +50,8 @@ const STYLE_OVERRIDE_MODE_TABS = [
// empty-value defaults the server expects for the optional ones. Module-level
// constants so the `useArcCanvasSync` callbacks keep a stable identity.
const ARC_FLUSH_FIELDS = [
- 'name', 'logline', 'premise', 'styleNotes', 'styleGuide', 'titleLogo', 'author', 'authorId',
+ 'name', 'logline', 'premise', 'styleNotes', 'factCritical', 'factReference', 'styleGuide',
+ 'titleLogo', 'author', 'authorId',
'stylePromptOverride', 'stylePromptOverrideMode', 'issueCountTarget', 'universeId', 'characterArcs',
];
const ARC_PAYLOAD_DEFAULTS = {
@@ -59,6 +60,10 @@ const ARC_PAYLOAD_DEFAULTS = {
authorId: null,
stylePromptOverride: '',
stylePromptOverrideMode: STYLE_OVERRIDE_MODE_DEFAULT,
+ // Fact-checking opt-in + author fact reference (#1588). false / '' are the
+ // server-sanitizer defaults for "not fact-critical" / "no reference".
+ factCritical: false,
+ factReference: '',
// Structured house style — null means "no style guide", which the server
// sanitizer also produces from an all-empty guide.
styleGuide: null,
@@ -387,6 +392,8 @@ function BibleSidebar({ series, universes, patchSeries, onSeriesUpdate, onFlushP
<StyleGuideSection series={series} patchSeries={patchSeries} />
+ <FactReferenceSection series={series} patchSeries={patchSeries} />
+
<CharacterArcsSection series={series} patchSeries={patchSeries} />
<div className="block">
@@ -588,6 +595,50 @@ const TRANSITION_KIND_OPTIONS = [
['sacrifice', 'Sacrifice'],
];
+// Fact-checking opt-in + author fact reference (#1588). When the series is flagged
+// fact-critical AND a non-empty reference is supplied, the gated research.fact-accuracy
+// editorial check reconciles the prose against these documented real-world facts.
+// Both fields persist on Save (factCritical / factReference are in ARC_FLUSH_FIELDS).
+// The toggle is htmlFor/id paired; the textarea is only meaningful (and shown
+// prominently) once the toggle is on, so it stays collapsed for pure-fantasy series.
+function FactReferenceSection({ series, patchSeries }) {
+ const factCritical = series.factCritical === true;
+ return (
+ <div className="block">
+ <h3 className="text-xs uppercase tracking-wider text-gray-500 mb-2">Fact accuracy (grounded series)</h3>
+ <label htmlFor="fact-critical" className="flex items-start gap-2 cursor-pointer mb-2">
+ <input
+ id="fact-critical"
+ type="checkbox"
+ checked={factCritical}
+ onChange={(e) => patchSeries({ factCritical: e.target.checked })}
+ className="mt-0.5 accent-port-accent"
+ />
+ <span className="text-xs text-gray-300">
+ Fact-critical series
+ <span className="block text-[11px] text-gray-500">
+ Enable the real-world fact-accuracy editorial check. Leave off for pure fantasy, where the check would second-guess deliberate invention.
+ </span>
+ </span>
+ </label>
+ {factCritical && (
+ <label htmlFor="fact-reference" className="block">
+ <span className="block text-xs uppercase tracking-wider text-gray-500 mb-1">Fact reference (real-world ground truth)</span>
+ <textarea
+ id="fact-reference"
+ value={series.factReference || ''}
+ onChange={(e) => patchSeries({ factReference: e.target.value })}
+ rows={5}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
+ maxLength={8000}
+ placeholder="Documented real-world facts the prose must respect: geography, dates, technology timelines, physical/physiological limits. The fact-accuracy check flags prose claims that contradict what you write here."
+ />
+ </label>
+ )}
+ </div>
+ );
+}
+
// Per-character story arcs (#1293). Authored want/need, start → end state, and
// explicit transition beats, edited into local series state via patchSeries and
// persisted on Save (characterArcs is in ARC_FLUSH_FIELDS). The server sanitizer
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index 04c47ea04e..9864935755 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -597,6 +597,13 @@
"returnsJson": true,
"variables": []
},
+ "pipeline-editorial-fact-accuracy": {
+ "name": "Pipeline — Editorial Check: Research / fact accuracy",
+ "description": "Editorial check (#1588): scans grounded fiction for contradictions to real-world facts the author has documented — a city placed in the wrong country, an anachronistic event or technology, a physiologically impossible feat. Reconciles the stitched manuscript against the author-supplied fact reference (series.factReference); distinct from the internal timeline/canon-contradiction check. Opt-in and gated on the per-series fact-critical flag so it never fires on pure fantasy. Returns issue-anchored findings.",
+ "model": "default",
+ "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.",
diff --git a/data.reference/prompts/stages/pipeline-editorial-fact-accuracy.md b/data.reference/prompts/stages/pipeline-editorial-fact-accuracy.md
new file mode 100644
index 0000000000..c9dea4f767
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-editorial-fact-accuracy.md
@@ -0,0 +1,87 @@
+# Pipeline — Editorial Check: Research / fact accuracy
+
+You are a research editor doing a single focused pass for ONE concern:
+**contradictions to real-world facts the author has documented**. Grounded fiction
+— historical, hard-SF, technothriller, anything that leans on the credibility of
+the real world — loses the reader the moment it gets a checkable fact wrong: a city
+in the wrong country, a battle dated before the war it belongs to, a drug with an
+effect it cannot have, a feat the human body cannot perform.
+
+This is NOT a check for internal contradictions (a character who dies and reappears,
+an inconsistent timeline within the story) — a separate pass owns that. Your job is
+to reconcile the prose against the EXTERNAL fact reference below: where the story
+asserts something about the real world that the reference says is false.
+
+A genuine fact-accuracy problem is one of:
+
+- **geography / place** — a real location described in a way that contradicts the
+ reference (a city placed in the wrong country, region, or hemisphere; an
+ impossible distance or adjacency).
+- **history / chronology** — a real event, person, or technology placed in a time
+ it could not occupy (an anachronism: a device, word, or institution that did not
+ yet exist; a dated event off by enough to matter).
+- **science / physiology** — a claim that violates a documented physical or
+ biological limit (a survivable injury that isn't, a chemical/physical effect that
+ cannot occur, an impossible feat of strength, speed, or endurance).
+
+## Author fact reference — the ground truth
+
+The author has supplied this real-world fact reference. Treat it as the
+authoritative record the prose must stay consistent with. Flag a passage that
+contradicts a fact stated here; reason from the reference, not from your own
+general knowledge, when the two might differ.
+
+```
+{{factReference}}
+```
+
+Do NOT flag: a claim the reference does not actually address (you are reconciling
+against the reference, not policing every real-world detail); deliberate, signalled
+alternate-history or speculative invention the story clearly frames as a departure;
+a figure of speech, exaggeration, or character's mistaken belief the prose marks as
+such rather than asserting as true.
+
+## 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 problem kinds above, reconciling each checkable
+claim against the fact reference. For each genuine contradiction:
+
+1. Name the prose claim and the reference fact it contradicts.
+2. Quote a short verbatim anchor (≤ 200 chars) at the contradicting passage.
+3. Set the `location` to the subject + the problem kind — one of `geography`,
+ `history`, or `science` — e.g. `Paris — geography` or `the antibiotic — science`.
+
+Severity: a factual error the plot turns on, or one a knowledgeable reader cannot
+miss, is high; a small, easily-fixed detail is low. If the prose is consistent with
+the reference, return an empty `findings` array — do not invent errors, and do not
+flag claims the reference is silent on.
+
+## 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 + problem kind (e.g. 'Paris — geography' or 'the antibiotic — science')",
+ "problem": "1–3 sentences naming the prose claim and the reference fact it contradicts, and why it matters",
+ "suggestion": "1–3 sentences proposing how to correct or reconcile the claim",
+ "anchorQuote": "short verbatim quote at the contradicting passage (≤ 200 chars)"
+ }
+ ]
+}
+```
diff --git a/scripts/migrations/135-editorial-fact-accuracy-stage.js b/scripts/migrations/135-editorial-fact-accuracy-stage.js
new file mode 100644
index 0000000000..6db7a85494
--- /dev/null
+++ b/scripts/migrations/135-editorial-fact-accuracy-stage.js
@@ -0,0 +1,75 @@
+/**
+ * Seed the `pipeline-editorial-fact-accuracy` stage into existing installs (#1588).
+ *
+ * Mirrors `134-editorial-voice-consistency-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 fact-accuracy stage unseeded and the
+ * `research.fact-accuracy` 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-fact-accuracy.md';
+const STAGE_KEY = 'pipeline-editorial-fact-accuracy';
+
+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-fact-accuracy prompt: already present`);
+ } else {
+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
+ if (!sampleExists) {
+ console.warn(`⚠️ pipeline-editorial-fact-accuracy: sample missing for ${FILENAME} — skipping copy`);
+ } else {
+ try {
+ await copyFile(samplePath, dataPath);
+ console.log(`✅ seeded ${FILENAME}`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-editorial-fact-accuracy: 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-fact-accuracy: 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-fact-accuracy stage-config: already present`);
+ return;
+ }
+ if (!sample?.stages?.[STAGE_KEY]) {
+ console.warn(`⚠️ pipeline-editorial-fact-accuracy: 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-fact-accuracy stage-config (${action}): 1 added`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-editorial-fact-accuracy: stage-config merge failed: ${err.message}`);
+ }
+ },
+};
diff --git a/scripts/migrations/135-editorial-fact-accuracy-stage.test.js b/scripts/migrations/135-editorial-fact-accuracy-stage.test.js
new file mode 100644
index 0000000000..8f56ec8e4b
--- /dev/null
+++ b/scripts/migrations/135-editorial-fact-accuracy-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 './135-editorial-fact-accuracy-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 134) — no MD5 bookkeeping, so the
+// seed / no-clobber behavior is asserted directly.
+
+const FILENAME = 'pipeline-editorial-fact-accuracy.md';
+const STAGE_KEY = 'pipeline-editorial-fact-accuracy';
+const BODY = '# Research / fact accuracy\n\nshipped body\n';
+
+describe('migration 135 — seed editorial-fact-accuracy 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-135-'));
+ 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 98a9961acf..8f124a01e1 100644
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@ -146,6 +146,11 @@ export const EDITORIAL_SOURCES = Object.freeze([
'series.arc.tickingClock',
'series.arc.readerMap',
'series.arc.themes',
+ // The author-supplied real-world fact reference the opt-in research.fact-accuracy
+ // check reconciles the prose against (#1588). Lives on the already-loaded series
+ // record (no extra I/O); fingerprinting it stales fact findings when the author
+ // edits the reference.
+ 'series.factReference',
'reverseOutline',
'reverseOutline.plotlines',
'editorialArcs',
@@ -548,6 +553,16 @@ export const PLOT_STRUCTURE_STAGE = 'pipeline-editorial-plot-structure';
// impossible chronology.
export const TIMELINE_CONTRADICTION_STAGE = 'pipeline-editorial-timeline-contradiction';
+// Stage name for the research / fact-accuracy LLM check (#1588). Ships in
+// data.reference/prompts/stages/ + stage-config.json (fresh installs via
+// setup-data.js) and migrates to existing installs via migration 135 (boot runs
+// migrations but NOT setup-data, so the migration is required). Reconciles the
+// stitched manuscript against the author-supplied real-world fact reference
+// (`series.factReference`) — a prose claim that contradicts a documented external
+// fact (geography, history, physics/physiology). Opt-in and gated on the
+// `series.factCritical` flag so it never fires on pure fantasy.
+export const FACT_ACCURACY_STAGE = 'pipeline-editorial-fact-accuracy';
+
// 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
@@ -3253,6 +3268,65 @@ export const EDITORIAL_CHECKS = [
});
},
},
+ {
+ id: 'research.fact-accuracy',
+ sources: ['manuscript', 'series.factReference'],
+ label: 'Research / fact accuracy',
+ description:
+ 'LLM scan for contradictions to real-world facts the author has documented — a grounded historical, scientific, or geographic claim the prose gets wrong (a city placed in the wrong country, a date that predates the technology it describes, a physiologically impossible feat). Distinct from the internal timeline/canon-contradiction check: this reconciles the prose against EXTERNAL truth, not the story bible. Opt-in and gated — it runs only when the series is flagged fact-critical AND the author has supplied a fact reference, so it never second-guesses deliberate invention in pure fantasy.',
+ scope: 'series',
+ kind: 'llm',
+ category: 'accuracy',
+ // Fallback severity when the model omits one. A factual howler in grounded
+ // fiction is a credibility killer, but the prompt directs the model to mark a
+ // plot-relevant error 'high' per finding, so the worst cases still surface high.
+ severityDefault: 'medium',
+ // Opt-in: off by default so the check never runs on a series that hasn't
+ // declared itself fact-critical and supplied a reference (the gate also
+ // enforces both at run time).
+ defaultEnabled: false,
+ // 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 on BOTH the per-series fact-critical opt-in AND a non-empty author
+ // fact reference (plus a non-empty manuscript). Without a reference there's
+ // nothing authoritative to reconcile against, and the flag keeps the check
+ // off for fantasy where "wrong" real-world facts may be intentional.
+ gate: (ctx) =>
+ ctx.series?.factCritical === true
+ && (ctx.series?.factReference || '').trim().length > 0
+ && (ctx.manuscript || '').trim().length > 0,
+ run: (ctx) => {
+ // The author's documented real-world facts are the authoritative reference
+ // the prose is judged against — fixed per-call overhead re-sent on each
+ // chunk. Trimmed largest-first if the manuscript needs the room.
+ const factReference = (ctx.series?.factReference || '').trim();
+ return runManuscriptLlmCheck(ctx, {
+ stage: FACT_ACCURACY_STAGE,
+ category: 'accuracy',
+ context: { factReference },
+ buildVars: (manuscript, _meta, c) => ({
+ manuscript,
+ factReference: c.factReference,
+ }),
+ });
+ },
+ },
{
id: 'character.consistency',
sources: ['manuscript', 'canon', 'reverseOutline', 'series.characterArcs'],
diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.js
index 054c3af146..bd43a2868b 100644
--- a/server/lib/editorial/checkRegistry.test.js
+++ b/server/lib/editorial/checkRegistry.test.js
@@ -106,6 +106,26 @@ describe('editorial check registry — shape invariants', () => {
it('getCheck returns null for an unknown id', () => {
expect(getCheck('does.not-exist')).toBeNull();
});
+
+ it('fact-accuracy check is opt-in and gated on factCritical + a reference + manuscript (#1588)', () => {
+ const check = getCheck('research.fact-accuracy');
+ expect(check).toBeTruthy();
+ expect(check.kind).toBe('llm');
+ expect(check.scope).toBe('series');
+ // Off by default so it never runs on a series that hasn't declared itself
+ // fact-critical with a reference.
+ expect(check.defaultEnabled).toBe(false);
+ expect(check.sources).toContain('series.factReference');
+
+ const manuscript = 'Some prose.';
+ // All three preconditions present → gate opens.
+ expect(check.gate({ manuscript, series: { factCritical: true, factReference: 'Paris is in France.' } })).toBe(true);
+ // Missing any one → gate stays closed.
+ expect(check.gate({ manuscript, series: { factCritical: false, factReference: 'Paris is in France.' } })).toBe(false);
+ expect(check.gate({ manuscript, series: { factCritical: true, factReference: ' ' } })).toBe(false);
+ expect(check.gate({ manuscript: '', series: { factCritical: true, factReference: 'Paris is in France.' } })).toBe(false);
+ expect(check.gate({ manuscript, series: null })).toBe(false);
+ });
});
describe('editorial check registry — fail-fast guards', () => {
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 963ec68a05..c8a7b339d4 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -107,7 +107,15 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// arcs and last-writer-wins the loss back onto the newer peer. Bump makes the
// older peer reject the ahead-version series transfer instead. Per-category
// gate → only series sync pauses with old peers.
- pipelineSeries: 6,
+ // v7 = `series.factCritical` + `series.factReference` added (#1588) — the
+ // opt-in flag + author-supplied real-world fact reference the gated
+ // `research.fact-accuracy` editorial check reconciles the prose against. Same
+ // silent-strip-then-LWW corruption as styleGuide/characterArcs: a ≤v6 peer
+ // that re-sanitizes a series through its factReference-unaware `sanitizeSeries`
+ // would drop the reference (and reset the flag) and last-writer-wins the loss
+ // back onto the newer peer. Bump makes the older peer reject the ahead-version
+ // series transfer instead. Per-category gate → only series sync pauses with old peers.
+ pipelineSeries: 7,
// NOT bumped for the manuscript-review sibling doc now bundled on series
// pushes/exports (`data/pipeline-series/{id}/manuscript-review.json`).
// Unlike `readerMap` (v2), the review is NOT a field inside the series
diff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.js
index 20f2f0bbf4..ab40a7f15a 100644
--- a/server/lib/schemaVersions.test.js
+++ b/server/lib/schemaVersions.test.js
@@ -27,9 +27,10 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {
it('declares pipeline collection layout versions', () => {
// pipelineIssues bumped to 2 when stages.audio.audioMode + cues[] were added.
expect(PORTOS_SCHEMA_VERSIONS.pipelineIssues).toBe(2);
- // pipelineSeries bumped to 6 when series.characterArcs was added (v2 = readerMap,
- // v3 = tickingClock, v4 = styleGuide, v5 = coverImage).
- expect(PORTOS_SCHEMA_VERSIONS.pipelineSeries).toBe(6);
+ // pipelineSeries bumped to 7 when series.factCritical + series.factReference
+ // were added (#1588) (v2 = readerMap, v3 = tickingClock, v4 = styleGuide,
+ // v5 = coverImage, v6 = characterArcs).
+ expect(PORTOS_SCHEMA_VERSIONS.pipelineSeries).toBe(7);
});
it('declares mediaCollections layout version', () => {
@@ -43,7 +44,7 @@ describe('buildPortosMeta', () => {
expect(meta.portosVersion).toMatch(/^\d+\.\d+\.\d+/);
expect(meta.schemaVersions.universes).toBe(7);
expect(meta.schemaVersions.pipelineIssues).toBe(2);
- expect(meta.schemaVersions.pipelineSeries).toBe(6);
+ expect(meta.schemaVersions.pipelineSeries).toBe(7);
});
it('overrides merge into schemaVersions', async () => {
diff --git a/server/routes/pipeline/series.js b/server/routes/pipeline/series.js
index 74ebf74368..32c0cd99c7 100644
--- a/server/routes/pipeline/series.js
+++ b/server/routes/pipeline/series.js
@@ -181,6 +181,9 @@ const seriesCreateSchema = z.object({
characterArcs: characterArcsSchema.optional(),
locked: seriesLockedSchema.optional(),
styleNotes: z.string().trim().max(seriesSvc.STYLE_NOTES_MAX).optional().default(''),
+ // Fact-checking opt-in + author fact reference (#1588).
+ factCritical: z.boolean().optional().default(false),
+ factReference: z.string().trim().max(seriesSvc.FACT_REFERENCE_MAX).optional().default(''),
styleGuide: styleGuideSchema.nullable().optional(),
titleLogo: z.string().trim().max(seriesSvc.TITLE_LOGO_MAX).optional().default(''),
author: z.string().trim().max(seriesSvc.AUTHOR_MAX).optional().default(''),
@@ -206,6 +209,9 @@ const seriesPatchSchema = z.object({
characterArcs: characterArcsSchema.optional(),
locked: seriesLockedSchema.optional(),
styleNotes: z.string().trim().max(seriesSvc.STYLE_NOTES_MAX).optional(),
+ // Fact-checking opt-in + author fact reference (#1588).
+ factCritical: z.boolean().optional(),
+ factReference: z.string().trim().max(seriesSvc.FACT_REFERENCE_MAX).optional(),
styleGuide: styleGuideSchema.nullable().optional(),
titleLogo: z.string().trim().max(seriesSvc.TITLE_LOGO_MAX).optional(),
author: z.string().trim().max(seriesSvc.AUTHOR_MAX).optional(),
diff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.js
index 3170b0b538..6f70206b54 100644
--- a/server/services/pipeline/editorial/checkRunner.js
+++ b/server/services/pipeline/editorial/checkRunner.js
@@ -83,6 +83,10 @@ const SOURCE_RESOLVERS = {
// (#1317). Lives on the already-loaded series record, so no extra I/O — fingerprint
// the whole themes array so adding/editing a declared theme stales the findings.
'series.arc.themes': ({ series }) => canonicalStringify(series?.arc?.themes ?? null),
+ // The author-supplied real-world fact reference the research.fact-accuracy check
+ // reconciles the prose against (#1588). Lives on the already-loaded series record,
+ // so no extra I/O — fingerprint the reference text so editing it stales fact findings.
+ 'series.factReference': ({ series }) => canonicalStringify(series?.factReference ?? null),
// The reverse-outline scenes the check reads (#1296). Fingerprinting the whole
// scenes array is intentionally over-eager (any scene edit stales a finding)
// rather than under: safe vs. false-fresh, and the check reads several scene fields.
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index b285c9ca20..37c6496e48 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -50,6 +50,11 @@ export const NAME_MAX = 200;
export const LOGLINE_MAX = 500;
export const PREMISE_MAX = 8000;
export const STYLE_NOTES_MAX = 4000;
+// Author-supplied real-world fact reference (#1588) — the ground-truth facts the
+// opt-in `research.fact-accuracy` editorial check reconciles the prose against
+// (e.g. "Paris is the capital of France"; physiological limits). Generous cap so
+// a grounded historical/SFF series can paste a sizable fact sheet.
+export const FACT_REFERENCE_MAX = 8000;
export const STYLE_PROMPT_OVERRIDE_MAX = 1000;
// How `stylePromptOverride` composes with the universe's style influences:
// 'prepend' — override leads, universe trails (the historical default
@@ -223,6 +228,14 @@ const sanitizeSeries = (raw) => {
characterArcs: sanitizeCharacterArcList(raw.characterArcs),
locked: sanitizeSeriesLocked(raw.locked),
styleNotes: trimTo(raw.styleNotes, STYLE_NOTES_MAX),
+ // Fact-checking opt-in (#1588). When true (and a non-empty `factReference`
+ // is supplied), the gated `research.fact-accuracy` editorial check runs so
+ // it never fires on pure fantasy. Defaults to false — existing series.json
+ // files (which predate these fields) migrate forward without a writer pass;
+ // first save backfills both. Wire-gated (pipelineSeries schema v7) so a
+ // factReference-unaware peer can't strip-then-LWW the loss back.
+ factCritical: raw.factCritical === true,
+ factReference: trimTo(raw.factReference, FACT_REFERENCE_MAX),
// Per-series house style (tense/POV/audience/rating/reading-level/tone/
// conventions). Structured companion to the free-text styleNotes above;
// sanitizeStyleGuide returns null when empty so existing series.json files
@@ -311,6 +324,8 @@ export async function createSeries(input = {}) {
characterArcs: input.characterArcs || [],
locked: input.locked || {},
styleNotes: input.styleNotes || '',
+ factCritical: input.factCritical === true,
+ factReference: input.factReference || '',
styleGuide: input.styleGuide || null,
titleLogo: input.titleLogo || '',
author: input.author || '',
@@ -473,6 +488,11 @@ export async function updateSeries(id, patch = {}) {
// Wholesale replace — `locked: {}` clears every lock; omission preserves.
...('locked' in patch ? { locked: patch.locked } : {}),
...('styleNotes' in patch ? { styleNotes: patch.styleNotes } : {}),
+ // Fact-checking opt-in + author fact reference (#1588). `factReference: ''`
+ // clears the reference; omission preserves. Sanitizer normalizes a
+ // non-true `factCritical` back to false.
+ ...('factCritical' in patch ? { factCritical: patch.factCritical } : {}),
+ ...('factReference' in patch ? { factReference: patch.factReference } : {}),
// Wholesale replace — sanitizeStyleGuide normalizes an empty object back
// to null (clear); omission preserves. Mirrors the arc/readerMap pattern.
...('styleGuide' in patch ? { styleGuide: patch.styleGuide } : {}),
@@ -703,7 +723,7 @@ async function cascadeDeleteSideEffects(id) {
// consult the RAW remote payload to tell the two apart: key absent → preserve
// local; key present (even null/empty) → honor the intentional clear. Mirrors
// the `universeId` hierarchy guard. See issue #1361.
-const ADDITIVE_SERIES_FIELDS = ['arc', 'seasons', 'styleGuide', 'styleNotes', 'characterArcs'];
+const ADDITIVE_SERIES_FIELDS = ['arc', 'seasons', 'styleGuide', 'styleNotes', 'characterArcs', 'factReference', 'factCritical'];
// Additive sub-fields nested inside `arc`. A peer that predates these (readerMap
// shipped at schema v2, tickingClock at #1289/v3) still sends an `arc` object —
// just without these keys — so the erasure for them happens one level down.
diff --git a/server/services/pipeline/series.test.js b/server/services/pipeline/series.test.js
index 9dc5a89e97..eaed2c14e6 100644
--- a/server/services/pipeline/series.test.js
+++ b/server/services/pipeline/series.test.js
@@ -99,6 +99,32 @@ describe('pipeline series service', () => {
expect(updated.updatedAt >= s.updatedAt).toBe(true);
});
+ it('defaults fact-checking fields off (#1588) and round-trips an opt-in + reference', async () => {
+ const off = await svc.createSeries({ name: 'Fantasy' });
+ expect(off.factCritical).toBe(false);
+ expect(off.factReference).toBe('');
+
+ const on = await svc.createSeries({
+ name: 'Grounded',
+ factCritical: true,
+ factReference: 'Paris is the capital of France.',
+ });
+ expect(on.factCritical).toBe(true);
+ expect(on.factReference).toBe('Paris is the capital of France.');
+ });
+
+ it('updateSeries clears the fact reference with "" but preserves it on omission (#1588)', async () => {
+ const s = await svc.createSeries({ name: 'Grounded', factCritical: true, factReference: 'Real facts.' });
+ // Omitting the field preserves both.
+ const kept = await svc.updateSeries(s.id, { logline: 'L2' });
+ expect(kept.factCritical).toBe(true);
+ expect(kept.factReference).toBe('Real facts.');
+ // Explicit "" clears the reference; toggling factCritical off sticks.
+ const cleared = await svc.updateSeries(s.id, { factCritical: false, factReference: '' });
+ expect(cleared.factCritical).toBe(false);
+ expect(cleared.factReference).toBe('');
+ });
+
it('updateSeries throws ERR_NOT_FOUND for unknown id', async () => {
await expect(svc.updateSeries('ser-nope', { name: 'x' })).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });
});