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

add reveal-gated canon (spoiler scoping) + continuity.premature-reveal check

[._.]/ Adam Eivyc51b0bc9b866
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0403d8f81a..65e8a18226 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -26,6 +26,7 @@
- **[issue-2170] A simulated four-persona reader panel now reads your whole series and shows you where the readers disagree.** Convene the panel from a new **Reader Panel** tab on the Reader Map page (deep-linkable via `?tab=panel`) and four distinct readers — The Editor (prose texture, subtext, over-explaining), The Genre Reader (pacing and page-turn pull, "gets bored by beautiful prose that doesn't GO anywhere"), The Writer (structure, beats, foreshadowing payoff, whose worst insult is "I can see the outline"), and The First Reader (pure emotional response, no craft vocabulary) — each read a condensed, content-hash-pinned arc digest of the series (per-issue summary, opening/closing excerpts, and notable dialogue) and answer the same ten qualitative questions (where momentum is lost, is the ending earned, what to cut, a missing scene, the thinnest character, best/worst scene, would-recommend, what haunts you, would-read-the-next-book), citing specific issue numbers. The editorial signal is where they *disagree*: an issue flagged by 3+ personas is routed straight into your editorial-findings triage flow as a consensus concern; softer some-flagged-some-didn't calls and "polarizing" issues (one persona's best scene is another's worst) are surfaced for your judgment. One LLM call per persona, run only from the explicit Convene button — nothing fires on its own.
- **[issue-2175] Worldbuilding craft doctrine now shapes universe generation up-front, and two new editorial checks verify it.** The universe-expansion prompt now injects Sanderson's-Laws craft doctrine before the writer model drafts — limitations over powers, costs that drive plot decisions, solutions foreshadowed before they resolve, iceberg depth, interconnected systems, 2–3 societal implications per major system, and a sensory signature per location — so autonomous and interactive runs alike start from a lived-in world instead of decorative set dressing (Series Autopilot calls the same stages, so autonomous mode is upgraded automatically). Two new series-scope editorial checks close the loop on the review side: `world.unforeshadowed-solution` (a plot problem solved by a rule/power the reader was never shown — the worldbuilding sibling of the deus ex machina) and `world.cost-free-power` (an ability used at a decisive moment with no cost or limitation on the page). Both reconcile the prose against the established world canon and the continuity-bible world-rule facts, so a rule that WAS planted earlier is not flagged. (First slice of #2175 — the character-framework and structure-rule pillars ship separately.)
- **[issue-2179] A series style guide can now carry concrete voice exemplar and anti-exemplar passages — "the tuning fork" — that get injected into every draft and revision prompt.** Adjective lists ("witty, atmospheric") anchor prose voice far more weakly than an actual passage does, so the series style guide gains two new fields: `voiceExemplars` (1–3 short passages that nail the target voice, each with an optional one-line note on what it demonstrates) and `voiceAntiExemplars` (passages in the wrong register kept as negative examples, noted with what's wrong — "too ornate", "wrong emotional temperature"). Add and edit them inline on the series style-guide editor. On generation they render into the house-style block as a "MATCH this voice — echo their rhythm, diction, and register" block and a "NEVER drift toward this" block — conditional, so a guide with no passages injects nothing. They ride the existing `{{series.styleNotes}}` template variable (via `composeStyleNotes`), so prose drafting, revision, arc planning, and episode-seed passes all honor them with no new prompt-template variable and no migration. The sanitizer drops empty passages, trims each to ~2000 chars, and caps the list at 3 so the fixed per-call prompt overhead stays tight. (First slice of #2179 — the AI-assisted voice-discovery flow, Writers Room parity, and the voice-fingerprint baseline hook ship separately.)
+- **[issue-2178] Canon can now be reveal-gated so a mystery or twist doesn't leak into the prose before it's due.** Canon context — including character secrets and late-story facts — was injected into every issue's drafting prompt, so the writer model could (and would) spill a reveal issues early. Each canon entry (character, place, or object) now carries optional reveal gating: a `revealIssue` number hides the fact from any issue before it; a `spoiler` flag hard-hides it from all drafting context; and an optional `surfaceDescriptor` is the spoiler-free stand-in shown before the reveal ("the locked east wing" instead of "the wing where the heir is imprisoned"). The drafting/rewrite prompts (`buildStageContext`, the alternate-POV rewrite cast) filter canon to each issue's reveal horizon, while the judge and editorial checks still receive the full canon so they can verify hint placement. Absent gate fields mean "always visible," so every existing canon entry and every federation peer round-trips unchanged. A reveal-timing editor with a spoiler badge lands on every canon-entry card (universe + series). A new `continuity.premature-reveal` editorial check (gated on the series having authored any reveal-gated canon) scans drafted prose for a gated fact stated or unambiguously implied before its reveal issue, distinguishing a genuine leak from deliberate foreshadowing — and its reveal issue feeds the Chekhov setups-payoffs check as an authored payoff so an orphaned reveal is flagged too.
## Human Activity Tracking
diff --git a/client/src/components/pipeline/CanonCard.jsx b/client/src/components/pipeline/CanonCard.jsx
index 7ec3e49a77..a327c2fc8d 100644
--- a/client/src/components/pipeline/CanonCard.jsx
+++ b/client/src/components/pipeline/CanonCard.jsx
@@ -23,6 +23,7 @@ import CharacterDetailEditor from '../universe/CharacterDetailEditor';
import ObjectAttachmentsEditor from '../universe/ObjectAttachmentsEditor';
import CharacterReferenceSheetPanel from '../universe/CharacterReferenceSheetPanel';
import CharacterLoraChip from '../loraTraining/CharacterLoraChip';
+import Pill from '../ui/Pill';
import { BIBLE_LIMITS } from '../../lib/bibleLimits';
// Place metadata enums — kept in lock-step with `PLACE_INT_EXT` and
@@ -98,6 +99,113 @@ function ReadonlyChip({ children }) {
);
}
+// A canon entry is reveal-gated (#2178) when it carries a hard `spoiler` flag
+// or a numeric `revealIssue`. Mirrors the server's `isEntryRevealGated`.
+const isEntryGated = (entry) => entry?.spoiler === true || Number.isInteger(entry?.revealIssue);
+
+// Spoiler badge shown in the card title when an entry is reveal-gated (#2178).
+// Purely informational; the gating itself happens server-side in
+// `buildStageContext`. Uses the shared `Pill` primitive (warning tone).
+function SpoilerBadge({ entry }) {
+ if (!isEntryGated(entry)) return null;
+ const label = entry.spoiler === true ? 'spoiler' : `reveal #${entry.revealIssue}`;
+ const title = entry.spoiler === true
+ ? 'Hard spoiler — hidden from every issue’s drafting prompt'
+ : `Hidden from drafting context until Issue ${entry.revealIssue}`;
+ return (
+ <Pill tone="warning" size="xs" title={title} className="rounded-full uppercase tracking-wider">
+ {label}
+ </Pill>
+ );
+}
+
+// Reveal-timing editor (#2178) — sets when a canon fact may enter a drafting
+// prompt. Applies to every kind. `revealIssue` (int) hides the entry from
+// issues before that number; `spoiler` hard-hides it from all drafting;
+// `surfaceDescriptor` is the pre-reveal stand-in substituted into context.
+// Absent = always visible (backward-compatible default). Labels are
+// `htmlFor`/`id` paired per the accessibility convention.
+function RevealTimingField({ entry, editable, onPatch }) {
+ const idBase = `reveal-${entry.id}`;
+ const surfaceDraft = useFieldDraft(
+ typeof entry.surfaceDescriptor === 'string' ? entry.surfaceDescriptor : '',
+ (v) => onPatch({ surfaceDescriptor: v || null }),
+ );
+ const gated = isEntryGated(entry);
+ if (!editable) {
+ if (!gated) return null;
+ return (
+ <div className="mt-2 flex flex-wrap items-center gap-2 text-[10px] text-gray-500">
+ <span className="uppercase tracking-wider">Reveal:</span>
+ {entry.spoiler === true
+ ? <ReadonlyChip>hard spoiler</ReadonlyChip>
+ : <ReadonlyChip>Issue {entry.revealIssue}</ReadonlyChip>}
+ {entry.surfaceDescriptor
+ ? <span className="italic text-gray-500">surface: {entry.surfaceDescriptor}</span>
+ : null}
+ </div>
+ );
+ }
+ return (
+ <details className="mt-2 group">
+ <summary className="cursor-pointer list-none flex items-center gap-1 text-[10px] uppercase tracking-wider text-gray-500 hover:text-gray-300">
+ <ChevronRight size={11} className="group-open:hidden" />
+ <ChevronDown size={11} className="hidden group-open:inline" />
+ Reveal timing (spoiler scoping)
+ {gated ? <span className="ml-1 text-port-warning normal-case tracking-normal">· gated</span> : null}
+ </summary>
+ <div className="mt-1.5 space-y-2 pl-3 border-l border-port-border">
+ <div className="flex flex-wrap items-center gap-3">
+ <div className="flex flex-col gap-0.5">
+ <label htmlFor={`${idBase}-issue`} className="text-[10px] uppercase tracking-wider text-gray-500">
+ Reveal in issue #
+ </label>
+ <input
+ id={`${idBase}-issue`}
+ type="number"
+ min={1}
+ max={BIBLE_LIMITS.REVEAL_ISSUE_MAX}
+ value={Number.isInteger(entry.revealIssue) ? entry.revealIssue : ''}
+ onChange={(e) => {
+ const v = e.target.value.trim();
+ const n = v === '' ? null : Math.trunc(Number(v));
+ onPatch({ revealIssue: Number.isInteger(n) && n >= 1 ? n : null });
+ }}
+ placeholder="—"
+ className="w-20 px-2 py-1 text-xs bg-port-bg border border-port-border rounded text-gray-200"
+ />
+ </div>
+ <label htmlFor={`${idBase}-spoiler`} className="flex items-center gap-1.5 text-[11px] text-gray-400 mt-3">
+ <input
+ id={`${idBase}-spoiler`}
+ type="checkbox"
+ checked={entry.spoiler === true}
+ onChange={(e) => onPatch({ spoiler: e.target.checked })}
+ className="accent-port-warning"
+ />
+ Hard spoiler (never in drafting)
+ </label>
+ </div>
+ <div className="flex flex-col gap-0.5">
+ <label htmlFor={`${idBase}-surface`} className="text-[10px] uppercase tracking-wider text-gray-500">
+ Surface descriptor (pre-reveal stand-in)
+ </label>
+ <textarea
+ id={`${idBase}-surface`}
+ value={surfaceDraft.value}
+ onChange={surfaceDraft.onChange}
+ onBlur={surfaceDraft.onBlur}
+ rows={2}
+ maxLength={BIBLE_LIMITS.SURFACE_DESCRIPTOR_MAX}
+ placeholder="What the world looks like BEFORE the reveal (e.g. &quot;the locked east wing&quot;). Substituted into drafting context until the reveal issue."
+ className="w-full px-2 py-1 text-xs bg-port-bg border border-port-border rounded text-gray-200 whitespace-pre-wrap"
+ />
+ </div>
+ </div>
+ </details>
+ );
+}
+
// Collapsible wrapper for the universe-only character details panel
// (CharacterDetailEditor + CharacterReferenceSheetPanel). Single toggle so the
// card stays terse by default — the user opens it only when filling in
@@ -346,6 +454,7 @@ export default function CanonCard({
seriesName={seriesNameMap?.[entry.sourceSeriesId]}
/>
) : null}
+ <SpoilerBadge entry={entry} />
</div>
);
@@ -390,6 +499,13 @@ export default function CanonCard({
{entry.timeOfDay ? <ReadonlyChip>{entry.timeOfDay}</ReadonlyChip> : null}
</div>
) : null}
+ {/* Reveal-gated canon / spoiler scoping (#2178) — every kind. Editable
+ when a PATCH channel exists and the entry isn't locked. */}
+ <RevealTimingField
+ entry={entry}
+ editable={!!onPatchEntry && !locked}
+ onPatch={(patch) => onPatchEntry?.(entry.id, patch)}
+ />
{kind.key === 'characters' ? (
<WardrobeSection
wardrobes={Array.isArray(entry.wardrobes) ? entry.wardrobes : []}
diff --git a/client/src/components/pipeline/CanonCard.test.jsx b/client/src/components/pipeline/CanonCard.test.jsx
index 7582e6cc98..3c4748316e 100644
--- a/client/src/components/pipeline/CanonCard.test.jsx
+++ b/client/src/components/pipeline/CanonCard.test.jsx
@@ -154,6 +154,69 @@ describe('CanonCard — inline description editor', () => {
});
});
+describe('CanonCard — reveal timing / spoiler scoping (#2178)', () => {
+ const editableKind = {
+ key: 'characters', label: 'Characters',
+ descFor: (e) => e.physicalDescription || e.description || '',
+ descField: 'physicalDescription', descFieldFallback: 'description', descFieldMax: 2000,
+ };
+
+ it('shows a spoiler badge when the entry has a revealIssue', () => {
+ render_({ entry: { ...baseEntry, revealIssue: 8 } });
+ expect(screen.getByText('reveal #8')).toBeInTheDocument();
+ });
+
+ it('shows a hard-spoiler badge when the entry has spoiler: true', () => {
+ render_({ entry: { ...baseEntry, spoiler: true } });
+ expect(screen.getByText('spoiler')).toBeInTheDocument();
+ });
+
+ it('omits the badge for an ungated entry', () => {
+ render_();
+ expect(screen.queryByText(/^reveal #/)).not.toBeInTheDocument();
+ expect(screen.queryByText('spoiler')).not.toBeInTheDocument();
+ });
+
+ it('PATCHes revealIssue from the number input when editable', () => {
+ const onPatchEntry = vi.fn();
+ render(
+ <CanonCard kind={editableKind} entry={baseEntry} onRender={() => {}} onPatchEntry={onPatchEntry} />,
+ );
+ fireEvent.click(screen.getByText(/Reveal timing/));
+ const input = screen.getByLabelText(/Reveal in issue/);
+ fireEvent.change(input, { target: { value: '8' } });
+ expect(onPatchEntry).toHaveBeenCalledWith('ent-1', { revealIssue: 8 });
+ });
+
+ it('PATCHes spoiler from the checkbox and surfaceDescriptor on blur', () => {
+ const onPatchEntry = vi.fn();
+ render(
+ <CanonCard kind={editableKind} entry={baseEntry} onRender={() => {}} onPatchEntry={onPatchEntry} />,
+ );
+ fireEvent.click(screen.getByText(/Reveal timing/));
+ fireEvent.click(screen.getByLabelText(/Hard spoiler/));
+ expect(onPatchEntry).toHaveBeenCalledWith('ent-1', { spoiler: true });
+
+ const surface = screen.getByLabelText(/Surface descriptor/);
+ fireEvent.change(surface, { target: { value: 'a quiet neighbor' } });
+ fireEvent.blur(surface);
+ expect(onPatchEntry).toHaveBeenCalledWith('ent-1', { surfaceDescriptor: 'a quiet neighbor' });
+ });
+
+ it('renders read-only reveal info when locked (no editor inputs)', () => {
+ render(
+ <CanonCard
+ kind={editableKind}
+ entry={{ ...baseEntry, revealIssue: 5, locked: true }}
+ onRender={() => {}}
+ onPatchEntry={vi.fn()}
+ />,
+ );
+ expect(screen.getByText('Issue 5')).toBeInTheDocument();
+ expect(screen.queryByLabelText(/Reveal in issue/)).not.toBeInTheDocument();
+ });
+});
+
describe('CanonCard — wardrobe pending-row promotion', () => {
const renderEditable = (onPatchEntry) => render(
<CanonCard
diff --git a/client/src/lib/bibleLimits.js b/client/src/lib/bibleLimits.js
index c398d2949f..88a92c48e7 100644
--- a/client/src/lib/bibleLimits.js
+++ b/client/src/lib/bibleLimits.js
@@ -78,6 +78,9 @@ export const BIBLE_LIMITS = Object.freeze({
SOURCE_SERIES_ID_MAX: 64,
VOICE_ID_MAX: 200,
INGREDIENT_ID_MAX: 64,
+ // Reveal-gated canon / spoiler scoping (#2178).
+ SURFACE_DESCRIPTOR_MAX: 2000,
+ REVEAL_ISSUE_MAX: 100000,
});
// Client-only helper (the cap *value* IMAGE_REFS_PER_ENTRY_MAX is mirrored from
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index 6d410b8347..a822219cfd 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -548,6 +548,13 @@
"returnsJson": true,
"variables": []
},
+ "pipeline-editorial-premature-reveal": {
+ "name": "Pipeline — Editorial Check: Premature reveal (spoiler leak)",
+ "description": "Editorial check (#2178): the information-economy guard for reveal-gated canon — flags a deliberately-withheld fact (character secret, late-story twist, hidden identity) that the prose states or unambiguously implies BEFORE its reveal issue, so a first-time reader learns it too early. Reconciles the stitched manuscript against the reveal-gated canon entries (reveal issue / hard-spoiler flag, spoiler-free surface descriptor, and the underlying gated fact) and distinguishes a genuine leak from deliberate foreshadowing, flagging only leaks. Returns issue-anchored findings.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
+ },
"pipeline-editorial-world-unforeshadowed-solution": {
"name": "Pipeline — Editorial Check: Unforeshadowed solution",
"description": "Editorial check (#2175): the worldbuilding sibling of the deus ex machina — flags a story problem resolved by a rule, power, property, or artifact the reader was never shown before it saved the day (Sanderson's First Law). Reconciles the stitched manuscript against the established world canon (artifacts/objects + places) and the continuity-bible world-rule facts, so a rule that WAS planted earlier is not flagged; the whole-arc verdict lands on the final part with earlier plants carried in the setup digest. Returns issue-anchored findings.",
diff --git a/data.reference/prompts/stages/pipeline-editorial-premature-reveal.md b/data.reference/prompts/stages/pipeline-editorial-premature-reveal.md
new file mode 100644
index 0000000000..6e6429c1ca
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-editorial-premature-reveal.md
@@ -0,0 +1,101 @@
+# Pipeline — Editorial Check: Premature reveal (spoiler leak)
+
+You are a developmental editor doing a single focused pass for ONE problem:
+**premature reveals** — the information economy of a mystery or twist. Certain
+canon facts are deliberately **withheld**: a character secret, a late-story
+twist, a hidden identity, a fact the reader is not meant to learn until a
+specific issue. The prose must not spill them early.
+
+Your job: scan the manuscript for any **reveal-gated fact** that a first-time
+reader would **learn** — stated outright or unambiguously implied — in an issue
+**before** the fact is due to be revealed.
+
+## The reveal-gated facts to watch
+
+{{#revealGatedCanon}}
+{{revealGatedCanon}}
+{{/revealGatedCanon}}
+{{^revealGatedCanon}}
+(No reveal-gated canon was supplied — reason from the manuscript alone and flag
+nothing unless a clearly-planted secret is obviously spilled early.)
+{{/revealGatedCanon}}
+
+Each gated fact names the issue it is meant to be revealed in (or that it is a
+**hard spoiler** never to appear in the drafted issues), the spoiler-free
+**surface** view the reader IS allowed to know before then, and the underlying
+secret that must NOT leak.
+
+## Leak vs. foreshadowing — flag only leaks
+
+This is the crucial distinction. Do **NOT** flag deliberate foreshadowing.
+
+- **Leak (FLAG this).** A first-time reader now **knows** the withheld fact: the
+ prose states it, names it, or implies it so unambiguously that the reveal is
+ spoiled. "Mara was the arsonist all along" appearing in Issue 2 when the arson
+ reveal is set for Issue 8. The surface descriptor was supposed to hold ("the
+ wing nobody enters") but the prose says the quiet part out loud ("the wing
+ where the heir is imprisoned").
+- **Foreshadowing (do NOT flag).** A hint that only **acquires meaning on
+ reread** — the first-time reader does not yet know the secret, but a returning
+ reader recognizes the plant. A meaningful glance, an unexplained absence, a
+ detail that reads as ordinary now and loaded later. This is the craft working
+ as intended; leave it alone.
+
+The bar: would a **first-time reader**, having read only up to this point, now
+**know** the gated fact? If yes → leak. If they merely encountered a detail
+whose significance they can't yet decode → foreshadowing, not a finding.
+
+Also do NOT flag: the **surface descriptor** itself (that's what the reader is
+allowed to know); a fact appearing **at or after** its reveal issue (that's the
+reveal landing on schedule); a fact the manuscript never actually reveals.
+
+## Manuscript
+
+```
+{{manuscript}}
+```
+
+{{#finalPart}}
+This is the **final part** of the manuscript. Judge each gated fact against the
+earliest issue it appears in (use the setup digest above for earlier parts).
+{{/finalPart}}
+{{^finalPart}}
+**You are reading the manuscript in PARTS.** Flag a leak the moment a gated fact
+appears before its reveal issue in the text you can see; the setup digest above
+carries which gated facts already surfaced in earlier parts, so measure the
+issue-of-first-leak against the earliest appearance, not just this part.
+{{/finalPart}}
+
+## Task
+
+Report every gated fact that leaks before its reveal issue. For each, quote a
+short verbatim anchor from the manuscript (≤ 200 characters) so the editor can
+jump to the exact sentence, name the issue number it leaks in, name the gated
+fact and its scheduled reveal issue in the `location`, explain why a first-time
+reader now knows the secret (and why it is a leak, not mere foreshadowing), and
+suggest the fix (cut the giveaway, replace it with the surface descriptor, or
+move the reveal earlier if the leak is actually where the twist wants to land).
+
+Be specific and cite the text. If no gated fact leaks early, return an empty
+`findings` array — do not invent issues, and do not flag legitimate
+foreshadowing.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no
+commentary:
+
+```json
+{
+ "findings": [
+ {
+ "severity": "high|medium|low",
+ "issueNumber": 2,
+ "location": "string — the gated fact + where it leaks (e.g. 'Issue 2 — leaks the arson reveal (due Issue 8)')",
+ "problem": "1–3 sentences naming the withheld fact and how the prose spills it early to a first-time reader",
+ "suggestion": "1–3 sentences on the fix — cut the giveaway, use the surface descriptor, or move the reveal",
+ "anchorQuote": "short verbatim quote from the manuscript (≤ 200 chars)"
+ }
+ ]
+}
+```
diff --git a/scripts/migrations/168-editorial-premature-reveal-stage.js b/scripts/migrations/168-editorial-premature-reveal-stage.js
new file mode 100644
index 0000000000..cc15763bab
--- /dev/null
+++ b/scripts/migrations/168-editorial-premature-reveal-stage.js
@@ -0,0 +1,16 @@
+/**
+ * Seed the premature-reveal editorial-check stage into existing installs
+ * (#2178 — CWQE Phase 13).
+ *
+ * Mirrors `143-editorial-object-weight-proportionality-stage.js`: copies the
+ * `.md` template from `data.reference/prompts/stages/` and merges its
+ * 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 stage unseeded and the `continuity.premature-reveal` editorial
+ * check would throw "Stage not found" the first time it runs.
+ */
+
+import { makeSeedMigration } from './_seedStageHelpers.js';
+
+export default makeSeedMigration('pipeline-editorial-premature-reveal');
diff --git a/scripts/migrations/168-editorial-premature-reveal-stage.test.js b/scripts/migrations/168-editorial-premature-reveal-stage.test.js
new file mode 100644
index 0000000000..5b90bbaffb
--- /dev/null
+++ b/scripts/migrations/168-editorial-premature-reveal-stage.test.js
@@ -0,0 +1,101 @@
+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 './168-editorial-premature-reveal-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 143's seed test) — no MD5 bookkeeping,
+// so the seed/no-clobber behavior is asserted directly.
+
+const FILES = [
+ { filename: 'pipeline-editorial-premature-reveal.md', stageKey: 'pipeline-editorial-premature-reveal', body: '# Premature reveal\n\nshipped body\n', returnsJson: true },
+];
+
+describe('migration 168 — seed premature-reveal editorial stage', () => {
+ let rootDir;
+ let stagesDir;
+ let refStagesDir;
+ let installedConfigPath;
+
+ const seedReference = ({ withConfig = true } = {}) => {
+ for (const { filename, body } of FILES) {
+ writeFileSync(join(refStagesDir, filename), body);
+ }
+ if (withConfig) {
+ const refConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ const stages = {};
+ for (const { stageKey, returnsJson } of FILES) {
+ stages[stageKey] = { name: stageKey, description: `${stageKey} desc`, model: 'default', returnsJson, variables: [] };
+ }
+ writeFileSync(refConfigPath, JSON.stringify({ stages }, null, 2) + '\n');
+ }
+ };
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-168-'));
+ 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();
+
+ for (const { filename, body } of FILES) {
+ expect(readFileSync(join(stagesDir, filename), 'utf8')).toBe(body);
+ }
+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));
+ expect(installed.stages['pipeline-editorial-premature-reveal']).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';
+ for (const { filename } of FILES) {
+ writeFileSync(join(stagesDir, filename), customBody);
+ }
+ writeFileSync(
+ installedConfigPath,
+ JSON.stringify({ stages: { [FILES[0].stageKey]: { name: 'user-tuned', model: 'custom' } } }, null, 2) + '\n',
+ );
+
+ await migration.up({ rootDir });
+
+ for (const { filename } of FILES) {
+ expect(readFileSync(join(stagesDir, filename), 'utf8')).toBe(customBody);
+ }
+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));
+ expect(installed.stages[FILES[0].stageKey]).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();
+ for (const { filename } of FILES) {
+ expect(existsSync(join(stagesDir, filename))).toBe(false);
+ }
+ });
+
+ it('matches the live shipped stage-config keys + prompt files (drift catch)', () => {
+ const refConfig = JSON.parse(
+ readFileSync(join(repoRoot, 'data.reference', 'prompts', 'stage-config.json'), 'utf8'),
+ );
+ for (const { stageKey, filename, returnsJson } of FILES) {
+ expect(refConfig.stages[stageKey], `stage-config missing ${stageKey}`).toBeTruthy();
+ expect(refConfig.stages[stageKey].returnsJson).toBe(returnsJson);
+ expect(existsSync(join(repoRoot, 'data.reference', 'prompts', 'stages', filename))).toBe(true);
+ }
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 11a3c83866..0879e81711 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -52,7 +52,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| Module | Purpose |
|---|---|
| `editorial/` | Extensible editorial-check registry (#1284) — `EDITORIAL_CHECKS` + fail-fast guards + lookup/state helpers. See `editorial/README.md`. The runner that executes checks lives at `server/services/pipeline/editorial/checkRunner.js`. |
-| `storyBible.js` | Canonical Character / Place / Object shapes + `BIBLE_LIMITS`. |
+| `storyBible.js` | Canonical Character / Place / Object shapes + `BIBLE_LIMITS`. Also the reveal-gated canon / spoiler-scoping helpers (#2178): `filterCanonForIssue` / `filterCanonListForIssue` / `isCanonEntryGatedForIssue` (hide or surface-substitute a gated entry in a drafting prompt), `canonHasRevealGated` + `revealGatedCanonRows` (for the `continuity.premature-reveal` check gate/summary). |
| `storyArc.js` | Canonical Arc + Season + Reader-Map shapes for pipeline arc planning. |
| `styleGuide.js` | Per-series house style (tense/POV/audience/rating/reading-level/tone/conventions): `sanitizeStyleGuide` + `renderStyleGuide` generation block + enums. |
| `storyBuilderSteps.js` | Unified Story Builder ordered step definitions + helpers (`STEPS`, `STEP_IDS`, `STEP_STATUSES`, `isValidStepId`, `stepIndex`). |
diff --git a/server/lib/canonPrompt.js b/server/lib/canonPrompt.js
index a32b217d9e..4d0c9eed86 100644
--- a/server/lib/canonPrompt.js
+++ b/server/lib/canonPrompt.js
@@ -151,6 +151,20 @@ export function shortCanonDescriptorFragments(kind, entry) {
return [];
}
+/**
+ * The single primary descriptor field for a kind — the field a SHORT card
+ * leads with (chars: `physicalDescription`, objects: `description`, places:
+ * the first `sequence` field, `description`). Single source of truth so
+ * callers that need "which field is the headline descriptor for this kind"
+ * (e.g. the reveal-gated surface substitution in storyBible.js, #2178) don't
+ * hand-maintain a parallel map. Returns null for an unknown kind.
+ */
+export function shortCanonPrimaryField(kind) {
+ const spec = SHORT_SPEC[normalizeKind(kind)];
+ if (!spec) return null;
+ return spec.primary || spec.sequence?.[0]?.field || null;
+}
+
/**
* RICH descriptor fragments — every descriptive field that contributes to
* a render prompt body. Used by render-synthesis and the
diff --git a/server/lib/canonPrompt.test.js b/server/lib/canonPrompt.test.js
index ae7432efcf..a1f84775f2 100644
--- a/server/lib/canonPrompt.test.js
+++ b/server/lib/canonPrompt.test.js
@@ -5,6 +5,7 @@ import {
descriptorForCanonEntry,
hasCanonDescriptorContent,
previewCanonFragments,
+ shortCanonPrimaryField,
} from './canonPrompt.js';
describe('canonPrompt.js', () => {
@@ -113,6 +114,22 @@ describe('canonPrompt.js', () => {
});
});
+ describe('shortCanonPrimaryField', () => {
+ it('returns the per-kind primary descriptor field (singular + plural kinds)', () => {
+ expect(shortCanonPrimaryField('character')).toBe('physicalDescription');
+ expect(shortCanonPrimaryField('characters')).toBe('physicalDescription');
+ expect(shortCanonPrimaryField('object')).toBe('description');
+ expect(shortCanonPrimaryField('objects')).toBe('description');
+ // Places use a sequence — the first field is the primary.
+ expect(shortCanonPrimaryField('place')).toBe('description');
+ expect(shortCanonPrimaryField('places')).toBe('description');
+ });
+ it('returns null for an unknown kind', () => {
+ expect(shortCanonPrimaryField('gadget')).toBeNull();
+ expect(shortCanonPrimaryField(undefined)).toBeNull();
+ });
+ });
+
describe('shortCanonDescriptorFragments', () => {
it('returns empty array for unknown kind', () => {
expect(shortCanonDescriptorFragments('unknown', { description: 'x' })).toEqual([]);
diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.md
index d2736f420b..1cdca2c05b 100644
--- a/server/lib/editorial/README.md
+++ b/server/lib/editorial/README.md
@@ -195,7 +195,7 @@ runner-injected `ctx.callInlineLLM` (an inline-prompt sibling of
|---|---|
| `checkRegistry.js` | The public entry point. Assembles `EDITORIAL_CHECKS` by spreading the per-category arrays from `./checks/*.js`, re-exports the shared infra from `./checkInfra.js`, and keeps the registry's lookup/state helpers that need the assembled array: `EDITORIAL_SOURCES` (the per-check `sources` vocabulary the staleness runner fingerprints, #1387), fail-fast guards (`assertValidChecks`), and `getCheck`, `getCheckById`, `getAllChecks`, `listChecks`, `resolveCheckState`, `getEnabledChecks`, `resolveCheckConfig`, `orderChecksByDependencies` (the dependency topo-sort, #1627) plus the user-defined-check helpers (`buildCustomCheck`, `readCustomCheckDefs`, `isCustomCheckId`, `isValidCustomCheckDef`). Decomposed from a 7,474-line god file in #1829. |
| `checkInfra.js` | Shared check infrastructure extracted in #1829: imports + constants + stage names + the pure summary/helper functions (e.g. `runManuscriptLlmCheck`, `canonCharacterTraitsSummary`, `editorialFindingKey`, `buildCustomCheckPrompt`, `normalizeCheckScopes`/`primaryCheckScope`) that the check definitions and the registry tail depend on. Kept side-effect-free so `./checks/*.js` import from it without a cycle through `checkRegistry.js` (whose `EDITORIAL_CHECKS` spread would otherwise hit a TDZ on the checks' eagerly-evaluated `configSchema`s). Re-exports its externals (zod + the sibling primitive modules) so a check file imports everything from one hub. |
-| `checks/*.js` | The `EDITORIAL_CHECKS` definitions, grouped by category (#1829): `naming`, `cast`, `pov`, `characterArc`, `continuity`, `comic`, `visual`, `scene`, `dialogue`, `proseStyle`, `research`, `slop` (#2165 — `prose.slop-banned-words`/`prose.ai-tells`/`prose.structural-tics`/`prose.burstiness`, built on `../slopScore.js`), `world` (#2175 — `world.unforeshadowed-solution`/`world.cost-free-power`, the review-side companion to the Sanderson's-Laws worldbuilding doctrine injected into the universe-expansion generation prompt; reconciles against canon + the continuity-bible world-rule facts). Each exports a `<group>Checks` array of declarative check entries (scope, kind, severity, `configSchema`, `gate`, `run(ctx)`); `checkRegistry.js` imports and spreads them. Internal to the registry — imported only via `checkRegistry.js`, not the barrel. |
+| `checks/*.js` | The `EDITORIAL_CHECKS` definitions, grouped by category (#1829): `naming`, `cast`, `pov`, `characterArc`, `continuity` (incl. #2178 `continuity.premature-reveal` — the information-economy guard that flags a reveal-gated canon fact leaked before its reveal issue, reconciled against `revealGatedCanonSummary`; gated on `canonHasRevealGated`), `comic`, `visual`, `scene`, `dialogue`, `proseStyle`, `research`, `slop` (#2165 — `prose.slop-banned-words`/`prose.ai-tells`/`prose.structural-tics`/`prose.burstiness`, built on `../slopScore.js`), `world` (#2175 — `world.unforeshadowed-solution`/`world.cost-free-power`, the review-side companion to the Sanderson's-Laws worldbuilding doctrine injected into the universe-expansion generation prompt; reconciles against canon + the continuity-bible world-rule facts). Each exports a `<group>Checks` array of declarative check entries (scope, kind, severity, `configSchema`, `gate`, `run(ctx)`); `checkRegistry.js` imports and spreads them. Internal to the registry — imported only via `checkRegistry.js`, not the barrel. |
| `nameSimilarity.js` | Pure, dependency-free name-confusability primitives for `naming.dissimilar-names` (#1291): `normalizeName`, `vowelSkeleton`, `soundex` (phonetic key), `levenshtein` (edit distance), `nameSimilaritySignals` (the per-pair signal list, with option toggles), and `firstLetterHistogram` / `findFirstLetterClusters` (cast first-letter crowding). |
| `cliches.js` | Pure, dependency-free cliché + overwriting primitives for `prose.cliches` and `prose.modifier-stacking` (#1308): `CLICHE_PHRASES` (seed stock-simile/idiom list), `findCliches` (whole-word phrase scan with house-style allow/extra lists), and `findModifierStacking` (cumulative no-comma runs of 3+ stacked adjectives/adverbs). The LLM sibling `prose.dead-metaphor` handles the judgment cases (mixed/dead metaphor, novel clichés, purple prose). |
| `italicThoughts.js` | Pure, dependency-free italic-thought primitive for `prose.italic-thoughts` (#1300): `findItalicThoughts` (multi-word markdown `*…*` / `_…_` italic runs, dedup + word-count threshold so single-word emphasis, bold, and `snake_case` are skipped). The LLM siblings (`opening.wrong-start`, `prose.mirror-description`, `dialogue.pleasantries`, `prose.kill-your-darlings`) handle the judgment cases in the #1300 anti-pattern bundle. |
diff --git a/server/lib/editorial/checkInfra.js b/server/lib/editorial/checkInfra.js
index ea7421e596..b0d9be4db6 100644
--- a/server/lib/editorial/checkInfra.js
+++ b/server/lib/editorial/checkInfra.js
@@ -57,6 +57,7 @@ import {
authoredRevealSummary,
} from './comicPacing.js';
import { findAxisReversals, findShotTypeMonotony, summarizeStoryboardShots } from './shotContinuity.js';
+import { revealGatedCanonRows, canonHasRevealGated } from '../storyBible.js';
// Re-exported so ./checks/*.js and ./checkRegistry.js import everything from here.
export {
@@ -108,6 +109,8 @@ export {
splitScenes,
summarizeStoryboardShots,
transitionOpenerRatio,
+ canonHasRevealGated,
+ revealGatedCanonRows,
z,
};
@@ -309,6 +312,56 @@ export const INTERIORITY_STAGE = 'pipeline-editorial-interiority';
// migrations but NOT setup-data, so the migration is required).
export const CHEKHOV_STAGE = 'pipeline-editorial-chekhov';
+// Stage name for the premature-reveal editorial LLM check (#2178 — CWQE Phase
+// 13). Ships in data.reference/prompts/stages/ + stage-config.json (fresh
+// installs via setup-data.js) and migrates to existing installs via migration
+// 168 (boot runs migrations but NOT setup-data, so the migration is required).
+export const PREMATURE_REVEAL_STAGE = 'pipeline-editorial-premature-reveal';
+
+// Render the reveal-gated canon (#2178) into a compact text block the
+// premature-reveal check passes alongside the manuscript, so the model knows
+// which facts are SECRETS not yet due and when each is meant to surface. Each
+// row names the entry, its reveal issue (or hard spoiler), the spoiler-free
+// surface stand-in the reader IS allowed to see, and the underlying fact that
+// must NOT leak early. Pure + deterministic so it's unit-testable and its token
+// cost counts into the per-chunk overhead. Returns '' when no canon is
+// reveal-gated (the check gates on `canonHasRevealGated` so this won't be
+// called with an empty set, but the guard keeps it safe).
+export function revealGatedCanonSummary(canon) {
+ const rows = revealGatedCanonRows(canon);
+ if (!rows.length) return '';
+ const lines = rows.map((r) => {
+ const when = r.spoiler
+ ? 'HARD SPOILER — must not appear in ANY drafted issue'
+ : `revealed in Issue ${r.revealIssue} — must not appear before then`;
+ const surface = r.surfaceDescriptor
+ ? ` Pre-reveal, the reader may only know: "${r.surfaceDescriptor}".`
+ : '';
+ const fact = r.fact ? ` The gated fact (must NOT leak early): ${r.fact}.` : '';
+ return `- ${r.kind} "${r.name}" (${when}).${surface}${fact}`;
+ });
+ return 'Reveal-gated canon (these facts are deliberately withheld — flag any that a first-time reader would '
+ + 'learn from the prose before the fact is due):\n' + lines.join('\n');
+}
+
+// Render reveal-gated canon (#2178) as AUTHORED PAYOFFS for the Chekhov check —
+// a gated entry's `revealIssue` is effectively an authored payoff point (the
+// issue where the withheld fact is meant to fire). Folded into the Chekhov
+// `authoredSetups` block so the check can flag a reveal that arrives with zero
+// prior setup (an orphaned payoff). Only NUMERIC reveal gates render — a hard
+// `spoiler` has no scheduled payoff issue to reconcile against. Returns '' when
+// no numeric-gated entry exists (the block renders nothing). Pure.
+export function revealGatedPayoffsSummary(canon) {
+ const rows = revealGatedCanonRows(canon).filter((r) => Number.isInteger(r.revealIssue));
+ if (!rows.length) return '';
+ const lines = rows.map((r) => {
+ const what = r.fact || `the withheld fact about ${r.kind} "${r.name}"`;
+ return `- ${r.kind} "${r.name}" — reveal-gated fact due to pay off in Issue ${r.revealIssue}: ${what}`;
+ });
+ return 'Authored reveal-gated payoffs (each gated fact is meant to be revealed — fire — in its named issue; '
+ + 'flag a reveal that arrives with no prior setup):\n' + lines.join('\n');
+}
+
// Stage name for the chapter-ending cliffhanger LLM check (#1298). Ships in
// data.reference/prompts/stages/ + stage-config.json (fresh installs via
// setup-data.js) and migrates to existing installs via migration 102 (boot runs
diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.js
index 473d3fe4e0..c865fac7b5 100644
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@ -201,6 +201,7 @@ const CHECK_ORDER = Object.freeze([
'style.reading-level',
'style.conformance',
'chekhov.setups-payoffs',
+ 'continuity.premature-reveal',
'prose.cliches',
'prose.modifier-stacking',
'prose.filter-words',
diff --git a/server/lib/editorial/checks/continuity.js b/server/lib/editorial/checks/continuity.js
index 8fd949dc5b..4936329e4d 100644
--- a/server/lib/editorial/checks/continuity.js
+++ b/server/lib/editorial/checks/continuity.js
@@ -5,11 +5,13 @@ import {
OBJECT_BACKSTORY_STAGE,
OBJECT_MOTIVATION_STAGE,
OBJECT_WEIGHT_STAGE,
+ PREMATURE_REVEAL_STAGE,
TIMELINE_CONTRADICTION_STAGE,
attachmentBackstoryRows,
attachmentCanon,
authoredSetupPayoffSummary,
canonCharacterStatesSummary,
+ canonHasRevealGated,
continuityLedgerSummary,
describeObjectAttachments,
describeObjectWeight,
@@ -17,6 +19,8 @@ import {
mapLlmFindings,
relationshipCanon,
renderCharacterArcsForPrompt,
+ revealGatedCanonSummary,
+ revealGatedPayoffsSummary,
runManuscriptLlmCheck,
sceneGroundingSummary,
z,
@@ -434,8 +438,14 @@ export const continuityChecks = [
run: (ctx) => {
// Authored hooks/payoffs + the foreshadowing ledger (#2172) are fixed
// per-call overhead (re-sent on each chunk). The ledger is folded into the
- // same authoredSetups block so the prompt consumes it unchanged.
- const authoredSetups = authoredSetupPayoffSummary(ctx.series?.arc?.readerMap, ctx.series?.arc?.foreshadowing);
+ // same authoredSetups block so the prompt consumes it unchanged. Reveal-
+ // gated canon (#2178) adds each gated fact as an authored payoff at its
+ // reveal issue, so the check can flag a reveal that arrives with no prior
+ // setup (an orphaned payoff).
+ const authoredSetups = [
+ authoredSetupPayoffSummary(ctx.series?.arc?.readerMap, ctx.series?.arc?.foreshadowing),
+ revealGatedPayoffsSummary(ctx.canon),
+ ].filter(Boolean).join('\n\n');
// 0 disables the distant sub-check; >0 is the issue-gap threshold. Pass a
// string so the prompt's `{{#distantGap}}` section renders only when enabled.
const distantGap = ctx.config?.distantGap ?? 4;
@@ -474,4 +484,62 @@ export const continuityChecks = [
});
},
},
+ {
+ id: 'continuity.premature-reveal',
+ sources: ['manuscript', 'canon'],
+ label: 'Premature reveal (spoiler leak)',
+ description:
+ 'LLM check (#2178) — the information-economy guard for reveal-gated canon. Scans drafted prose for a canon fact that is deliberately withheld (a character secret, a late-story twist, a hidden identity) stated or unambiguously implied BEFORE its reveal issue, so a first-time reader learns it too early. Reconciles the prose against the reveal-gated canon entries (their reveal issue / hard-spoiler flag, the spoiler-free surface descriptor the reader IS allowed to know, and the underlying gated fact). Distinguishes a genuine LEAK (a first-time reader now knows the secret) from deliberate FORESHADOWING (a hint that only acquires meaning on reread) — flags only leaks. Gated on the series having authored any reveal-gated canon; otherwise it never runs.',
+ scope: 'series',
+ kind: 'llm',
+ category: 'continuity',
+ severityDefault: 'high',
+ defaultEnabled: true,
+ // Reads the stitched manuscript corpus — so the runner only pays the
+ // section-collection I/O when a manuscript-consuming check is enabled.
+ needsManuscript: true,
+ configSchema: z.object({
+ // Cap findings per run so a long manuscript can't flood the review.
+ maxFindings: z.number().int().min(1).max(50).default(12),
+ }),
+ configFields: [
+ {
+ key: 'maxFindings',
+ label: 'Max findings per run',
+ type: 'number',
+ min: 1,
+ max: 50,
+ step: 1,
+ help: 'Cap findings so a long manuscript can not flood the review.',
+ },
+ ],
+ // Skip the LLM call entirely when the series authored no reveal-gated canon
+ // (no revealIssue / spoiler on any entry) AND when there's no manuscript to
+ // scan — there is nothing a premature reveal could be measured against.
+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0 && canonHasRevealGated(ctx.canon),
+ run: (ctx) => {
+ // The reveal-gated canon block is fixed per-call overhead (re-sent on each
+ // chunk) and pure context: it names each withheld fact, WHEN it's due, the
+ // spoiler-free surface view, and the underlying secret — the ground truth a
+ // leak is judged against. Trimmed by the runner to keep the manuscript a
+ // budget floor.
+ const revealGatedCanon = revealGatedCanonSummary(ctx.canon);
+ return runManuscriptLlmCheck(ctx, {
+ stage: PREMATURE_REVEAL_STAGE,
+ category: 'continuity',
+ context: { revealGatedCanon },
+ buildVars: (manuscript, _meta, c) => ({ manuscript, revealGatedCanon: c.revealGatedCanon }),
+ // A reveal can leak in an early issue for a fact due much later; the
+ // findings digest keeps prior leaks in view so a later chunk doesn't
+ // re-flag, and the setup digest rolls forward which gated facts have
+ // already surfaced (legitimately or not) so the issue-of-first-leak is
+ // measured against the earliest appearance, not each chunk in isolation.
+ crossChunkDigest: true,
+ crossChunkSetup: true,
+ setupFocus: 'For each reveal-gated canon fact, note the earliest issue in which the prose so far states '
+ + 'or unambiguously implies it (so a later chunk measures the leak against its first appearance, not just '
+ + 'its own text) — and whether that issue is before the fact\'s reveal issue.',
+ });
+ },
+ },
];
diff --git a/server/lib/editorial/prematureReveal.test.js b/server/lib/editorial/prematureReveal.test.js
new file mode 100644
index 0000000000..db1dbcf202
--- /dev/null
+++ b/server/lib/editorial/prematureReveal.test.js
@@ -0,0 +1,116 @@
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'fs';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+
+import { applyTemplate } from '../promptTemplate.js';
+import { getCheck } from './checkRegistry.js';
+import { revealGatedCanonSummary, revealGatedPayoffsSummary, PREMATURE_REVEAL_STAGE } from './checkInfra.js';
+
+// #2178 — the premature-reveal editorial check (CWQE Phase 13). Pins the gate
+// (only fires when the series authored reveal-gated canon AND a manuscript
+// exists), the summary block the prompt consumes, and the shipped template's
+// leak-vs-foreshadowing distinction + finalPart toggle.
+
+const PROMPT = readFileSync(
+ join(dirname(fileURLToPath(import.meta.url)), '../../../data.reference/prompts/stages/pipeline-editorial-premature-reveal.md'),
+ 'utf-8',
+);
+
+describe('continuity.premature-reveal check gating (#2178)', () => {
+ const check = getCheck('continuity.premature-reveal');
+
+ it('is registered with the expected scope/kind/category', () => {
+ expect(check).toBeTruthy();
+ expect(check.scope).toBe('series');
+ expect(check.kind).toBe('llm');
+ expect(check.category).toBe('continuity');
+ expect(check.needsManuscript).toBe(true);
+ });
+
+ it('gate is false without reveal-gated canon, false without a manuscript, true with both', () => {
+ const gated = { characters: [{ name: 'Vex', revealIssue: 8 }], places: [], objects: [] };
+ const ungated = { characters: [{ name: 'Mira' }], places: [], objects: [] };
+ expect(check.gate({ manuscript: 'text', canon: gated })).toBe(true);
+ expect(check.gate({ manuscript: 'text', canon: ungated })).toBe(false);
+ expect(check.gate({ manuscript: ' ', canon: gated })).toBe(false);
+ expect(check.gate({ manuscript: 'text', canon: null })).toBe(false);
+ });
+});
+
+describe('revealGatedCanonSummary (#2178)', () => {
+ it('renders reveal issue, hard spoiler, surface descriptor, and the gated fact', () => {
+ const canon = {
+ characters: [{
+ name: 'Vex', physicalDescription: 'the true killer', background: 'poisoned the well',
+ revealIssue: 8, surfaceDescriptor: 'a reclusive apothecary',
+ }],
+ objects: [{ name: 'Vial', description: 'the poison', spoiler: true }],
+ places: [],
+ };
+ const out = revealGatedCanonSummary(canon);
+ expect(out).toContain('Vex');
+ expect(out).toContain('Issue 8');
+ expect(out).toContain('a reclusive apothecary');
+ expect(out).toContain('the true killer');
+ expect(out).toContain('Vial');
+ expect(out).toContain('HARD SPOILER');
+ });
+
+ it('returns empty string when nothing is gated', () => {
+ expect(revealGatedCanonSummary({ characters: [{ name: 'A' }] })).toBe('');
+ });
+});
+
+describe('revealGatedPayoffsSummary — Chekhov interaction (#2178)', () => {
+ it('renders only numeric-gated entries as authored payoffs at their reveal issue', () => {
+ const canon = {
+ characters: [
+ { name: 'Vex', physicalDescription: 'the true killer', revealIssue: 8 },
+ { name: 'Ghost', description: 'the mastermind', spoiler: true }, // hard spoiler — no payoff issue
+ ],
+ objects: [], places: [],
+ };
+ const out = revealGatedPayoffsSummary(canon);
+ expect(out).toContain('Vex');
+ expect(out).toContain('Issue 8');
+ expect(out).toContain('the true killer');
+ // A hard spoiler has no scheduled payoff issue — excluded.
+ expect(out).not.toContain('Ghost');
+ });
+
+ it('returns empty string when no numeric reveal gate exists', () => {
+ expect(revealGatedPayoffsSummary({ characters: [{ name: 'Ghost', spoiler: true }] })).toBe('');
+ expect(revealGatedPayoffsSummary({ characters: [{ name: 'A' }] })).toBe('');
+ });
+});
+
+describe('pipeline-editorial-premature-reveal prompt rendering (#2178)', () => {
+ const baseVars = (overrides = {}) => ({
+ manuscript: '# Issue 2\n\nMara struck the match.',
+ revealGatedCanon: 'character "Mara" (revealed in Issue 8 — must not appear before then).',
+ finalPart: '',
+ ...overrides,
+ });
+
+ it('renders the reveal-gated canon block and the leak-vs-foreshadowing rule', () => {
+ const out = applyTemplate(PROMPT, baseVars());
+ expect(out).toContain('Mara');
+ expect(out).toContain('foreshadowing');
+ expect(out).toContain('first-time reader');
+ });
+
+ it('renders the non-final-part guidance when finalPart is falsy and the final-part note when set', () => {
+ expect(applyTemplate(PROMPT, baseVars({ finalPart: '' }))).toContain('reading the manuscript in PARTS');
+ expect(applyTemplate(PROMPT, baseVars({ finalPart: 'true' }))).toContain('final part');
+ });
+
+ it('falls back gracefully when no reveal-gated canon is supplied', () => {
+ const out = applyTemplate(PROMPT, baseVars({ revealGatedCanon: '' }));
+ expect(out).toContain('No reveal-gated canon was supplied');
+ });
+
+ it('uses the correct stage key', () => {
+ expect(PREMATURE_REVEAL_STAGE).toBe('pipeline-editorial-premature-reveal');
+ });
+});
diff --git a/server/lib/storyBible.js b/server/lib/storyBible.js
index dc155fa51a..be731f7fb4 100644
--- a/server/lib/storyBible.js
+++ b/server/lib/storyBible.js
@@ -11,6 +11,7 @@ import { randomUUID } from 'crypto';
import { normalizeSlugline } from './scenePrompt.js';
import { PATHS, resolveImageRef } from './fileUtils.js';
import { isPlainObject } from './objects.js';
+import { shortCanonPrimaryField } from './canonPrompt.js';
// Re-export so callers (writers-room domain files) can import a single
// canonical normalizer when they need to match places by slugline.
@@ -127,6 +128,15 @@ export const BIBLE_LIMITS = Object.freeze({
// `piper:en_GB-northern_english_male`). Caps generously since 3rd-party
// providers (ElevenLabs) use uuid-shaped voice ids.
VOICE_ID_MAX: 200,
+ // Reveal-gated canon (#2178): `surfaceDescriptor` is the pre-reveal
+ // stand-in — what the world looks like BEFORE the spoiler is due ("the
+ // locked east wing" vs "the wing where the heir is imprisoned"). Roomy
+ // like a place description so a full surface-level paragraph fits.
+ SURFACE_DESCRIPTOR_MAX: 2000,
+ // Upper bound for the issue number a canon fact is revealed in. A generous
+ // cap that comfortably exceeds any real series length while still rejecting
+ // a hallucinated/overflowed integer.
+ REVEAL_ISSUE_MAX: 100000,
});
// Canonical provenance vocabulary. `BIBLE_SOURCE.SERIES_EXTRACT` is the
@@ -741,6 +751,17 @@ function sanitizeAttachment(raw) {
return out;
}
+// Normalize a reveal-issue gate to a positive integer or null. Accepts a
+// finite number or a numeric string (LLM/JSON both occur); a 0/negative/
+// non-integer/over-cap value collapses to null (no gate). Null = the entry is
+// always visible — the backward-compatible default for every existing canon
+// entry that predates reveal gating (#2178).
+function ensureRevealIssue(raw) {
+ const n = typeof raw === 'number' ? raw : (isStr(raw) && raw.trim() !== '' ? Number(raw) : NaN);
+ if (!Number.isInteger(n) || n < 1 || n > BIBLE_LIMITS.REVEAL_ISSUE_MAX) return null;
+ return n;
+}
+
// Shared canon extras applied to every kind. Persists explicit `locked: true`
// AND `locked: false` so a Universe-Builder caller can flip the bit and have
// the change survive round-trips. Missing `locked` still collapses to absent
@@ -756,9 +777,21 @@ function applyCanonExtras(raw) {
// every entry so the round-trip never strips it on a not-yet-promoted
// record. See migrateBibleToCatalog.js for the backfill path.
ingredientId: trimTo(raw.ingredientId, BIBLE_LIMITS.INGREDIENT_ID_MAX) || null,
+ // Reveal-gated canon / spoiler scoping (#2178). All three collapse to
+ // null/absent so every pre-existing entry stays "always visible" (full
+ // backward compat; peers store the fields verbatim). `revealIssue` is the
+ // issue number at/after which the fact may enter a drafting prompt;
+ // `surfaceDescriptor` is the pre-reveal stand-in substituted into context
+ // before then. `spoiler` is a soft flag (gate without a specific issue) —
+ // an entry the writer wants excluded from drafting context regardless of
+ // issue number (autonovel's "MYSTERY.md is not for drafting" pattern).
+ revealIssue: ensureRevealIssue(raw.revealIssue),
+ surfaceDescriptor: trimTo(raw.surfaceDescriptor, BIBLE_LIMITS.SURFACE_DESCRIPTOR_MAX) || null,
};
if (raw.locked === true) out.locked = true;
else if (raw.locked === false) out.locked = false;
+ if (raw.spoiler === true) out.spoiler = true;
+ else if (raw.spoiler === false) out.spoiler = false;
return out;
}
@@ -955,6 +988,172 @@ export const SANITIZERS = Object.freeze({
object: sanitizeObject,
});
+// ---------------------------------------------------------------------------
+// Reveal-gated canon / spoiler scoping (#2178)
+// ---------------------------------------------------------------------------
+//
+// Canon context is injected into every issue's drafting prompt, so a character
+// secret or late-story fact could leak into the prose long before it's due.
+// A canon entry can carry a reveal gate:
+// - `revealIssue` (int) — the entry's fact is hidden from any issue numbered
+// BEFORE this. At/after it, the entry is fully visible.
+// - `spoiler: true` — a hard gate with no specific issue: excluded from
+// ALL drafting context (autonovel's "MYSTERY.md is not for drafting").
+// - `surfaceDescriptor` — the pre-reveal stand-in. When present on a gated
+// entry, the entry is KEPT in context but reduced to a spoiler-free surface
+// view (identity + surfaceDescriptor only). When absent, the gated entry is
+// dropped from context entirely.
+//
+// Absent gate fields = always visible — every pre-#2178 entry round-trips
+// unchanged. The JUDGE (#2167) and editorial checks receive the FULL canon:
+// this filter is ONLY for the writer-facing drafting/revision context.
+
+// The field a surface view replaces with `surfaceDescriptor` is the kind's
+// SHORT primary descriptor — sourced from canonPrompt's SHORT_SPEC via
+// `shortCanonPrimaryField` so there's no parallel per-kind map to drift.
+
+// True when an entry carries ANY reveal gate (a hard `spoiler` flag or a valid
+// numeric `revealIssue`) — the shared predicate behind `canonHasRevealGated`,
+// `revealGatedCanonRows`, and the client badge. Issue-agnostic: use
+// `isCanonEntryGatedForIssue` when you need "gated FOR this issue".
+export function isEntryRevealGated(entry) {
+ return !!entry && (entry.spoiler === true || ensureRevealIssue(entry.revealIssue) != null);
+}
+
+/**
+ * True when a canon entry is reveal-gated for the given issue number:
+ * a hard `spoiler` flag, OR a `revealIssue` the issue hasn't reached yet.
+ * A non-finite/absent `issueNumber` is treated as "unknown position" and only
+ * the hard `spoiler` flag gates (a numeric reveal gate can't be evaluated
+ * without knowing which issue we're drafting).
+ */
+export function isCanonEntryGatedForIssue(entry, issueNumber) {
+ if (!entry || typeof entry !== 'object') return false;
+ if (entry.spoiler === true) return true;
+ const reveal = ensureRevealIssue(entry.revealIssue);
+ if (reveal == null) return false;
+ const n = typeof issueNumber === 'number' ? issueNumber : Number(issueNumber);
+ if (!Number.isFinite(n)) return false;
+ return n < reveal;
+}
+
+/**
+ * Reduce a gated entry to its spoiler-free surface view: identity fields plus
+ * the `surfaceDescriptor` substituted into the kind's primary descriptor
+ * field. Every other narrative/prose field is dropped so no spoiler-bearing
+ * text (background, significance, motivations, …) leaks through. Returns null
+ * when the entry has no `surfaceDescriptor` — the caller drops it from context.
+ */
+function surfaceCanonEntry(kind, entry) {
+ const surface = trimTo(entry?.surfaceDescriptor, BIBLE_LIMITS.SURFACE_DESCRIPTOR_MAX);
+ if (!surface) return null;
+ const descField = shortCanonPrimaryField(kind);
+ const out = {
+ id: entry.id,
+ name: entry.name || '',
+ aliases: Array.isArray(entry.aliases) ? entry.aliases : [],
+ // Preserve the identity/continuity keys a matcher or roster needs, but
+ // nothing that carries the secret.
+ ...(kind === 'character' && entry.role ? { role: entry.role } : {}),
+ ...(kind === 'place' && entry.slugline ? { slugline: entry.slugline } : {}),
+ // Flag so any downstream renderer / debugging can tell this is a masked view.
+ surfaced: true,
+ };
+ if (descField) out[descField] = surface;
+ return out;
+}
+
+/**
+ * Filter one kind's canon list for a drafting/revision prompt at `issueNumber`.
+ * Ungated entries pass through untouched; gated entries with a
+ * `surfaceDescriptor` are reduced to their surface view; gated entries without
+ * one are dropped. Pure — returns a new array, never mutates the input.
+ */
+export function filterCanonListForIssue(list, kind, issueNumber) {
+ if (!Array.isArray(list)) return [];
+ const out = [];
+ for (const entry of list) {
+ if (!isCanonEntryGatedForIssue(entry, issueNumber)) {
+ out.push(entry);
+ continue;
+ }
+ const surfaced = surfaceCanonEntry(kind, entry);
+ if (surfaced) out.push(surfaced);
+ // else: no surface stand-in → hidden from drafting context entirely.
+ }
+ return out;
+}
+
+/**
+ * Filter a whole `{ characters, places, objects }` canon bundle for a drafting
+ * prompt at `issueNumber`. Returns a NEW bundle with each list reveal-filtered;
+ * a nullish canon returns empty lists. Used by `buildStageContext` and the
+ * revision-loop cast builder — NOT by the editorial checks (they get full canon).
+ */
+export function filterCanonForIssue(canon, issueNumber) {
+ return {
+ characters: filterCanonListForIssue(canon?.characters, 'character', issueNumber),
+ places: filterCanonListForIssue(canon?.places, 'place', issueNumber),
+ objects: filterCanonListForIssue(canon?.objects, 'object', issueNumber),
+ };
+}
+
+/**
+ * True when ANY entry across a `{ characters, places, objects }` canon bundle
+ * carries a reveal gate (a `revealIssue` or a `spoiler` flag). The
+ * `continuity.premature-reveal` editorial check gates on this so it never fires
+ * on a series that authored no reveal-gated canon.
+ */
+export function canonHasRevealGated(canon) {
+ for (const key of BIBLE_KEYS) {
+ const list = canon?.[key];
+ if (Array.isArray(list) && list.some(isEntryRevealGated)) return true;
+ }
+ return false;
+}
+
+// The spoiler-bearing narrative fields per kind whose content the
+// premature-reveal prompt names as "the gated fact" (what a leak looks like).
+// Keyed by BIBLE_KIND so a future kind added to the enum surfaces here.
+const SECRET_FIELDS_BY_KIND = Object.freeze({
+ [BIBLE_KIND.CHARACTER]: ['physicalDescription', 'personality', 'background', 'motivations', 'specialTraits'],
+ [BIBLE_KIND.PLACE]: ['description', 'recurringDetails'],
+ [BIBLE_KIND.OBJECT]: ['description', 'significance'],
+});
+
+/**
+ * Enumerate every reveal-gated canon entry across a bundle as a compact row
+ * `{ kind, name, revealIssue, spoiler, surfaceDescriptor, fact }` for the
+ * `continuity.premature-reveal` prompt. `fact` is the spoiler content the prose
+ * must NOT reveal early — the kind's primary descriptor plus the deeper
+ * narrative field so the model knows what "leaked" looks like. Pure.
+ */
+export function revealGatedCanonRows(canon) {
+ const rows = [];
+ // Iterate kinds via BIBLE_KIND → BIBLE_FIELD (kind → plural key) so the
+ // kind↔key mapping stays derived from the module's single source of truth.
+ for (const kind of BIBLE_KINDS) {
+ const list = canon?.[BIBLE_FIELD[kind]];
+ if (!Array.isArray(list)) continue;
+ for (const e of list) {
+ if (!isEntryRevealGated(e)) continue;
+ const fact = SECRET_FIELDS_BY_KIND[kind]
+ .map((f) => trimTo(e[f], 600))
+ .filter(Boolean)
+ .join(' — ');
+ rows.push({
+ kind,
+ name: trimTo(e.name, BIBLE_LIMITS.NAME_MAX) || '(unnamed)',
+ revealIssue: ensureRevealIssue(e.revealIssue),
+ spoiler: e.spoiler === true,
+ surfaceDescriptor: trimTo(e.surfaceDescriptor, BIBLE_LIMITS.SURFACE_DESCRIPTOR_MAX) || null,
+ fact,
+ });
+ }
+ }
+ return rows;
+}
+
// Per-kind merge config:
// userEditable — fields filled only when blank on the existing entry
// keyFields — which fields contribute to the dedup lookup map, paired
diff --git a/server/lib/storyBible.test.js b/server/lib/storyBible.test.js
index 21d24176b4..8c5aa3cbd9 100644
--- a/server/lib/storyBible.test.js
+++ b/server/lib/storyBible.test.js
@@ -35,6 +35,11 @@ const {
SERVER_OWNED_CHARACTER_FIELDS,
trimTo,
trimToClause,
+ filterCanonForIssue,
+ filterCanonListForIssue,
+ isCanonEntryGatedForIssue,
+ canonHasRevealGated,
+ revealGatedCanonRows,
} = storyBible;
const WORK_ID = 'wr-work-aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee';
@@ -1441,3 +1446,151 @@ describe('storyBible — trimToClause (boundary-aware prose cap)', () => {
expect(trimToClause(long, 100).length).toBeLessThanOrEqual(100);
});
});
+
+describe('storyBible — reveal-gated canon (#2178)', () => {
+ describe('sanitizer field round-trip', () => {
+ it('defaults reveal fields to null/absent on every kind (backward compat)', () => {
+ const c = sanitizeCharacter({ name: 'Alex' });
+ expect(c.revealIssue).toBeNull();
+ expect(c.surfaceDescriptor).toBeNull();
+ expect(c.spoiler).toBeUndefined();
+ const p = sanitizePlace({ name: 'The Wing' });
+ expect(p.revealIssue).toBeNull();
+ expect(p.surfaceDescriptor).toBeNull();
+ const o = sanitizeObject({ name: 'The Locket' });
+ expect(o.revealIssue).toBeNull();
+ expect(o.spoiler).toBeUndefined();
+ });
+
+ it('persists a valid revealIssue (number or numeric string) and rejects bad values', () => {
+ expect(sanitizeCharacter({ name: 'A', revealIssue: 8 }).revealIssue).toBe(8);
+ expect(sanitizeCharacter({ name: 'A', revealIssue: '8' }).revealIssue).toBe(8);
+ expect(sanitizeCharacter({ name: 'A', revealIssue: 0 }).revealIssue).toBeNull();
+ expect(sanitizeCharacter({ name: 'A', revealIssue: -3 }).revealIssue).toBeNull();
+ expect(sanitizeCharacter({ name: 'A', revealIssue: 2.5 }).revealIssue).toBeNull();
+ expect(sanitizeCharacter({ name: 'A', revealIssue: 'soon' }).revealIssue).toBeNull();
+ expect(sanitizeCharacter({ name: 'A', revealIssue: BIBLE_LIMITS.REVEAL_ISSUE_MAX + 1 }).revealIssue).toBeNull();
+ });
+
+ it('persists explicit spoiler true/false and drops a non-boolean', () => {
+ expect(sanitizeCharacter({ name: 'A', spoiler: true }).spoiler).toBe(true);
+ expect(sanitizeCharacter({ name: 'A', spoiler: false }).spoiler).toBe(false);
+ expect(sanitizeCharacter({ name: 'A', spoiler: 'yes' }).spoiler).toBeUndefined();
+ expect(sanitizeCharacter({ name: 'A' }).spoiler).toBeUndefined();
+ });
+
+ it('caps surfaceDescriptor at its limit and collapses blank to null', () => {
+ const long = 'x'.repeat(BIBLE_LIMITS.SURFACE_DESCRIPTOR_MAX + 100);
+ expect(sanitizePlace({ name: 'A', surfaceDescriptor: long }).surfaceDescriptor.length)
+ .toBe(BIBLE_LIMITS.SURFACE_DESCRIPTOR_MAX);
+ expect(sanitizePlace({ name: 'A', surfaceDescriptor: ' ' }).surfaceDescriptor).toBeNull();
+ });
+ });
+
+ describe('isCanonEntryGatedForIssue', () => {
+ it('hard spoiler gates regardless of issue number', () => {
+ expect(isCanonEntryGatedForIssue({ spoiler: true }, 1)).toBe(true);
+ expect(isCanonEntryGatedForIssue({ spoiler: true }, 99)).toBe(true);
+ expect(isCanonEntryGatedForIssue({ spoiler: true }, undefined)).toBe(true);
+ });
+ it('revealIssue gates only issues before it', () => {
+ expect(isCanonEntryGatedForIssue({ revealIssue: 8 }, 2)).toBe(true);
+ expect(isCanonEntryGatedForIssue({ revealIssue: 8 }, 8)).toBe(false);
+ expect(isCanonEntryGatedForIssue({ revealIssue: 8 }, 9)).toBe(false);
+ });
+ it('an ungated entry is never gated', () => {
+ expect(isCanonEntryGatedForIssue({ name: 'A' }, 1)).toBe(false);
+ expect(isCanonEntryGatedForIssue(null, 1)).toBe(false);
+ });
+ it('a numeric reveal gate is not evaluable without an issue number', () => {
+ expect(isCanonEntryGatedForIssue({ revealIssue: 8 }, undefined)).toBe(false);
+ expect(isCanonEntryGatedForIssue({ revealIssue: 8 }, 'not-a-number')).toBe(false);
+ });
+ });
+
+ describe('filterCanonListForIssue — surface substitution + drop', () => {
+ it('passes ungated entries through untouched', () => {
+ const list = [{ id: 'c1', name: 'Open', physicalDescription: 'tall' }];
+ expect(filterCanonListForIssue(list, 'character', 1)).toEqual(list);
+ });
+ it('substitutes surfaceDescriptor for a gated entry and strips the secret', () => {
+ const list = [{
+ id: 'c1', name: 'Mara', role: 'suspect',
+ physicalDescription: 'the arsonist who burned the mill',
+ background: 'set the fire in Issue 8',
+ revealIssue: 8,
+ surfaceDescriptor: 'a quiet neighbor who keeps to herself',
+ }];
+ const out = filterCanonListForIssue(list, 'character', 2);
+ expect(out).toHaveLength(1);
+ expect(out[0].physicalDescription).toBe('a quiet neighbor who keeps to herself');
+ expect(out[0].name).toBe('Mara');
+ expect(out[0].role).toBe('suspect');
+ expect(out[0].surfaced).toBe(true);
+ // The secret fields are gone.
+ expect(out[0].background).toBeUndefined();
+ });
+ it('drops a gated entry entirely when it has no surfaceDescriptor', () => {
+ const list = [{ id: 'c1', name: 'Twist', description: 'the real killer', revealIssue: 8 }];
+ expect(filterCanonListForIssue(list, 'object', 2)).toEqual([]);
+ });
+ it('substitutes the place description field for a gated place', () => {
+ const list = [{
+ id: 'p1', name: 'East Wing', slugline: 'INT. EAST WING',
+ description: 'the wing where the heir is imprisoned',
+ revealIssue: 5,
+ surfaceDescriptor: 'the locked east wing nobody enters',
+ }];
+ const out = filterCanonListForIssue(list, 'place', 3);
+ expect(out[0].description).toBe('the locked east wing nobody enters');
+ expect(out[0].slugline).toBe('INT. EAST WING');
+ });
+ it('reveals the full entry at/after the reveal issue', () => {
+ const list = [{ id: 'c1', name: 'Mara', physicalDescription: 'the arsonist', revealIssue: 8, surfaceDescriptor: 'a neighbor' }];
+ expect(filterCanonListForIssue(list, 'character', 8)[0].physicalDescription).toBe('the arsonist');
+ });
+ });
+
+ describe('filterCanonForIssue — whole bundle', () => {
+ it('filters all three kinds and returns empty for a nullish canon', () => {
+ expect(filterCanonForIssue(null, 1)).toEqual({ characters: [], places: [], objects: [] });
+ const canon = {
+ characters: [{ id: 'c', name: 'C', spoiler: true }],
+ places: [{ id: 'p', name: 'P' }],
+ objects: [{ id: 'o', name: 'O', revealIssue: 4, surfaceDescriptor: 'a plain box', description: 'the bomb' }],
+ };
+ const out = filterCanonForIssue(canon, 2);
+ expect(out.characters).toEqual([]); // hard spoiler, no surface → dropped
+ expect(out.places).toHaveLength(1); // ungated
+ expect(out.objects[0].description).toBe('a plain box'); // surfaced
+ });
+ });
+
+ describe('canonHasRevealGated + revealGatedCanonRows', () => {
+ it('is false when nothing is gated, true when any entry is gated', () => {
+ expect(canonHasRevealGated({ characters: [{ name: 'A' }] })).toBe(false);
+ expect(canonHasRevealGated({ characters: [{ name: 'A', revealIssue: 3 }] })).toBe(true);
+ expect(canonHasRevealGated({ objects: [{ name: 'O', spoiler: true }] })).toBe(true);
+ expect(canonHasRevealGated(null)).toBe(false);
+ });
+ it('enumerates gated rows with kind/name/reveal/spoiler/fact', () => {
+ const canon = {
+ characters: [{ name: 'Mara', physicalDescription: 'arsonist', background: 'lit the fire', revealIssue: 8, surfaceDescriptor: 'a neighbor' }],
+ objects: [{ name: 'Box', description: 'the bomb', spoiler: true }],
+ places: [{ name: 'Plain Room' }],
+ };
+ const rows = revealGatedCanonRows(canon);
+ expect(rows).toHaveLength(2);
+ const mara = rows.find((r) => r.name === 'Mara');
+ expect(mara.kind).toBe('character');
+ expect(mara.revealIssue).toBe(8);
+ expect(mara.spoiler).toBe(false);
+ expect(mara.surfaceDescriptor).toBe('a neighbor');
+ expect(mara.fact).toContain('arsonist');
+ expect(mara.fact).toContain('lit the fire');
+ const box = rows.find((r) => r.name === 'Box');
+ expect(box.spoiler).toBe(true);
+ expect(box.revealIssue).toBeNull();
+ });
+ });
+});
diff --git a/server/services/pipeline/perspectiveRewrite.js b/server/services/pipeline/perspectiveRewrite.js
index ac36a31ca6..36d24016dc 100644
--- a/server/services/pipeline/perspectiveRewrite.js
+++ b/server/services/pipeline/perspectiveRewrite.js
@@ -25,6 +25,7 @@ import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';
import { runStagedLLM, resolveStageContext } from '../../lib/stageRunner.js';
import { manuscriptContentBudgetChars, estimateTokens } from '../../lib/contextBudget.js';
import { richCanonDescriptorFragments, flattenCanonDescriptorFragments } from '../../lib/canonPrompt.js';
+import { filterCanonListForIssue } from '../../lib/storyBible.js';
import { getIssue } from './issues.js';
import { getSeries } from './series.js';
import { getSeriesCanon } from './seriesCanon.js';
@@ -110,9 +111,24 @@ function shapeCastEntry(char) {
};
}
-async function resolveCast(series) {
+// Resolve the cast for a rewrite prompt at `issueNumber`. This is a
+// writer-facing GENERATIVE prompt (it grounds regenerated prose in the cast's
+// full canon, incl. background/personality), so it must reveal-gate the canon
+// exactly like `buildStageContext` (#2178) — a later-reveal character's secret
+// must not leak into an earlier issue's rewrite. `keepFullId` (the POV
+// character being rewritten FROM) is exempt: the narrator knows their own
+// secrets, so they keep their full record even when gated. Absent
+// `issueNumber` = no gate (backward compatible).
+async function resolveCast(series, issueNumber, keepFullId = null) {
const canon = series ? await getSeriesCanon(series).catch(() => ({ characters: [] })) : { characters: [] };
- return (canon.characters || []).map(shapeCastEntry).filter(Boolean);
+ const chars = Array.isArray(canon.characters) ? canon.characters : [];
+ const gated = Number.isFinite(issueNumber)
+ ? chars.map((c) => (c?.id && c.id === keepFullId
+ ? c
+ : filterCanonListForIssue([c], 'character', issueNumber)[0]))
+ .filter(Boolean)
+ : chars;
+ return gated.map(shapeCastEntry).filter(Boolean);
}
// ---------- sanitize LLM analysis ----------
@@ -221,7 +237,9 @@ export async function generatePerspectiveRewrite(issueId, { povCharacterId, sour
if (!picked) return { status: 'no-content', issueId, seriesId: issue.seriesId };
const series = await getSeries(issue.seriesId).catch(() => null);
- const cast = await resolveCast(series);
+ // Reveal-gate the cast to this issue's horizon (#2178) — but keep the POV
+ // character (the narrator) full, since they know their own secrets.
+ const cast = await resolveCast(series, issue.number, povCharacterId);
const pov = cast.find((c) => c.id === povCharacterId || c.name === povCharacterId);
if (!pov) return { status: 'unknown-character', issueId, seriesId: issue.seriesId, povCharacterId };
diff --git a/server/services/pipeline/seriesCanon.js b/server/services/pipeline/seriesCanon.js
index 4f8d48d29a..cd6b7c1944 100644
--- a/server/services/pipeline/seriesCanon.js
+++ b/server/services/pipeline/seriesCanon.js
@@ -31,6 +31,18 @@ export const pickCanon = (universe) => ({
* universe record in scope. Returns frozen-empty when the series is orphan
* (no universeId) or the linked universe is missing.
*
+ * Returns the FULL canon — this reader does NOT reveal-gate (#2178). The
+ * reveal-gating contract is: a **writer-facing generative prompt** (prose /
+ * script drafting, alternate-POV rewrite) must run the result through
+ * `filterCanonForIssue` / `filterCanonListForIssue` from
+ * `server/lib/storyBible.js` before injecting it, so a later-reveal secret
+ * can't leak into an earlier issue. The **judge, editorial checks, canon
+ * extraction, arc/scene planning** intentionally consume the full canon (they
+ * need the truth and have no single issue number). New prompt-builders that
+ * load canon here for a drafting prompt MUST apply the filter; see
+ * `textStages.buildStageContext` and `perspectiveRewrite.resolveCast` for the
+ * reference call sites.
+ *
* @returns {Promise<{ characters, places, objects }>}
*/
export async function getSeriesCanon(series) {
diff --git a/server/services/pipeline/textStages.js b/server/services/pipeline/textStages.js
index 39de4381a0..aeb28a81d6 100644
--- a/server/services/pipeline/textStages.js
+++ b/server/services/pipeline/textStages.js
@@ -25,6 +25,7 @@ import { computeIssueTargets, assessSynopsisScope } from '../../lib/issueLength.
import { renderEntitiesSummary } from '../../lib/universePromptRenderers.js';
import { composeStyleNotes } from '../../lib/styleGuide.js';
import { renderTickingClock } from '../../lib/storyArc.js';
+import { filterCanonForIssue } from '../../lib/storyBible.js';
const STAGE_TO_TEMPLATE = Object.freeze({
idea: 'pipeline-idea-expansion',
@@ -369,6 +370,16 @@ function buildIssueScopeText(issue, sourceMaterials, seedInput) {
* Visual stages aren't included — text templates don't need rendered images.
*/
function buildStageContext({ series, canon, world, issue, stageId, seedInput, sourceStageIds }) {
+ // Reveal-gated canon / spoiler scoping (#2178). Filter the writer-facing canon
+ // to this issue's reveal horizon BEFORE it's scoped or rostered: a canon fact
+ // gated to a later issue is dropped (or reduced to its spoiler-free
+ // `surfaceDescriptor`) so the drafting prompt can't leak a reveal early. Both
+ // the full-record character block AND the compact world roster are filtered —
+ // they read the same universe arrays, so filtering one is not enough. Absent
+ // gate fields = always visible (full backward compat). The judge (#2167) and
+ // editorial checks bypass this and receive the FULL canon.
+ const revealCanon = filterCanonForIssue(canon, issue.number);
+ const revealWorld = world ? { ...world, ...filterCanonForIssue(world, issue.number) } : world;
const stages = {};
for (const id of TEXT_STAGE_IDS) {
if (id === stageId) break; // only include stages BEFORE the current one
@@ -391,8 +402,8 @@ function buildStageContext({ series, canon, world, issue, stageId, seedInput, so
// named in the issue's source text. Only the roster-backed stages are scoped
// (see ROSTER_BACKED_STAGES); the idea stage keeps the full cast.
const scopedCharacters = ROSTER_BACKED_STAGES.has(stageId)
- ? scopeCharactersForIssue(canon?.characters || [], buildIssueScopeText(issue, sourceMaterials, seedInput))
- : (canon?.characters || []);
+ ? scopeCharactersForIssue(revealCanon.characters, buildIssueScopeText(issue, sourceMaterials, seedInput))
+ : revealCanon.characters;
// Compact one-line-per-kind synopsis of the linked universe's canon. Lets
// per-issue text prompts reference named entities without paying the full
// canon-block token cost. The roster carries the REST of the cast — everyone
@@ -405,8 +416,8 @@ function buildStageContext({ series, canon, world, issue, stageId, seedInput, so
const scopedCharacterNames = new Set(
scopedCharacters.map((c) => (c?.name || '').trim().toLowerCase()).filter(Boolean),
);
- const worldEntitiesSummary = world
- ? (renderEntitiesSummary(world, {
+ const worldEntitiesSummary = revealWorld
+ ? (renderEntitiesSummary(revealWorld, {
maxPerKind: { characters: Infinity },
excludeCharacterNames: scopedCharacterNames,
}) || '(none)')
diff --git a/server/services/pipeline/textStages.test.js b/server/services/pipeline/textStages.test.js
index 7839ed1ae2..5d66c9e9db 100644
--- a/server/services/pipeline/textStages.test.js
+++ b/server/services/pipeline/textStages.test.js
@@ -762,6 +762,79 @@ describe('pipeline text stage generator', () => {
expect(text).toContain('SRC-B');
});
+ it('buildStageContext reveal-gates canon: hides a later-reveal character before its issue, reveals it at/after (#2178)', () => {
+ const series = { name: 'S', logline: 'l', premise: 'p' };
+ const canon = {
+ characters: [
+ { id: 'c1', name: 'Mira', role: 'lead', physicalDescription: 'the detective' },
+ {
+ id: 'c2', name: 'Vex', role: 'suspect',
+ physicalDescription: 'the true killer who poisoned the well',
+ background: 'committed the murder in Issue 8',
+ revealIssue: 8,
+ surfaceDescriptor: 'a reclusive apothecary nobody trusts',
+ },
+ ],
+ places: [], objects: [],
+ };
+ const world = { characters: canon.characters, places: [], objects: [] };
+ // The idea stage keeps the full cast (not roster-scoped), so the surfaced
+ // full record is visible directly in `series.characters`.
+ const early = textStages.__testing.buildStageContext({
+ series, canon, world, issue: { number: 2, title: 'T', stages: {} }, stageId: 'idea',
+ });
+ const vexEarly = early.series.characters.find((c) => c.name === 'Vex');
+ // Surfaced view only — the secret is gone, the surface descriptor stands in.
+ expect(vexEarly.physicalDescription).toBe('a reclusive apothecary nobody trusts');
+ expect(vexEarly.surfaced).toBe(true);
+ expect(vexEarly.background).toBeUndefined();
+
+ const late = textStages.__testing.buildStageContext({
+ series, canon, world, issue: { number: 8, title: 'T', stages: {} }, stageId: 'idea',
+ });
+ const vexLate = late.series.characters.find((c) => c.name === 'Vex');
+ expect(vexLate.physicalDescription).toBe('the true killer who poisoned the well');
+ expect(vexLate.background).toBe('committed the murder in Issue 8');
+ });
+
+ it('buildStageContext reveal-gates the prose roster: surfaced view in worldEntitiesSummary, not the secret (#2178)', () => {
+ const series = { name: 'S', logline: 'l', premise: 'p' };
+ const canon = {
+ characters: [
+ { id: 'c1', name: 'Mira', role: 'lead', physicalDescription: 'the detective' },
+ {
+ id: 'c2', name: 'Vex', role: 'suspect',
+ physicalDescription: 'the true killer who poisoned the well',
+ revealIssue: 8,
+ surfaceDescriptor: 'a reclusive apothecary nobody trusts',
+ },
+ ],
+ places: [], objects: [],
+ };
+ const world = { characters: canon.characters, places: [], objects: [] };
+ // Prose scopes the full-record block to principals/named — Vex (not named)
+ // lands in the roster, which must show its surface view, never the secret.
+ const ctx = textStages.__testing.buildStageContext({
+ series, canon, world, issue: { number: 2, title: 'T', stages: {} }, stageId: 'prose',
+ });
+ expect(ctx.worldEntitiesSummary).not.toContain('true killer');
+ expect(ctx.worldEntitiesSummary).toContain('reclusive apothecary');
+ });
+
+ it('buildStageContext drops a hard-spoiler canon entry with no surface descriptor from context (#2178)', () => {
+ const series = { name: 'S', logline: 'l', premise: 'p' };
+ const canon = {
+ characters: [{ id: 'c1', name: 'Ghost', physicalDescription: 'the villain behind it all', spoiler: true }],
+ places: [], objects: [],
+ };
+ const world = { characters: canon.characters, places: [], objects: [] };
+ const ctx = textStages.__testing.buildStageContext({
+ series, canon, world, issue: { number: 3, title: 'T', stages: {} }, stageId: 'prose',
+ });
+ expect(ctx.series.characters.find((c) => c.name === 'Ghost')).toBeUndefined();
+ expect(ctx.worldEntitiesSummary).not.toContain('villain behind it all');
+ });
+
it('does NOT scope the idea stage — it gets the full cast (no roster in that template)', async () => {
const { series } = await seed();
const world = await universeSvc.createUniverse({ name: 'Seed Verse' });