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: continuity bible facts-ledger + Series Continuity view (#1305)

[._.]/ Adam Eivy95a49c0233df
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 1430c6a263..fc3a5cc3e9 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **[issue-1305] Continuity bible — an established-facts ledger for your series.** A new **Series Continuity** view (linked from the series page) builds a ledger of the concrete, *checkable* facts your story has committed to — the kind a later scene could contradict. Facts are **auto-seeded from universe canon** (each character's physical description, each place/object's description; **locked** canon is flagged as ground truth) and then **learned from the drafted prose** via an LLM extraction pass, sorted into seven buckets: physical traits, ages & birthdays, dates & elapsed time, locations & geography, possessions & wardrobe, world rules, and **who-knows-what-when**. Each fact shows its subject, the assertion, a canon/prose badge, and — for prose facts — a verbatim anchor quote and a deep-link to the issue where it was established. Generation streams live progress; the ledger flags itself **stale** when the manuscript or canon changes so you know to rebuild. This ledger is the substrate the upcoming contradiction checks (canon-contradiction, timeline, knowledge-leak, wardrobe/prop/injury) will read rather than re-deriving. New endpoints: `GET /api/pipeline/series/:id/continuity-bible` + `POST …/generate` (with SSE progress + cancel); one new stage prompt (`pipeline-continuity-bible`) shipped + migrated for existing installs. (#1305)
+
- **[issue-1303] Per-series style guide — one source of truth for tense, POV, audience, rating, and reading level.** Style used to live only in free-text notes, so generation could drift and nothing could check conformance. Each series now has a structured **style guide** on its bible: narrative **tense** (past/present), **POV person** (first / second / third-limited / third-omniscient), **target audience**, **content rating** + allowed **profanity**, a target **reading level**, **tone** words, and copy-edit **conventions** (Oxford comma, US/UK spelling, italicize-thoughts). The guide is woven into prose and arc generation so the AI writes in the right register from the start, and two new editorial checks audit the drafted manuscript against it: **Reading-level conformance** (measures the manuscript's grade level and flags it when it drifts from the target) and **Style-guide conformance** (an LLM scan for tense slips, POV-person drift, and content/profanity beyond the configured rating). Everything is optional and additive — a series without a style guide behaves exactly as before — and the field is version-gated for cross-machine sync so an older peer can't silently strip it. (#1303)
- **[issue-1354] Catalog cards show image thumbnails, generate art from a description, and a "Sync from Universes" button pulls in missing canon.** Three catalog gaps closed at once. (1) **Missing canon items** — characters/places/objects you add to a universe *after* the one-time setup never appeared in the Catalog, because canon→catalog promotion only ran once per install. A new **Sync from Universes** button on the Catalog page re-runs that promotion on demand (idempotent — already-catalogued items are skipped), so the catalog catches up to your universes in one click and the list refreshes with what was pulled in. (2) **Thumbnails** — each catalog card now shows the item's portrait (or its most recent reference image) as a thumbnail, falling back to a placeholder when there's no image, so the grid is scannable at a glance. (3) **Generate from description** — the catalog item editor's Media panel gets a **Generate** button that turns the item's description into an image via the same image-gen queue the universe canon uses; the first generated image becomes the item's portrait (and thumbnail), later ones attach as references. The button is disabled until the item has a description to render from. (#1354)
diff --git a/client/src/App.jsx b/client/src/App.jsx
index f3edba9fac..bbef865c62 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -93,6 +93,7 @@ const PipelineSeries = lazyWithReload(() => import('./pages/PipelineSeries'));
const PipelineSeriesRoadmap = lazyWithReload(() => import('./pages/PipelineSeriesRoadmap'));
const PipelineEditorialChecks = lazyWithReload(() => import('./pages/PipelineEditorialChecks'));
const PipelineReverseOutline = lazyWithReload(() => import('./pages/PipelineReverseOutline'));
+const PipelineContinuityBible = lazyWithReload(() => import('./pages/PipelineContinuityBible'));
const PipelineManuscriptEditor = lazyWithReload(() => import('./pages/PipelineManuscriptEditor'));
const PipelineIssue = lazyWithReload(() => import('./pages/PipelineIssue'));
const Login = lazyWithReload(() => import('./pages/Login'));
@@ -315,6 +316,7 @@ export default function App() {
<Route path="pipeline/series/:seriesId" element={<PipelineSeries />} />
<Route path="pipeline/series/:seriesId/roadmap" element={<PipelineSeriesRoadmap />} />
<Route path="pipeline/series/:seriesId/reverse-outline" element={<PipelineReverseOutline />} />
+ <Route path="pipeline/series/:seriesId/continuity-bible" element={<PipelineContinuityBible />} />
{/* Splat (not a :param route) so navigating between issues reuses the
same component instance instead of remounting + refetching. */}
<Route path="pipeline/series/:seriesId/manuscript/*" element={<PipelineManuscriptEditor />} />
diff --git a/client/src/pages/PipelineContinuityBible.jsx b/client/src/pages/PipelineContinuityBible.jsx
new file mode 100644
index 0000000000..35e96382b0
--- /dev/null
+++ b/client/src/pages/PipelineContinuityBible.jsx
@@ -0,0 +1,266 @@
+/**
+ * Pipeline — Continuity Bible / Series Continuity view (#1305, PR 1).
+ *
+ * A browsable established-facts ledger: the concrete, checkable facts the story
+ * has committed to, grouped by category (physical traits, ages, dates, places,
+ * possessions, world rules, who-knows-what-when). Facts are auto-seeded from
+ * universe canon (locked canon = ground truth) and learned from the drafted
+ * prose. Each prose fact deep-links to the issue where it was established.
+ * Generation streams progress over SSE; the ledger flags itself stale when the
+ * manuscript or canon changes.
+ */
+
+import { useEffect, useRef, useState } from 'react';
+import { Link, useParams, useNavigate } from 'react-router-dom';
+import { Loader2, RefreshCw, X, ArrowLeft, BookOpen, AlertTriangle, BookMarked, Lock } from 'lucide-react';
+import toast from '../components/ui/Toast';
+import {
+ getPipelineSeries,
+ getContinuityBible,
+ generateContinuityBible,
+ cancelContinuityBible,
+ getContinuityBibleStatus,
+ pipelineContinuityBibleSseUrl,
+} from '../services/api';
+import { usePipelineProgress } from '../hooks/usePipelineProgress';
+
+const RUN_ENDED = new Set(['complete', 'canceled', 'cancelled', 'error']);
+
+// The server ships `ledger.categories` (its FACT_CATEGORIES) with every
+// response, so section order + labels come from the server and can't drift.
+// This is only a fallback for a payload that predates that field.
+const FALLBACK_CATEGORIES = [
+ { id: 'physical', label: 'Physical traits' },
+ { id: 'age', label: 'Ages & birthdays' },
+ { id: 'timeline', label: 'Dates & elapsed time' },
+ { id: 'location', label: 'Locations & geography' },
+ { id: 'possession', label: 'Possessions & wardrobe' },
+ { id: 'world-rule', label: 'World rules' },
+ { id: 'knowledge', label: 'Who knows what, when' },
+];
+
+export default function PipelineContinuityBible() {
+ const { seriesId } = useParams();
+ const navigate = useNavigate();
+ const [series, setSeries] = useState(null);
+ const [ledger, setLedger] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [active, setActive] = useState(false);
+ const [starting, setStarting] = useState(false);
+ const activeRunIdRef = useRef(null);
+
+ // Load series + ledger, and re-attach to an in-flight run on (re)mount.
+ useEffect(() => {
+ let canceled = false;
+ setLoading(true);
+ Promise.all([
+ getPipelineSeries(seriesId),
+ getContinuityBible(seriesId),
+ getContinuityBibleStatus(seriesId).catch(() => ({ active: false })),
+ ])
+ .then(([s, l, status]) => {
+ if (canceled) return;
+ setSeries(s);
+ setLedger(l);
+ if (status?.active) setActive(true);
+ })
+ .catch((err) => {
+ if (canceled) return;
+ toast.error(err.message || 'Failed to load continuity bible');
+ navigate('/pipeline');
+ })
+ .finally(() => { if (!canceled) setLoading(false); });
+ return () => { canceled = true; };
+ }, [seriesId, navigate]);
+
+ const { latest } = usePipelineProgress(pipelineContinuityBibleSseUrl, [seriesId], { enabled: active });
+
+ // React to the terminal frame: refetch the ledger, drop the busy state.
+ useEffect(() => {
+ if (!active || !latest || !RUN_ENDED.has(latest.type)) return;
+ if (activeRunIdRef.current && latest.runId && latest.runId !== activeRunIdRef.current) return;
+ setActive(false);
+ activeRunIdRef.current = null;
+ if (latest.type === 'complete') {
+ getContinuityBible(seriesId).then((l) => setLedger(l)).catch(() => {});
+ if (latest.status === 'no-content') toast.warning('Nothing to build a ledger from — add canon or draft a manuscript first');
+ else toast.success(`Continuity bible ready — ${latest.factCount || 0} facts`);
+ } else if (latest.type === 'canceled') {
+ toast.success('Continuity bible canceled');
+ } else {
+ toast.error(latest.error || 'Continuity bible failed');
+ }
+ }, [active, latest, seriesId]);
+
+ const handleGenerate = async (force) => {
+ setStarting(true);
+ // Await the POST so the run is registered server-side BEFORE the SSE
+ // subscription connects — otherwise the progress stream 404s on attach.
+ const res = await generateContinuityBible(seriesId, { force }, { silent: true }).catch((err) => {
+ toast.error(err.message || 'Failed to start continuity bible');
+ return null;
+ });
+ setStarting(false);
+ if (!res?.runId) return;
+ activeRunIdRef.current = res.runId;
+ setActive(true);
+ };
+
+ const handleCancel = () => {
+ cancelContinuityBible(seriesId).catch(() => {});
+ };
+
+ if (loading) {
+ return (
+ <div className="h-full flex items-center justify-center text-gray-400">
+ <Loader2 className="animate-spin" size={20} />
+ </div>
+ );
+ }
+
+ const facts = ledger?.facts || [];
+ const hasLedger = ledger?.status === 'complete' && facts.length > 0;
+ const busy = active || starting;
+ const categories = ledger?.categories?.length ? ledger.categories : FALLBACK_CATEGORIES;
+ const groups = categories
+ .map((cat) => ({ ...cat, facts: facts.filter((f) => f.category === cat.id) }))
+ .filter((g) => g.facts.length > 0);
+ const canonCount = facts.filter((f) => f.source === 'canon').length;
+
+ return (
+ <div className="h-full overflow-y-auto p-4 md:p-6">
+ <header className="flex flex-wrap items-center gap-2 mb-4">
+ <Link
+ to={`/pipeline/series/${seriesId}`}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-400 hover:text-white border border-port-border bg-port-card"
+ title="Back to series"
+ >
+ <ArrowLeft size={12} /> Series
+ </Link>
+ <h1 className="text-lg font-semibold text-white flex items-center gap-2">
+ <BookMarked size={18} className="text-port-accent" /> Series Continuity
+ </h1>
+ {series?.name ? <span className="text-sm text-gray-400 truncate">— {series.name}</span> : null}
+ <div className="ml-auto flex items-center gap-2">
+ {active ? (
+ <button
+ type="button"
+ onClick={handleCancel}
+ className="inline-flex items-center gap-1 px-3 py-2 rounded-lg border border-port-border bg-port-card text-sm text-gray-300 hover:text-white"
+ >
+ <X size={14} /> Cancel
+ </button>
+ ) : null}
+ <button
+ type="button"
+ onClick={() => handleGenerate(hasLedger)}
+ disabled={busy}
+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"
+ title={hasLedger ? 'Re-extract the facts ledger from canon + the current manuscript' : 'Build the facts ledger from canon + the drafted manuscript'}
+ >
+ {busy ? <Loader2 size={14} className="animate-spin" /> : <RefreshCw size={14} />}
+ {busy ? 'Building…' : hasLedger ? 'Rebuild ledger' : 'Build ledger'}
+ </button>
+ </div>
+ </header>
+
+ {ledger?.stale && hasLedger ? (
+ <div className="mb-4 flex items-center gap-2 px-3 py-2 rounded-lg border border-port-warning/40 bg-port-warning/10 text-port-warning text-sm">
+ <AlertTriangle size={14} />
+ The manuscript or canon changed since this ledger was built — rebuild to refresh.
+ </div>
+ ) : null}
+
+ {!hasLedger ? (
+ <EmptyState status={ledger?.status} active={busy} />
+ ) : (
+ <div className="flex flex-col gap-5">
+ {groups.map((group) => (
+ <FactGroup key={group.id} group={group} seriesId={seriesId} navigate={navigate} />
+ ))}
+ <p className="text-xs text-gray-500">
+ {facts.length} facts · {canonCount} from canon · {facts.length - canonCount} from prose
+ {ledger?.truncated ? ' · manuscript truncated for analysis (long series)' : ''}
+ </p>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function EmptyState({ status, active }) {
+ if (active) {
+ return (
+ <div className="text-center text-gray-400 py-16">
+ <Loader2 className="animate-spin mx-auto mb-3" size={24} />
+ Extracting established facts from canon and the manuscript…
+ </div>
+ );
+ }
+ if (status === 'no-content') {
+ return (
+ <div className="text-center text-gray-400 py-16">
+ <BookOpen className="mx-auto mb-3 opacity-40" size={28} />
+ No canon and nothing drafted yet. Add characters/places/objects or write a manuscript, then build the ledger.
+ </div>
+ );
+ }
+ return (
+ <div className="text-center text-gray-400 py-16">
+ <BookMarked className="mx-auto mb-3 opacity-40" size={28} />
+ No continuity bible yet. Build one to ledger the facts your story has established.
+ </div>
+ );
+}
+
+function FactGroup({ group, seriesId, navigate }) {
+ return (
+ <section className="border border-port-border rounded-lg overflow-hidden">
+ <h2 className="px-3 py-2 bg-port-card text-sm font-semibold text-white flex items-center gap-2">
+ {group.label}
+ <span className="text-xs text-gray-500 font-normal">{group.facts.length}</span>
+ </h2>
+ <ul className="divide-y divide-port-border/50">
+ {group.facts.map((fact) => (
+ <FactRow key={fact.id} fact={fact} seriesId={seriesId} navigate={navigate} />
+ ))}
+ </ul>
+ </section>
+ );
+}
+
+function FactRow({ fact, seriesId, navigate }) {
+ const fromCanon = fact.source === 'canon';
+ return (
+ <li className="px-3 py-2 flex flex-col gap-1">
+ <div className="flex items-start gap-2">
+ <span className="text-xs font-medium text-gray-200 shrink-0 mt-0.5">{fact.subject}</span>
+ <span className="text-sm text-gray-300 flex-1">{fact.statement}</span>
+ <span
+ className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] shrink-0 ${
+ fromCanon ? 'bg-port-accent/15 text-port-accent' : 'bg-port-border/40 text-gray-400'
+ }`}
+ title={fromCanon ? (fact.canonical ? 'Seeded from locked canon (ground truth)' : 'Seeded from universe canon') : 'Learned from the drafted prose'}
+ >
+ {fromCanon && fact.canonical ? <Lock size={9} /> : null}
+ {fromCanon ? 'canon' : 'prose'}
+ </span>
+ </div>
+ {(fact.anchorQuote || fact.issueNumber != null) ? (
+ <div className="flex items-center gap-2 text-xs text-gray-500">
+ {fact.anchorQuote ? <span className="italic truncate">“{fact.anchorQuote}”</span> : null}
+ {fact.issueNumber != null ? (
+ <button
+ type="button"
+ onClick={() => navigate(`/pipeline/series/${seriesId}/manuscript/${fact.issueNumber}`)}
+ className="ml-auto inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-gray-400 hover:text-white border border-port-border shrink-0"
+ title="Open the issue where this fact is established"
+ >
+ <BookOpen size={11} /> Issue {fact.issueNumber}
+ </button>
+ ) : null}
+ </div>
+ ) : null}
+ </li>
+ );
+}
diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsx
index 7520f803b2..ab3e22f9bb 100644
--- a/client/src/pages/PipelineSeries.jsx
+++ b/client/src/pages/PipelineSeries.jsx
@@ -14,7 +14,7 @@ import { useEffect, useState } from 'react';
import { Link, useParams, useNavigate } from 'react-router-dom';
import {
ArrowLeft, Save, Loader2, Workflow as WorkflowIcon, Globe, NotebookPen,
- PanelLeftClose, PanelLeftOpen, Sparkles, BookOpen, FileInput, Compass,
+ PanelLeftClose, PanelLeftOpen, Sparkles, BookOpen, FileInput, Compass, BookMarked,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import ArcCanvas from '../components/pipeline/ArcCanvas';
@@ -214,6 +214,13 @@ export default function PipelineSeries() {
>
<Compass size={12} /> Reverse Outline
</Link>
+ <Link
+ to={`/pipeline/series/${series.id}/continuity-bible`}
+ className="ml-2 inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-400 hover:text-white border border-port-border bg-port-card"
+ title="Browse the established-facts ledger — physical traits, ages, dates, places, possessions, world rules, and who knows what"
+ >
+ <BookMarked size={12} /> Continuity
+ </Link>
<Link
to={buildImporterLink({ universeId: series.universeId, seriesId: series.id })}
className="ml-2 inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-400 hover:text-white border border-port-border bg-port-card"
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index fe59168528..e7a6e7474e 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -684,6 +684,33 @@ export const getReverseOutlineStatus = (seriesId, options = {}) =>
export const pipelineReverseOutlineSseUrl = (seriesId) =>
`/api/pipeline/series/${encodeURIComponent(seriesId)}/reverse-outline/generate/progress`;
+// ---- Continuity Bible (established-facts ledger) ----
+// The stored ledger: { facts, stale, status }. `status:'none'` when never
+// generated, `'no-content'` shell while there's no canon and nothing drafted.
+export const getContinuityBible = (seriesId, options = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/continuity-bible`, options);
+
+// Kick off a (re)generation. { runId, alreadyRunning, sseUrl } — subscribe via
+// pipelineContinuityBibleSseUrl to stream progress, then re-fetch on `complete`.
+export const generateContinuityBible = (seriesId, opts = {}, options = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/continuity-bible/generate`, {
+ method: 'POST',
+ body: JSON.stringify(opts),
+ ...options,
+ });
+
+export const cancelContinuityBible = (seriesId) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/continuity-bible/generate/cancel`, {
+ method: 'POST',
+ });
+
+// { active: boolean } — lets a (re)mounting view re-attach to an in-flight run.
+export const getContinuityBibleStatus = (seriesId, options = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/continuity-bible/generate/status`, options);
+
+export const pipelineContinuityBibleSseUrl = (seriesId) =>
+ `/api/pipeline/series/${encodeURIComponent(seriesId)}/continuity-bible/generate/progress`;
+
// ---- Series Autopilot (full autonomous mode) ----
// Drives a series from its current state to story-ready (+ draft visuals) by
// composing every pipeline pass. SSE-backed; gated on the cos autonomy domain
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index c0c0b6e9f8..8f6e900026 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -296,6 +296,13 @@
"returnsJson": true,
"variables": []
},
+ "pipeline-continuity-bible": {
+ "name": "Pipeline — Continuity Bible (established-facts ledger)",
+ "description": "Read the whole drafted manuscript and extract concrete, checkable facts about the story world — physical traits, ages, dates/elapsed time, locations, possessions, world rules, and who-knows-what-when. Auto-seeded from universe canon (locked canon = ground truth) and learned from prose; feeds the browsable Series Continuity view and is the substrate the canon-contradiction / timeline / knowledge-leak checks read. Runs at `heavy` tier — reads the full stitched manuscript.",
+ "model": "heavy",
+ "returnsJson": true,
+ "variables": []
+ },
"pipeline-extract-scenes": {
"name": "Pipeline — Extract Scenes from TV Teleplay",
"description": "Parse an already-formatted TV teleplay into a structured scenes[] list (one entry per slugline) the storyboards stage can render. Defers to character / setting bibles for canonical names and slugline reuse.",
diff --git a/data.reference/prompts/stages/pipeline-continuity-bible.md b/data.reference/prompts/stages/pipeline-continuity-bible.md
new file mode 100644
index 0000000000..26a389e4f6
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-continuity-bible.md
@@ -0,0 +1,64 @@
+# Pipeline — Continuity Bible (established-facts ledger)
+
+You are a continuity editor building an **established-facts ledger** for an already-drafted manuscript — a list of concrete, *checkable* facts the prose has committed to, so a later pass can catch contradictions. You are NOT rewriting, improving, or judging the manuscript. You are reading it and recording what it has established as true in the story world.
+
+## Series
+
+- **Title:** {{series.name}}
+- **Tone / style:** {{series.styleNotes}}
+
+## Known characters
+
+{{knownCharacters}}
+
+## Source manuscript (stitched, in story order)
+
+Each issue/episode is delimited by a `# Issue N — Title (stage)` header.
+
+```
+{{manuscript}}
+```
+
+## What to extract
+
+Walk the manuscript and record every concrete, falsifiable fact about the story world. A good fact is one another scene could *contradict* (eye color, an age, a date, a possession, a rule of magic, who knows a secret). Skip vague impressions, mood, and anything not pinned to a specific detail.
+
+Sort each fact into exactly one of these categories (use the `id`):
+
+{{categories}}
+
+For each fact record:
+- **`category`** — one of the category ids above.
+- **`subject`** — who or what the fact is about (a character, place, or object name; match the known-characters list when possible).
+- **`statement`** — the established fact as a short, checkable assertion (e.g. `Has a crescent scar over the left eye`, `Is 34 years old at the story's start`, `The festival is three days after the duke arrives`, `Iron cannot cross the threshold stones`, `Knows Dov is the informant`).
+- **`issueNumber`** — the number from the nearest `# Issue N` header above where this fact is first established. Use `null` if it can't be tied to one issue.
+- **`anchorQuote`** — a short **verbatim** quote (5–12 words) copied exactly from the manuscript where the fact is established, so the editor can jump to it. Do not paraphrase — copy character-for-character. Use `""` if no clean anchor exists.
+
+**Knowledge facts (`knowledge`)** are special: record *who knows what, and as of when*, so a later check can catch a character acting on information they couldn't have yet. Phrase the statement as `<Character> knows <fact>` and anchor it to where they learn it.
+
+Be thorough but precise — one fact per assertion. Do not duplicate the same fact across categories.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:
+
+```json
+{
+ "facts": [
+ {
+ "category": "physical",
+ "subject": "Mara",
+ "statement": "Has green eyes",
+ "issueNumber": 1,
+ "anchorQuote": "her green eyes narrowed"
+ },
+ {
+ "category": "knowledge",
+ "subject": "Dov",
+ "statement": "Knows the safehouse address",
+ "issueNumber": 2,
+ "anchorQuote": "Dov memorized the address on Pell Street"
+ }
+ ]
+}
+```
diff --git a/scripts/migrations/097-continuity-bible-stage.js b/scripts/migrations/097-continuity-bible-stage.js
new file mode 100644
index 0000000000..c9b59142f6
--- /dev/null
+++ b/scripts/migrations/097-continuity-bible-stage.js
@@ -0,0 +1,75 @@
+/**
+ * Seed the `pipeline-continuity-bible` stage into existing installs (#1305).
+ *
+ * Mirrors `093-reverse-outline-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 Continuity Bible stage
+ * unseeded and `buildPrompt('pipeline-continuity-bible')` would throw "Stage not
+ * found" the first time a user generates a continuity bible.
+ */
+
+import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';
+import { dirname, join } from 'path';
+
+const FILENAME = 'pipeline-continuity-bible.md';
+const STAGE_KEY = 'pipeline-continuity-bible';
+
+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-continuity-bible prompt: already present`);
+ } else {
+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
+ if (!sampleExists) {
+ console.warn(`⚠️ pipeline-continuity-bible: sample missing for ${FILENAME} — skipping copy`);
+ } else {
+ try {
+ await copyFile(samplePath, dataPath);
+ console.log(`✅ seeded ${FILENAME}`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-continuity-bible: 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-continuity-bible: 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-continuity-bible stage-config: already present`);
+ return;
+ }
+ if (!sample?.stages?.[STAGE_KEY]) {
+ console.warn(`⚠️ pipeline-continuity-bible: 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-continuity-bible stage-config (${action}): 1 added`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-continuity-bible: stage-config merge failed: ${err.message}`);
+ }
+ },
+};
diff --git a/scripts/migrations/097-continuity-bible-stage.test.js b/scripts/migrations/097-continuity-bible-stage.test.js
new file mode 100644
index 0000000000..585081413f
--- /dev/null
+++ b/scripts/migrations/097-continuity-bible-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 './097-continuity-bible-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 093/095) — no MD5 bookkeeping, so the
+// seed / no-clobber behavior is asserted directly.
+
+const FILENAME = 'pipeline-continuity-bible.md';
+const STAGE_KEY = 'pipeline-continuity-bible';
+const BODY = '# Continuity bible\n\nshipped body\n';
+
+describe('migration 097 — seed continuity-bible 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: 'heavy', returnsJson: true, variables: [] } } }, null, 2) + '\n',
+ );
+ }
+ };
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-097-'));
+ 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/routes/pipeline/continuityBible.js b/server/routes/pipeline/continuityBible.js
new file mode 100644
index 0000000000..a68f9509e4
--- /dev/null
+++ b/server/routes/pipeline/continuityBible.js
@@ -0,0 +1,59 @@
+/**
+ * Pipeline continuity-bible routes (#1305) — established-facts ledger for a
+ * series, auto-seeded from canon and learned from prose. Read the stored
+ * ledger, kick off a (re)generation with SSE progress, probe/cancel a run.
+ */
+
+import { Router } from 'express';
+import { z } from 'zod';
+import { asyncHandler, ServerError } from '../../lib/errorHandler.js';
+import { validateRequest } from '../../lib/validation.js';
+import * as seriesSvc from '../../services/pipeline/series.js';
+import * as continuityBible from '../../services/pipeline/continuityBible.js';
+import { mapServiceError } from './shared.js';
+
+const router = Router();
+
+// Generation params — provider/model optional (falls through to the active or
+// stage-pinned provider); `force` re-extracts even when the inputs are
+// unchanged. Mirrors the reverse-outline schema.
+const continuityBibleGenerateSchema = z.object({
+ providerId: z.string().trim().max(80).optional(),
+ model: z.string().trim().max(200).optional(),
+ force: z.boolean().optional(),
+});
+
+// The stored ledger (facts) with a `stale` flag.
+router.get('/series/:id/continuity-bible', asyncHandler(async (req, res) => {
+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ res.json(await continuityBible.getContinuityBible(req.params.id));
+}));
+
+// (Re)generate — seed from canon + extract from the whole manuscript, progress via SSE.
+router.post('/series/:id/continuity-bible/generate', asyncHandler(async (req, res) => {
+ const body = validateRequest(continuityBibleGenerateSchema, req.body ?? {});
+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const result = continuityBible.startContinuityBibleRun(req.params.id, body);
+ res.json({
+ ...result,
+ sseUrl: `/api/pipeline/series/${req.params.id}/continuity-bible/generate/progress`,
+ });
+}));
+
+router.get('/series/:id/continuity-bible/generate/progress', (req, res) => {
+ const attached = continuityBible.attachClient(req.params.id, res);
+ if (!attached) {
+ throw new ServerError('No active continuity-bible run for this series', { status: 404 });
+ }
+});
+
+// Lightweight probe so a (re)mounting client can re-attach to an in-flight run.
+router.get('/series/:id/continuity-bible/generate/status', (req, res) => {
+ res.json({ active: continuityBible.isContinuityBibleActive(req.params.id) });
+});
+
+router.post('/series/:id/continuity-bible/generate/cancel', asyncHandler(async (req, res) => {
+ res.json({ canceled: continuityBible.cancelContinuityBible(req.params.id) });
+}));
+
+export default router;
diff --git a/server/routes/pipeline/index.js b/server/routes/pipeline/index.js
index 4bfb27197a..8e5401472d 100644
--- a/server/routes/pipeline/index.js
+++ b/server/routes/pipeline/index.js
@@ -30,6 +30,10 @@
* POST /series/:id/reverse-outline/generate → { runId, alreadyRunning, sseUrl }
* GET /series/:id/reverse-outline/generate/progress → SSE (text/event-stream)
* POST /series/:id/reverse-outline/generate/cancel → { canceled }
+ * GET /series/:id/continuity-bible → { facts, stale, status }
+ * POST /series/:id/continuity-bible/generate → { runId, alreadyRunning, sseUrl }
+ * GET /series/:id/continuity-bible/generate/progress → SSE (text/event-stream)
+ * POST /series/:id/continuity-bible/generate/cancel → { canceled }
* GET /issues/:id/pov-rewrites → { cast, rewrites, hasContent }
* POST /issues/:id/pov-rewrites → { status, rewrite }
* DELETE /issues/:id/pov-rewrites/:rewriteId → { removed }
@@ -50,6 +54,7 @@ import coverRoutes from './covers.js';
import issueRoutes from './issues.js';
import editorialRoutes from './editorial.js';
import reverseOutlineRoutes from './reverseOutline.js';
+import continuityBibleRoutes from './continuityBible.js';
import perspectiveRewriteRoutes from './perspectiveRewrite.js';
import autopilotRoutes from './autopilot.js';
import canonRoutes from './canon.js';
@@ -64,6 +69,7 @@ router.use(coverRoutes);
router.use(issueRoutes);
router.use(editorialRoutes);
router.use(reverseOutlineRoutes);
+router.use(continuityBibleRoutes);
router.use(perspectiveRewriteRoutes);
router.use(autopilotRoutes);
router.use(canonRoutes);
diff --git a/server/services/pipeline/continuityBible.js b/server/services/pipeline/continuityBible.js
new file mode 100644
index 0000000000..47772df397
--- /dev/null
+++ b/server/services/pipeline/continuityBible.js
@@ -0,0 +1,411 @@
+/**
+ * Pipeline — Continuity Bible facts ledger (#1305, PR 1).
+ *
+ * An **established-facts ledger** the manuscript is checked against: concrete,
+ * checkable facts about the story world — character physical traits, ages &
+ * birthdays, dates & elapsed time, locations/geography, possessions/wardrobe,
+ * world rules, and who-knows-what-when. The ledger is **auto-seeded from
+ * universe canon** (locked canon is treated as ground truth) and then **learned
+ * from the drafted prose** via an LLM extraction pass.
+ *
+ * This PR ships the ledger artifact + a browsable "Series Continuity" view. The
+ * four contradiction checks (canon / timeline / knowledge-leak / wardrobe-prop-
+ * injury) that read this ledger land in a follow-up PR against the editorial
+ * check registry (#1284) — the ledger is the substrate they consume.
+ *
+ * Stored as a sibling of the series record at
+ * `data/pipeline-series/{id}/continuity-bible.json` (same pattern as
+ * `reverse-outline.json`) so it travels with the series folder without bloating
+ * the LWW-merged series `index.json`. Two hashes pin the inputs so the UI flags
+ * the ledger stale once either the manuscript (`sourceContentHash`) or the canon
+ * (`sourceCanonHash`) changes. Writes serialize on a per-series tail (single
+ * tail per shared file, per CLAUDE.md). The SSE wrapper mirrors
+ * reverseOutline.js via lib/sseUtils.js.
+ */
+
+import { join } from 'path';
+import { createHash } from 'crypto';
+import { atomicWrite, readJSONFile } from '../../lib/fileUtils.js';
+import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';
+import { createSseRunner } from '../../lib/sseUtils.js';
+import { runStagedLLM, resolveStageContext } from '../../lib/stageRunner.js';
+import { usableInputTokens, estimateTokens, CHARS_PER_TOKEN } from '../../lib/contextBudget.js';
+import { seriesStore, getSeries } from './series.js';
+import { getSeriesCanon } from './seriesCanon.js';
+import { collectManuscriptSections, sectionsCorpus } from './arcPlanner.js';
+
+const STAGE = 'pipeline-continuity-bible';
+
+// Storage-layout version for the ledger document. Bump + migrate if the fact
+// shape changes in a way an older reader can't tolerate.
+const SCHEMA_VERSION = 1;
+
+const LEDGER_FILE = 'continuity-bible.json';
+const ledgerPath = (seriesId) => join(seriesStore().recordDir(seriesId), LEDGER_FILE);
+
+// Ordered fact categories — the buckets the issue enumerates. Order drives the
+// view's section order; ids are the stored `fact.category` values.
+export const FACT_CATEGORIES = Object.freeze([
+ { id: 'physical', label: 'Physical traits' },
+ { id: 'age', label: 'Ages & birthdays' },
+ { id: 'timeline', label: 'Dates & elapsed time' },
+ { id: 'location', label: 'Locations & geography' },
+ { id: 'possession', label: 'Possessions & wardrobe' },
+ { id: 'world-rule', label: 'World rules' },
+ { id: 'knowledge', label: 'Who knows what, when' },
+]);
+const CATEGORY_IDS = new Set(FACT_CATEGORIES.map((c) => c.id));
+
+// Map each canon kind to the fact category it seeds.
+const CANON_KIND_CATEGORY = Object.freeze({ character: 'physical', place: 'location', object: 'possession' });
+
+// Defensive caps on LLM output — never trust raw model JSON.
+const MAX_FACTS = 1_000;
+const SUBJECT_MAX = 120;
+const STATEMENT_MAX = 600;
+const ANCHOR_MAX = 240;
+
+// Floor on manuscript chars sent to the model — scaled UP to the target model's
+// context window in generateContinuityBible (mirrors reverseOutline), so a
+// big-context model reads the whole manuscript rather than a 60K slice.
+const CONTENT_MAX = 60_000;
+const LEDGER_OUTPUT_RESERVE_TOKENS = 6_000;
+
+const nowIso = () => new Date().toISOString();
+const clampStr = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
+
+// Content hash — pins an input so a later edit flips the ledger to `stale`.
+const contentHash = (text) => createHash('sha256').update(text || '').digest('hex');
+
+// Defense-in-depth: refuse path-traversal-shaped ids before they reach the
+// on-disk ledger path. Series ids are `ser-<uuid>` — restrict to a safe charset.
+function assertValidSeriesId(id) {
+ if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(id)) {
+ throw new Error(`Invalid series id: ${id}`);
+ }
+}
+
+// ---------- per-series write tail ----------
+
+const ledgerQueues = new Map();
+function queueLedgerWrite(seriesId, fn) {
+ const key = typeof seriesId === 'string' && seriesId ? seriesId : '__unknown__';
+ let q = ledgerQueues.get(key);
+ if (!q) { q = createFileWriteQueue(); ledgerQueues.set(key, q); }
+ return q(fn);
+}
+
+// ---------- canon seeding ----------
+
+// Stable dedup key for a fact — category + subject + statement, case/space
+// normalized — so a prose fact that merely restates a canon fact is dropped.
+const factKey = (f) => `${f.category}::${(f.subject || '').toLowerCase().trim()}::${(f.statement || '').toLowerCase().trim()}`;
+
+/**
+ * Seed checkable facts directly from universe canon. Each character with a
+ * physical description, each place with a description, and each object with a
+ * description becomes a ground-truth fact. `locked` canon is flagged
+ * `canonical: true` so downstream contradiction checks (PR 2) treat it as
+ * authoritative rather than just one more observation.
+ */
+export function seedFactsFromCanon(canon) {
+ const out = [];
+ const push = (kind, entry, descriptionField) => {
+ const subject = clampStr(entry?.name, SUBJECT_MAX);
+ const statement = clampStr(entry?.[descriptionField], STATEMENT_MAX);
+ if (!subject || !statement) return;
+ out.push({
+ category: CANON_KIND_CATEGORY[kind],
+ subject,
+ statement,
+ source: 'canon',
+ canonical: entry?.locked === true,
+ canonKind: kind,
+ canonEntryId: typeof entry?.id === 'string' ? entry.id : null,
+ issueNumber: null,
+ anchorQuote: null,
+ });
+ };
+ for (const c of Array.isArray(canon?.characters) ? canon.characters : []) push('character', c, 'physicalDescription');
+ for (const p of Array.isArray(canon?.places) ? canon.places : []) push('place', p, 'description');
+ for (const o of Array.isArray(canon?.objects) ? canon.objects : []) push('object', o, 'description');
+ return out;
+}
+
+// ---------- sanitize LLM output ----------
+
+// Shape one prose-extracted fact. Returns null for anything missing a category,
+// subject, or statement so the ledger never carries half-facts.
+function sanitizeProseFact(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ const category = typeof raw.category === 'string' && CATEGORY_IDS.has(raw.category) ? raw.category : null;
+ const subject = clampStr(raw.subject, SUBJECT_MAX);
+ const statement = clampStr(raw.statement, STATEMENT_MAX);
+ if (!category || !subject || !statement) return null;
+ return {
+ category,
+ subject,
+ statement,
+ source: 'prose',
+ canonical: false,
+ canonKind: null,
+ canonEntryId: null,
+ issueNumber: Number.isInteger(raw.issueNumber) ? raw.issueNumber : null,
+ anchorQuote: clampStr(raw.anchorQuote, ANCHOR_MAX) || null,
+ };
+}
+
+/**
+ * Merge canon-seeded facts with prose-extracted facts. Canon facts come first
+ * (ground truth), then prose facts whose (category, subject, statement) key
+ * isn't already present. Ids are assigned stably by final position. Exported
+ * via __testing.
+ */
+function buildFacts(canonFacts, parsed) {
+ const merged = [];
+ const seen = new Set();
+ const add = (f) => {
+ const key = factKey(f);
+ if (seen.has(key)) return;
+ seen.add(key);
+ merged.push(f);
+ };
+ for (const f of Array.isArray(canonFacts) ? canonFacts : []) add(f);
+ const rawProse = Array.isArray(parsed?.facts) ? parsed.facts : [];
+ for (const raw of rawProse) {
+ if (merged.length >= MAX_FACTS) break;
+ const f = sanitizeProseFact(raw);
+ if (f) add(f);
+ }
+ return merged
+ .slice(0, MAX_FACTS)
+ .map((f, idx) => ({ id: `fact-${String(idx + 1).padStart(3, '0')}`, ...f }));
+}
+
+// ---------- storage ----------
+
+const emptyLedger = () => ({ schemaVersion: SCHEMA_VERSION, status: 'none', facts: [] });
+
+async function readLedger(seriesId) {
+ // `null` = file absent (distinct from a present-but-empty ledger).
+ const raw = await readJSONFile(ledgerPath(seriesId), null);
+ if (raw == null || typeof raw !== 'object') return null;
+ return raw;
+}
+
+async function writeLedger(seriesId, ledger) {
+ await atomicWrite(ledgerPath(seriesId), ledger);
+}
+
+// ---------- input corpus + hashes ----------
+
+// Stitch the drafted manuscript into one corpus + the number→section map. The
+// canon is hashed off a stable shape (the seeded facts) so a canon edit that
+// changes a description flips the ledger to stale just like a prose edit.
+async function buildInputs(seriesId) {
+ const sections = await collectManuscriptSections(seriesId);
+ const byNumber = new Map(sections.map((s) => [s.number, s]));
+ const series = await getSeries(seriesId).catch(() => null);
+ const canon = series ? await getSeriesCanon(series).catch(() => null) : null;
+ const canonFacts = seedFactsFromCanon(canon || {});
+ return {
+ series,
+ corpus: sectionsCorpus(sections),
+ byNumber,
+ canonFacts,
+ canonHash: contentHash(JSON.stringify(canonFacts)),
+ };
+}
+
+// ---------- generation ----------
+
+/**
+ * Generate (or refresh) the continuity-bible facts ledger for a series. Returns
+ * the stored ledger, a `{ status:'no-content' }` marker when there's no canon
+ * AND no drafted prose to learn from, or the cached ledger when both inputs are
+ * unchanged and `!force`.
+ *
+ * @param {string} seriesId
+ * @param {object} [options]
+ * - providerId / model — forwarded to the LLM stage (autopilot/manual override)
+ * - force — re-extract even when both input hashes are unchanged
+ * - signal — AbortSignal checked before the persist
+ */
+export async function generateContinuityBible(seriesId, { providerId, model, force = false, signal } = {}) {
+ assertValidSeriesId(seriesId);
+ const { series, corpus, byNumber, canonFacts, canonHash } = await buildInputs(seriesId);
+ const hasProse = corpus.trim().length > 0;
+ if (!hasProse && canonFacts.length === 0) return { seriesId, status: 'no-content' };
+
+ const hash = contentHash(corpus);
+ const existing = await readLedger(seriesId);
+ if (
+ !force && existing && existing.status === 'complete' &&
+ existing.sourceContentHash === hash && existing.sourceCanonHash === canonHash
+ ) {
+ return { ...existing, stale: false, cached: true };
+ }
+
+ // Extract facts from prose only when there's prose to read; an empty draft
+ // still produces a canon-only ledger (no wasted LLM call).
+ let parsed = { facts: [] };
+ let result = { providerId, model, runId: null };
+ let truncated = false;
+ if (hasProse) {
+ const characterNames = (canonFacts.filter((f) => f.canonKind === 'character').map((f) => f.subject)).slice(0, 60);
+ const { contextWindow } = await resolveStageContext(STAGE, { providerOverride: providerId, modelOverride: model });
+ const overheadTokens = 1_500 + estimateTokens([series?.name || '', characterNames.join(', ')].join(' '));
+ const budgetChars = usableInputTokens({
+ contextWindow,
+ overheadTokens,
+ outputReserveTokens: LEDGER_OUTPUT_RESERVE_TOKENS,
+ }) * CHARS_PER_TOKEN;
+ const contentMax = Math.max(CONTENT_MAX, budgetChars);
+ truncated = corpus.length > contentMax;
+
+ const vars = {
+ series: { name: series?.name || 'Untitled series', styleNotes: series?.styleNotes || '' },
+ knownCharacters: characterNames.length ? characterNames.join(', ') : '(none on record)',
+ categories: FACT_CATEGORIES.map((c) => `- ${c.id}: ${c.label}`).join('\n'),
+ manuscript: truncated
+ ? `${corpus.slice(0, contentMax)}\n\n[manuscript truncated for analysis — ${corpus.length} chars total]`
+ : corpus,
+ };
+
+ result = await runStagedLLM(STAGE, vars, {
+ returnsJson: true,
+ providerOverride: providerId,
+ modelOverride: model,
+ source: 'pipeline-continuity-bible',
+ });
+ parsed = result.content;
+ if (signal?.aborted) return { seriesId, status: 'canceled' };
+ // Drop any model-reported issueNumber that doesn't match a real manuscript
+ // section, so a hallucinated number can't render a dead "Open issue" deep-link.
+ if (parsed && Array.isArray(parsed.facts)) {
+ for (const f of parsed.facts) {
+ if (f && Number.isInteger(f.issueNumber) && !byNumber.has(f.issueNumber)) f.issueNumber = null;
+ }
+ }
+ }
+
+ const facts = buildFacts(canonFacts, parsed);
+ const ledger = {
+ seriesId,
+ schemaVersion: SCHEMA_VERSION,
+ status: 'complete',
+ sourceContentHash: hash,
+ sourceCanonHash: canonHash,
+ truncated,
+ providerId: result.providerId || providerId || null,
+ model: result.model || model || null,
+ runId: result.runId || null,
+ generatedAt: nowIso(),
+ facts,
+ };
+ await queueLedgerWrite(seriesId, () => writeLedger(seriesId, ledger));
+ const canonCount = facts.filter((f) => f.source === 'canon').length;
+ console.log(`📖 continuity bible: series=${String(seriesId).slice(0, 12)} facts=${facts.length} (canon=${canonCount}, prose=${facts.length - canonCount})`);
+ return { ...ledger, stale: false };
+}
+
+// Single source of truth for staleness — a stored hash no longer matches its
+// current input (manuscript or canon). A legacy ledger missing a hash is treated
+// as not-stale for that input (can't tell).
+function isLedgerStale(ledger, { hash, canonHash }) {
+ if (!ledger || ledger.status !== 'complete') return false;
+ if (ledger.sourceContentHash && ledger.sourceContentHash !== hash) return true;
+ if (ledger.sourceCanonHash && ledger.sourceCanonHash !== canonHash) return true;
+ return false;
+}
+
+/**
+ * Read the stored ledger with a `stale` flag. Returns a shell (never null) when
+ * one has never been generated, so the route/UI has a consistent shape — and
+ * distinguishes `none` (no ledger yet, but there IS canon or draftable prose)
+ * from `no-content` (nothing to build a ledger from at all).
+ */
+export async function getContinuityBible(seriesId) {
+ assertValidSeriesId(seriesId);
+ const ledger = await readLedger(seriesId);
+ const { corpus, canonFacts, canonHash } = await buildInputs(seriesId);
+ const hasContent = corpus.trim().length > 0 || canonFacts.length > 0;
+ // Ship the category list with every response so the view renders the labels
+ // the server defines (mirrors reverseOutline shipping `plotlines`) — no
+ // hand-synced copy on the client to drift when a category is added/renamed.
+ if (!ledger) {
+ return { ...emptyLedger(), seriesId, categories: FACT_CATEGORIES, status: hasContent ? 'none' : 'no-content' };
+ }
+ return { ...ledger, seriesId, categories: FACT_CATEGORIES, stale: isLedgerStale(ledger, { hash: contentHash(corpus), canonHash }) };
+}
+
+/**
+ * Canonical facts-ledger accessor for downstream editorial checks (PR 2:
+ * canon-contradiction, timeline, knowledge-leak, wardrobe/prop/injury). Returns
+ * the stored facts (empty when never generated) plus a `stale` flag so a
+ * consumer can decide whether to trust or regenerate.
+ */
+export async function getFactsLedger(seriesId) {
+ const ledger = await getContinuityBible(seriesId);
+ return {
+ seriesId,
+ facts: ledger.facts || [],
+ status: ledger.status || 'none',
+ stale: ledger.stale === true,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// SSE run-tracking — shared lifecycle via createSseRunner (server/lib/sseUtils.js),
+// the same factory backing reverseOutline + editorial/checkRunner.
+// ---------------------------------------------------------------------------
+
+const runner = createSseRunner({ logLabel: 'continuity bible' });
+
+export function isContinuityBibleActive(seriesId) {
+ return runner.isActive(seriesId);
+}
+
+export function attachClient(seriesId, res) {
+ return runner.attachClient(seriesId, res);
+}
+
+export function cancelContinuityBible(seriesId) {
+ return runner.cancel(seriesId);
+}
+
+/**
+ * Kick off a streamed continuity-bible generation. Returns the runId
+ * immediately; progress + the terminal frame land via SSE. Re-calling while a
+ * run is in flight resolves to the existing runId.
+ */
+export function startContinuityBibleRun(seriesId, options = {}) {
+ return runner.start(seriesId, async ({ runId, signal, record, broadcast }) => {
+ broadcast({ type: 'start', runId });
+ const result = await generateContinuityBible(seriesId, {
+ providerId: options.providerId,
+ model: options.model,
+ force: options.force,
+ signal,
+ });
+ if (record.cancelRequested || result.status === 'canceled') {
+ broadcast({ type: 'canceled', runId, canceledAt: nowIso() });
+ console.log(`📖 continuity bible canceled — series=${String(seriesId).slice(0, 12)}`);
+ return;
+ }
+ if (result.status === 'no-content') {
+ broadcast({ type: 'complete', runId, status: 'no-content', factCount: 0, completedAt: nowIso() });
+ return;
+ }
+ broadcast({
+ type: 'complete',
+ runId,
+ status: 'complete',
+ factCount: result.facts?.length || 0,
+ completedAt: nowIso(),
+ });
+ });
+}
+
+// Export internals for tests.
+export const __testing = { seedFactsFromCanon, sanitizeProseFact, buildFacts, isLedgerStale, contentHash, factKey, runs: runner.runs };
diff --git a/server/services/pipeline/continuityBible.test.js b/server/services/pipeline/continuityBible.test.js
new file mode 100644
index 0000000000..d0c4f9ec13
--- /dev/null
+++ b/server/services/pipeline/continuityBible.test.js
@@ -0,0 +1,224 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// In-memory ledger store mirroring atomicWrite(object) + readJSONFile(object|fallback).
+const fileStore = new Map();
+
+vi.mock('../../lib/fileUtils.js', () => ({
+ atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, JSON.parse(JSON.stringify(data))); }),
+ readJSONFile: vi.fn(async (path, fallback = null) => (fileStore.has(path) ? fileStore.get(path) : fallback)),
+}));
+
+// runStagedLLM returns the next queued canned ledger.
+const llmQueue = [];
+const llmCalls = [];
+vi.mock('../../lib/stageRunner.js', () => ({
+ runStagedLLM: vi.fn(async (stage, vars) => {
+ llmCalls.push({ stage, vars });
+ const content = llmQueue.shift();
+ return { content, model: 'mock-model', providerId: 'mock-provider', runId: 'run-1' };
+ }),
+ resolveStageContext: vi.fn(async () => ({ provider: { id: 'mock-provider' }, model: 'mock-model', contextWindow: 1_000_000 })),
+}));
+
+vi.mock('../../lib/contextBudget.js', () => ({
+ usableInputTokens: vi.fn(() => 100_000),
+ estimateTokens: vi.fn(() => 100),
+ CHARS_PER_TOKEN: 4,
+}));
+
+const seriesFixture = new Map();
+vi.mock('./series.js', () => ({
+ seriesStore: () => ({ recordDir: (id) => `/mock/series/${id}` }),
+ getSeries: vi.fn(async (id) => seriesFixture.get(id) || null),
+}));
+
+// Canon fixture — driven per-test.
+let canonFixture = { characters: [], places: [], objects: [] };
+vi.mock('./seriesCanon.js', () => ({
+ getSeriesCanon: vi.fn(async () => canonFixture),
+}));
+
+// Manuscript corpus — driven per-test.
+let sectionsFixture = [];
+vi.mock('./arcPlanner.js', () => ({
+ collectManuscriptSections: vi.fn(async () => sectionsFixture),
+ sectionsCorpus: (sections) => sections.map((s) => `# Issue ${s.number}\n\n${s.content}`).join('\n\n---\n\n'),
+}));
+
+const svc = await import('./continuityBible.js');
+
+const SERIES_ID = 'ser-abc';
+
+function cannedLedger() {
+ return {
+ facts: [
+ { category: 'physical', subject: 'Mara', statement: 'Has green eyes', issueNumber: 1, anchorQuote: 'her green eyes' },
+ { category: 'knowledge', subject: 'Dov', statement: 'Knows the safehouse address', issueNumber: 2, anchorQuote: 'Dov memorized it' },
+ { category: 'bogus-cat', subject: 'X', statement: 'dropped — bad category' }, // dropped
+ { category: 'age', subject: '', statement: 'no subject' }, // dropped (no subject)
+ { nonsense: true }, // dropped
+ ],
+ };
+}
+
+beforeEach(() => {
+ fileStore.clear();
+ llmQueue.length = 0;
+ llmCalls.length = 0;
+ sectionsFixture = [{ issueId: 'iss-1', number: 1, title: 'One', stageId: 'prose', content: 'It was dusk on the pier.' }];
+ canonFixture = {
+ characters: [{ id: 'char-1', name: 'Mara', physicalDescription: 'Tall, green eyes', locked: true }],
+ places: [{ id: 'place-1', name: 'The Pier', description: 'A rotting harbor pier' }],
+ objects: [],
+ };
+ seriesFixture.clear();
+ seriesFixture.set(SERIES_ID, { id: SERIES_ID, name: 'Test Series', styleNotes: 'noir', universeId: 'uni-1' });
+});
+
+describe('generateContinuityBible', () => {
+ it('seeds facts from canon, learns from prose, drops bad facts, assigns stable ids', async () => {
+ llmQueue.push(cannedLedger());
+ const out = await svc.generateContinuityBible(SERIES_ID, {});
+
+ expect(out.status).toBe('complete');
+ expect(out.sourceContentHash).toBeTruthy();
+ expect(out.sourceCanonHash).toBeTruthy();
+
+ // Canon seeds: locked character → physical (canonical), place → location.
+ const mara = out.facts.find((f) => f.subject === 'Mara' && f.source === 'canon');
+ expect(mara.category).toBe('physical');
+ expect(mara.canonical).toBe(true);
+ expect(mara.canonEntryId).toBe('char-1');
+ const pier = out.facts.find((f) => f.subject === 'The Pier' && f.source === 'canon');
+ expect(pier.category).toBe('location');
+ expect(pier.canonical).toBe(false); // place not locked
+
+ // Prose facts merged; bad-category / no-subject / nonsense dropped.
+ const dov = out.facts.find((f) => f.subject === 'Dov');
+ expect(dov.source).toBe('prose');
+ expect(dov.category).toBe('knowledge');
+ expect(dov.issueNumber).toBeNull(); // canned issueNumber 2 has no matching section → dropped
+ expect(out.facts.some((f) => f.subject === 'X')).toBe(false);
+
+ // Stable ids.
+ expect(out.facts[0].id).toBe('fact-001');
+ });
+
+ it('builds a canon-only ledger without an LLM call when nothing is drafted', async () => {
+ sectionsFixture = [];
+ const out = await svc.generateContinuityBible(SERIES_ID, {});
+ expect(out.status).toBe('complete');
+ expect(llmCalls).toHaveLength(0); // no prose → no extraction call
+ expect(out.facts.length).toBe(2); // Mara + The Pier from canon
+ expect(out.facts.every((f) => f.source === 'canon')).toBe(true);
+ });
+
+ it('returns no-content when there is neither canon nor prose', async () => {
+ sectionsFixture = [];
+ canonFixture = { characters: [], places: [], objects: [] };
+ const out = await svc.generateContinuityBible(SERIES_ID, {});
+ expect(out.status).toBe('no-content');
+ expect(llmCalls).toHaveLength(0);
+ });
+
+ it('returns the cached ledger when inputs are unchanged and not forced', async () => {
+ llmQueue.push(cannedLedger());
+ await svc.generateContinuityBible(SERIES_ID, {});
+ const again = await svc.generateContinuityBible(SERIES_ID, {});
+ expect(again.cached).toBe(true);
+ expect(llmCalls).toHaveLength(1);
+ });
+
+ it('re-extracts when forced even if inputs are unchanged', async () => {
+ llmQueue.push(cannedLedger(), cannedLedger());
+ await svc.generateContinuityBible(SERIES_ID, {});
+ await svc.generateContinuityBible(SERIES_ID, { force: true });
+ expect(llmCalls).toHaveLength(2);
+ });
+});
+
+describe('getContinuityBible + staleness', () => {
+ it('returns a none shell (with category labels) when never generated but canon exists', async () => {
+ const out = await svc.getContinuityBible(SERIES_ID);
+ expect(out.status).toBe('none');
+ expect(out.facts).toEqual([]);
+ // Categories ship with every response so the client never hand-syncs them.
+ expect(out.categories.map((c) => c.id)).toContain('knowledge');
+ });
+
+ it('returns no-content (not none) when there is nothing to ledger', async () => {
+ sectionsFixture = [];
+ canonFixture = { characters: [], places: [], objects: [] };
+ const out = await svc.getContinuityBible(SERIES_ID);
+ expect(out.status).toBe('no-content');
+ });
+
+ it('flags stale when the manuscript changes after generation', async () => {
+ llmQueue.push(cannedLedger());
+ await svc.generateContinuityBible(SERIES_ID, {});
+ expect((await svc.getContinuityBible(SERIES_ID)).stale).toBe(false);
+
+ sectionsFixture = [{ issueId: 'iss-1', number: 1, title: 'One', stageId: 'prose', content: 'A completely rewritten draft.' }];
+ expect((await svc.getContinuityBible(SERIES_ID)).stale).toBe(true);
+ });
+
+ it('flags stale when canon changes after generation', async () => {
+ llmQueue.push(cannedLedger());
+ await svc.generateContinuityBible(SERIES_ID, {});
+ expect((await svc.getContinuityBible(SERIES_ID)).stale).toBe(false);
+
+ canonFixture = {
+ characters: [{ id: 'char-1', name: 'Mara', physicalDescription: 'Tall, BLUE eyes', locked: true }],
+ places: [{ id: 'place-1', name: 'The Pier', description: 'A rotting harbor pier' }],
+ objects: [],
+ };
+ expect((await svc.getContinuityBible(SERIES_ID)).stale).toBe(true);
+ });
+});
+
+describe('getFactsLedger', () => {
+ it('exposes the stored facts for downstream checks', async () => {
+ llmQueue.push(cannedLedger());
+ await svc.generateContinuityBible(SERIES_ID, {});
+ const led = await svc.getFactsLedger(SERIES_ID);
+ expect(led.status).toBe('complete');
+ expect(led.facts.length).toBeGreaterThan(0);
+ });
+
+ it('returns empty when never generated', async () => {
+ const led = await svc.getFactsLedger(SERIES_ID);
+ expect(led.status).toBe('none');
+ expect(led.facts).toEqual([]);
+ });
+});
+
+describe('pure helpers (__testing)', () => {
+ const { seedFactsFromCanon, buildFacts, sanitizeProseFact } = svc.__testing;
+
+ it('seedFactsFromCanon maps kinds to categories and respects locked', () => {
+ const facts = seedFactsFromCanon({
+ characters: [{ id: 'c1', name: 'A', physicalDescription: 'tall', locked: true }, { name: 'NoDesc' }],
+ places: [{ id: 'p1', name: 'Town', description: 'small' }],
+ objects: [{ id: 'o1', name: 'Sword', description: 'sharp', locked: false }],
+ });
+ expect(facts).toHaveLength(3); // NoDesc dropped (no description)
+ expect(facts.find((f) => f.subject === 'A')).toMatchObject({ category: 'physical', canonical: true });
+ expect(facts.find((f) => f.subject === 'Town')).toMatchObject({ category: 'location' });
+ expect(facts.find((f) => f.subject === 'Sword')).toMatchObject({ category: 'possession', canonical: false });
+ });
+
+ it('buildFacts dedups a prose fact that merely restates a canon fact', () => {
+ const canonFacts = seedFactsFromCanon({ characters: [{ id: 'c1', name: 'Mara', physicalDescription: 'green eyes' }] });
+ const merged = buildFacts(canonFacts, {
+ facts: [{ category: 'physical', subject: 'mara', statement: 'GREEN EYES' }], // case/space dup
+ });
+ expect(merged).toHaveLength(1);
+ expect(merged[0].source).toBe('canon');
+ });
+
+ it('sanitizeProseFact rejects unknown categories and half-facts', () => {
+ expect(sanitizeProseFact({ category: 'nope', subject: 'X', statement: 'Y' })).toBeNull();
+ expect(sanitizeProseFact({ category: 'physical', subject: '', statement: 'Y' })).toBeNull();
+ expect(sanitizeProseFact({ category: 'physical', subject: 'X', statement: 'Y' })).toMatchObject({ source: 'prose' });
+ });
+});