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: inject worldbuilding craft doctrine into generation + add world.* editorial checks (#2175)

[._.]/ Adam Eivyc4b66aa97201
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 17228ae8fc..c9fa23936b 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -22,6 +22,7 @@
- **[issue-2194] The voice-drift engine now has a dedicated matrix view showing every issue's full fingerprint, not just the flagged outliers.** A new deep-linkable **Voice Fingerprint** page (`/pipeline/series/:seriesId/voice-fingerprint`, linked from the series header and reachable via ⌘K / voice) renders the whole issues×metrics matrix as a monospace table — one row per drafted issue, one column per fingerprint metric (sentence rhythm, fragment/long-sentence rates, paragraph shape, dialogue ratio, em-dash rate, abstract-noun/simile density, dominant opener, plus any configured vocabulary wells) — with each statistical outlier cell highlighted in amber and a series mean/σ footer. Where the `style.voice-drift` editorial finding only names the flagged outliers in prose, this view shows the full picture at a glance, reading the same per-series config (drift threshold, min issues, vocabulary wells) as the check. Read-only, no LLM cost.
- **[issue-2168] A new "adversarial cuts" editorial check and mechanical applier tightens prose by identifying what a ruthless editor would cut.** The `prose.adversarial-cuts` check asks an LLM editor persona to cut 8–12% of the text as 10–20 passages, classifying each cut by type: FAT (purple prose), REDUNDANT (repeated information), OVER-EXPLAIN (spelling out what's clear), GENERIC (stock phrases), TELL (emotion-telling after showing), or STRUCTURAL (scenes that don't advance the story). Each cut lands as a manuscriptReview finding with the exact verbatim quote. The Manuscript Editor gains an "Apply safe cuts" action that batch-removes OVER-EXPLAIN and REDUNDANT cuts mechanically — exact string match with whitespace-normalized fallback, refusing ambiguous or too-short quotes — through the same snapshotted stage-write path fixes use (full undo via version history). The check also reports `fat_percentage`, `tightest_passage` (protected), and `loosest_passage` for a quick health read.
- **[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.)
## Human Activity Tracking
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index efe7aeedad..6d410b8347 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -548,6 +548,20 @@
"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.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
+ },
+ "pipeline-editorial-world-cost-free-power": {
+ "name": "Pipeline — Editorial Check: Cost-free power",
+ "description": "Editorial check (#2175): flags an ability, technology, or magic used at a decisive moment with no cost, limitation, or price paid on the page (Sanderson's Second Law — limitations are more interesting than powers). Reconciles the stitched manuscript against the established world canon and continuity-bible world-rule facts, so a use that pays the established cost — or a power the canon defines as limitless — is not flagged. Returns issue-anchored findings.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
+ },
"pipeline-editorial-comic-page-turn": {
"name": "Pipeline — Editorial Check: Comic page-turn beats",
"description": "Editorial check (#1314): flags comic reveals/cliffhangers placed where the reader sees them early — on a page that shares its two-page spread with earlier pages rather than the first page after a page turn. Reads each issue's parsed comic-page layout and reconciles placement against the authored reader-map reveals/cliffhangers. Returns issue-anchored findings.",
diff --git a/data.reference/prompts/stages/pipeline-editorial-world-cost-free-power.md b/data.reference/prompts/stages/pipeline-editorial-world-cost-free-power.md
new file mode 100644
index 0000000000..06c6eabf1c
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-editorial-world-cost-free-power.md
@@ -0,0 +1,78 @@
+# Pipeline — Editorial Check: Cost-free power
+
+You are a developmental editor doing a single focused pass for ONE concern:
+**cost-free powers** — abilities used at decisive moments with no price paid on
+the page. The rule (Sanderson's Second Law): *limitations are more interesting
+than powers.* A magic or technology that always works, at any scale, with no
+drawback drains tension from every scene it touches — the reader stops fearing
+for anyone.
+
+Flag a use when ALL of these hold:
+
+- An **ability, technology, or magic** is used at a **decisive moment** —
+ resolving a conflict, escaping danger, saving someone, or turning a scene.
+- The use pays **no cost or limitation on the page** — no fuel, blood, memory,
+ time, reputation, physical toll, risk, or hard cap on scale/range is spent or
+ even acknowledged.
+- The world canon / established rules give that system a cost or limit it is
+ **supposed** to carry (see below) — OR the prose itself has established one
+ elsewhere — and this decisive use quietly skips it.
+
+Do NOT flag: a use that DOES pay its established price (that is the system
+working as designed); a power the canon explicitly defines as limitless for a
+stated reason; a trivial, non-decisive use where cost would be pedantic; the
+FIRST introduction of a power whose costs the story is clearly still unfolding.
+
+{{#canonWorld}}
+## World canon (established — the costs/limits each system should carry)
+
+{{canonWorld}}
+{{/canonWorld}}
+
+{{#worldRules}}
+## Continuity-bible world rules (established ground truth)
+
+{{worldRules}}
+{{/worldRules}}
+
+## Manuscript
+
+The manuscript is stitched from the drafted issues. Section headers attribute
+each chunk to an issue (e.g. `# Issue 3 — Title (prose)`). Use the issue number
+in each header to attribute every finding to its `issueNumber`.
+
+```
+{{manuscript}}
+```
+
+## Task
+
+Flag every decisive use of a power/ability that skips the cost or limitation it
+should carry. For each, quote a short verbatim anchor (≤ 200 characters), name
+the issue number, name the power and the price it skipped, and suggest the fix
+(exact a cost on the page, cap the scale, or give the moment a limitation that
+forces a hard choice). Mark a climactic conflict resolved by a limitation-free
+power `high`; a smaller scene-level one `medium` or `low`.
+
+Be specific and cite the text. If every decisive use pays its established price,
+return an empty `findings` array — do not invent issues.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no
+commentary:
+
+```json
+{
+ "findings": [
+ {
+ "severity": "high|medium|low",
+ "issueNumber": 5,
+ "location": "string — where the cost-free use lands (e.g. 'Issue 5 — the escape')",
+ "problem": "1–3 sentences naming the power, the decisive moment, and the cost/limit it skipped",
+ "suggestion": "1–3 sentences on the fix — exact a cost, cap the scale, or add a limitation that forces a choice",
+ "anchorQuote": "short verbatim quote from the manuscript (≤ 200 chars)"
+ }
+ ]
+}
+```
diff --git a/data.reference/prompts/stages/pipeline-editorial-world-unforeshadowed-solution.md b/data.reference/prompts/stages/pipeline-editorial-world-unforeshadowed-solution.md
new file mode 100644
index 0000000000..60df76baaa
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-editorial-world-unforeshadowed-solution.md
@@ -0,0 +1,97 @@
+# Pipeline — Editorial Check: Unforeshadowed solution
+
+You are a developmental editor doing a single focused pass for ONE concern:
+**unforeshadowed solutions** — the worldbuilding sibling of the deus ex machina.
+The rule (Sanderson's First Law): *the ability to solve problems with a
+world's magic/technology is proportional to how well the reader already
+understands that magic/technology.* A problem resolved by a rule, power,
+property, or artifact the reader was NEVER shown reads as a cheat, no matter how
+internally consistent it is.
+
+Flag a solution when ALL of these hold:
+
+- It **resolves a real story problem** — escapes a trap, wins a fight, saves a
+ character, turns a scene, or closes the plot.
+- It relies on a **rule / power / property / artifact** of the world's
+ magic or technology.
+- That mechanism was **never planted** — not demonstrated, explained, or even
+ hinted at before the moment it saves the day.
+
+A mechanism counts as **planted** (do NOT flag) when the prose established it
+earlier — the reader saw the power used, was told the rule, or the artifact
+appears in the world canon below — even if the specific application is new. A
+clever new *use* of an established rule is good craft, not a cheat.
+
+{{#finalPart}}
+This is the **final part** of the manuscript, so you can now judge the whole
+arc: read the rules/powers/artifacts established in earlier parts (the setup
+digest above, when present) together with this part, and flag any solution built
+on a mechanism you can confirm was **never planted anywhere**.
+{{/finalPart}}
+{{^finalPart}}
+**You are reading the manuscript in PARTS and have not yet seen the later
+parts** — but a mechanism used here may have been planted in a part you already
+carried in the setup digest above. Do NOT flag a solution as unforeshadowed
+unless you can confirm its mechanism appears nowhere in this part OR the carried
+setup. When unsure, defer to the final part.
+{{/finalPart}}
+
+Do NOT flag: a solution that pays off a rule planted earlier (that is good
+setup→payoff); ordinary physical/interpersonal problem-solving that uses no
+special world mechanic; a deliberately mysterious power the story is clearly
+still withholding for a planned later reveal.
+
+{{#canonWorld}}
+## World canon (already established)
+
+{{canonWorld}}
+{{/canonWorld}}
+
+{{#worldRules}}
+## Continuity-bible world rules (established ground truth)
+
+{{worldRules}}
+{{/worldRules}}
+
+## Manuscript
+
+The manuscript is stitched from the drafted issues. Section headers attribute
+each chunk to an issue (e.g. `# Issue 3 — Title (prose)`). Use the issue number
+in each header to attribute every finding to its `issueNumber`.
+
+```
+{{manuscript}}
+```
+
+## Task
+
+Flag every solution that resolves a story problem using a world mechanic the
+reader was never shown. For each, quote a short verbatim anchor (≤ 200
+characters), name the issue number, name the mechanism and the problem it
+resolved, and suggest the fix (plant the rule/power earlier, or resolve the
+problem through an established capability instead). Mark a climactic solution
+built on a wholly-unplanted rule `high`; a minor scene-level one `medium` or
+`low`.
+
+Be specific and cite the text. If every solution is earned by an established
+mechanism, return an empty `findings` array — do not invent issues.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no
+commentary:
+
+```json
+{
+ "findings": [
+ {
+ "severity": "high|medium|low",
+ "issueNumber": 7,
+ "location": "string — where the unearned solution lands (e.g. 'Issue 7 — climax')",
+ "problem": "1–3 sentences naming the mechanism used and the problem it resolved, and confirming it was never planted",
+ "suggestion": "1–3 sentences on the fix — plant the mechanism earlier, or resolve through an established capability",
+ "anchorQuote": "short verbatim quote from the manuscript (≤ 200 chars)"
+ }
+ ]
+}
+```
diff --git a/scripts/migrations/165-editorial-world-unforeshadowed-solution-stage.js b/scripts/migrations/165-editorial-world-unforeshadowed-solution-stage.js
new file mode 100644
index 0000000000..2bdd1608d6
--- /dev/null
+++ b/scripts/migrations/165-editorial-world-unforeshadowed-solution-stage.js
@@ -0,0 +1,16 @@
+/**
+ * Seed the `pipeline-editorial-world-unforeshadowed-solution` stage into existing
+ * installs (#2175).
+ *
+ * Mirrors `130-editorial-character-consistency-stage.js`: copies the `.md` template
+ * from `data.reference/prompts/stages/` and merges the stage-config entry into
+ * `data/prompts/stage-config.json`. Boot runs migrations (server/index.js) but NOT
+ * `setup-data.js`, so an upgrade that pulls + `pm2 restart`s (rather than running
+ * `update.sh`) would otherwise leave the new stage unseeded and the
+ * `world.unforeshadowed-solution` editorial check would throw "Stage not found" the
+ * first time it runs.
+ */
+
+import { makeSeedMigration } from './_seedStageHelpers.js';
+
+export default makeSeedMigration('pipeline-editorial-world-unforeshadowed-solution');
diff --git a/scripts/migrations/165-editorial-world-unforeshadowed-solution-stage.test.js b/scripts/migrations/165-editorial-world-unforeshadowed-solution-stage.test.js
new file mode 100644
index 0000000000..b295881b6b
--- /dev/null
+++ b/scripts/migrations/165-editorial-world-unforeshadowed-solution-stage.test.js
@@ -0,0 +1,84 @@
+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 './165-editorial-world-unforeshadowed-solution-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 130) — no MD5 bookkeeping, so the
+// seed / no-clobber behavior is asserted directly.
+
+const FILENAME = 'pipeline-editorial-world-unforeshadowed-solution.md';
+const STAGE_KEY = 'pipeline-editorial-world-unforeshadowed-solution';
+const BODY = '# Unforeshadowed solution\n\nshipped body\n';
+
+describe('migration 165 — seed editorial-world-unforeshadowed-solution stage', () => {
+ let rootDir;
+ let stagesDir;
+ let refStagesDir;
+ let installedConfigPath;
+
+ const seedReference = () => {
+ writeFileSync(join(refStagesDir, FILENAME), BODY);
+ const refConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ writeFileSync(
+ refConfigPath,
+ JSON.stringify({ stages: { [STAGE_KEY]: { name: STAGE_KEY, description: 'desc', model: 'default', returnsJson: true, variables: [] } } }, null, 2) + '\n',
+ );
+ };
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-165-'));
+ 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/scripts/migrations/166-editorial-world-cost-free-power-stage.js b/scripts/migrations/166-editorial-world-cost-free-power-stage.js
new file mode 100644
index 0000000000..19727ac7fb
--- /dev/null
+++ b/scripts/migrations/166-editorial-world-cost-free-power-stage.js
@@ -0,0 +1,16 @@
+/**
+ * Seed the `pipeline-editorial-world-cost-free-power` stage into existing installs
+ * (#2175).
+ *
+ * Mirrors `130-editorial-character-consistency-stage.js`: copies the `.md` template
+ * from `data.reference/prompts/stages/` and merges the stage-config entry into
+ * `data/prompts/stage-config.json`. Boot runs migrations (server/index.js) but NOT
+ * `setup-data.js`, so an upgrade that pulls + `pm2 restart`s (rather than running
+ * `update.sh`) would otherwise leave the new stage unseeded and the
+ * `world.cost-free-power` editorial check would throw "Stage not found" the first
+ * time it runs.
+ */
+
+import { makeSeedMigration } from './_seedStageHelpers.js';
+
+export default makeSeedMigration('pipeline-editorial-world-cost-free-power');
diff --git a/scripts/migrations/166-editorial-world-cost-free-power-stage.test.js b/scripts/migrations/166-editorial-world-cost-free-power-stage.test.js
new file mode 100644
index 0000000000..3fbdf6b68c
--- /dev/null
+++ b/scripts/migrations/166-editorial-world-cost-free-power-stage.test.js
@@ -0,0 +1,84 @@
+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 './166-editorial-world-cost-free-power-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 130) — no MD5 bookkeeping, so the
+// seed / no-clobber behavior is asserted directly.
+
+const FILENAME = 'pipeline-editorial-world-cost-free-power.md';
+const STAGE_KEY = 'pipeline-editorial-world-cost-free-power';
+const BODY = '# Cost-free power\n\nshipped body\n';
+
+describe('migration 166 — seed editorial-world-cost-free-power stage', () => {
+ let rootDir;
+ let stagesDir;
+ let refStagesDir;
+ let installedConfigPath;
+
+ const seedReference = () => {
+ writeFileSync(join(refStagesDir, FILENAME), BODY);
+ const refConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ writeFileSync(
+ refConfigPath,
+ JSON.stringify({ stages: { [STAGE_KEY]: { name: STAGE_KEY, description: 'desc', model: 'default', returnsJson: true, variables: [] } } }, null, 2) + '\n',
+ );
+ };
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-166-'));
+ stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ refStagesDir = join(rootDir, 'data.reference', 'prompts', 'stages');
+ installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ mkdirSync(stagesDir, { recursive: true });
+ mkdirSync(refStagesDir, { recursive: true });
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ });
+
+ it('seeds the .md template and merges the stage-config entry on a fresh install', async () => {
+ seedReference();
+ await expect(migration.up({ rootDir })).resolves.not.toThrow();
+ expect(readFileSync(join(stagesDir, FILENAME), 'utf8')).toBe(BODY);
+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));
+ expect(installed.stages[STAGE_KEY]).toMatchObject({ returnsJson: true });
+ });
+
+ it('is idempotent and never clobbers a customized .md or an existing stage-config entry', async () => {
+ seedReference();
+ const customBody = '# CUSTOMIZED — do not overwrite\n';
+ writeFileSync(join(stagesDir, FILENAME), customBody);
+ writeFileSync(
+ installedConfigPath,
+ JSON.stringify({ stages: { [STAGE_KEY]: { name: 'user-tuned', model: 'custom' } } }, null, 2) + '\n',
+ );
+
+ await migration.up({ rootDir });
+
+ expect(readFileSync(join(stagesDir, FILENAME), 'utf8')).toBe(customBody);
+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));
+ expect(installed.stages[STAGE_KEY]).toEqual({ name: 'user-tuned', model: 'custom' });
+ });
+
+ it('does not throw when the data.reference samples are missing', async () => {
+ await expect(migration.up({ rootDir })).resolves.not.toThrow();
+ expect(existsSync(join(stagesDir, FILENAME))).toBe(false);
+ });
+
+ it('matches the live shipped stage-config key + prompt file (drift catch)', () => {
+ const refConfig = JSON.parse(
+ readFileSync(join(repoRoot, 'data.reference', 'prompts', 'stage-config.json'), 'utf8'),
+ );
+ expect(refConfig.stages[STAGE_KEY], `stage-config missing ${STAGE_KEY}`).toBeTruthy();
+ expect(refConfig.stages[STAGE_KEY].returnsJson).toBe(true);
+ expect(existsSync(join(repoRoot, 'data.reference', 'prompts', 'stages', FILENAME))).toBe(true);
+ });
+});
diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.md
index 11a60d420b..d2736f420b 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`). 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`, `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 9f674b671c..623a5a86a5 100644
--- a/server/lib/editorial/checkInfra.js
+++ b/server/lib/editorial/checkInfra.js
@@ -735,6 +735,20 @@ export function continuityLedgerSummary(facts) {
// subplots reconciled against the tagged plotlines.
export const PLOT_STRUCTURE_STAGE = 'pipeline-editorial-plot-structure';
+// Stage names for the worldbuilding-doctrine LLM check pair (#2175). Both ship in
+// data.reference/prompts/stages/ + stage-config.json (fresh installs via
+// setup-data.js) and reach existing installs via seed migrations 165/166 (boot
+// runs migrations but NOT setup-data, so the migration is required or the check
+// throws "Stage not found" on first run). Both reconcile the prose against the
+// canon world summary (`canonWorldSummary`) + the continuity-bible world-rule
+// facts so an established-and-planted rule is NOT flagged:
+// - unforeshadowed-solution: a plot problem solved by a rule/power the reader was
+// never shown — deus ex machina's worldbuilding sibling.
+// - cost-free-power: an ability used at a decisive moment with no cost/limitation
+// on the page (violates "limitations > powers").
+export const WORLD_UNFORESHADOWED_SOLUTION_STAGE = 'pipeline-editorial-world-unforeshadowed-solution';
+export const WORLD_COST_FREE_POWER_STAGE = 'pipeline-editorial-world-cost-free-power';
+
// Stage name for the series-wide pacing / intensity escalation-curve LLM check
// (#1618). Ships in data.reference/prompts/stages/ + stage-config.json (fresh
// installs via setup-data.js) and migrates to existing installs via migration 140
@@ -949,6 +963,44 @@ export function canonRosterNamesSummary(canon) {
return `Known characters (already in the story bible — do NOT flag these or their aliases):\n${lines.join('\n')}`;
}
+// Render the established WORLD canon (#2175) — the named objects (with their
+// significance) and places (with their recurring details) — into a compact text
+// block the worldbuilding-doctrine checks pass alongside the manuscript so the
+// model can tell a rule/power/artifact the prose ESTABLISHED (and may legitimately
+// use) from one that appears out of nowhere. Objects carry the artifacts/powers a
+// solution might draw on; places carry the world's physical logic. Prose
+// `significance` / `description` / `recurringDetails` are the fields that state
+// what a thing DOES and what it costs, so those are what get surfaced. Pure +
+// deterministic (unit-testable, token-countable) and type-guarded throughout (the
+// canon rides peer sync, so an older/hand-edited row could carry a non-string
+// field). Returns '' when no object or place has usable content (the prompt's
+// `{{#canonWorld}}` section then renders nothing and the check reasons from the
+// prose alone).
+export function canonWorldSummary(canon) {
+ const objects = Array.isArray(canon?.objects) ? canon.objects : [];
+ const places = Array.isArray(canon?.places) ? canon.places : [];
+ const trim = (v) => (typeof v === 'string' ? v.trim() : '');
+ const objectLines = [];
+ for (const o of objects) {
+ const name = trim(o?.name);
+ if (!name) continue;
+ const detail = trim(o?.significance) || trim(o?.description);
+ objectLines.push(detail ? `- ${name}: ${detail}` : `- ${name}`);
+ }
+ const placeLines = [];
+ for (const p of places) {
+ const name = trim(p?.name) || trim(p?.slugline);
+ if (!name) continue;
+ const detail = trim(p?.recurringDetails) || trim(p?.description);
+ placeLines.push(detail ? `- ${name}: ${detail}` : `- ${name}`);
+ }
+ if (!objectLines.length && !placeLines.length) return '';
+ const blocks = [];
+ if (objectLines.length) blocks.push(`Established artifacts / objects (with their significance):\n${objectLines.join('\n')}`);
+ if (placeLines.length) blocks.push(`Established places (with their recurring details):\n${placeLines.join('\n')}`);
+ return `World canon (already established in the story bible — a rule, power, or artifact drawn from here is FORESHADOWED; do NOT flag its use as unearned):\n\n${blocks.join('\n\n')}`;
+}
+
// Render the authored reader-map cliffhangers (#1298) into a compact text block
// the chapter-ending check passes alongside the manuscript so the model
// reconciles its DETECTED endings against the issue-boundary tugs the writer
diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.js
index aeed3c264d..473d3fe4e0 100644
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@ -92,6 +92,8 @@ export {
VOICE_CONSISTENCY_STAGE,
VOICE_DISTINCTIVENESS_STAGE,
WHITE_ROOM_STAGE,
+ WORLD_COST_FREE_POWER_STAGE,
+ WORLD_UNFORESHADOWED_SOLUTION_STAGE,
authoredCliffhangerSummary,
authoredPayoffsSummary,
authoredSetupPayoffSummary,
@@ -100,6 +102,7 @@ export {
canonCharacterStatesSummary,
canonCharacterTraitsSummary,
canonRosterNamesSummary,
+ canonWorldSummary,
characterVoiceProfiles,
comicIssuePages,
comicLetteringIssues,
@@ -146,6 +149,7 @@ import { characterArcChecks } from './checks/characterArc.js';
import { proseStyleChecks } from './checks/proseStyle.js';
import { dialogueChecks } from './checks/dialogue.js';
import { slopChecks } from './checks/slop.js';
+import { worldChecks } from './checks/world.js';
// Canonical display + run order of the built-in checks. Grouping the checks into
// ./checks/*.js by category (#1829) would otherwise change the observable order
@@ -178,6 +182,8 @@ const CHECK_ORDER = Object.freeze([
'arc.transitions',
'arc.regression',
'plot.structure-momentum',
+ 'world.unforeshadowed-solution',
+ 'world.cost-free-power',
'pacing.escalation-curve',
'theme.coherence',
'arc.climax-agency',
@@ -241,6 +247,7 @@ const ASSEMBLED_CHECKS = [
...continuityChecks,
...researchChecks,
...characterArcChecks,
+ ...worldChecks,
...proseStyleChecks,
...dialogueChecks,
...slopChecks,
diff --git a/server/lib/editorial/checks/world.js b/server/lib/editorial/checks/world.js
new file mode 100644
index 0000000000..7231b61187
--- /dev/null
+++ b/server/lib/editorial/checks/world.js
@@ -0,0 +1,127 @@
+// Editorial checks — world group (#2175). Worldbuilding-doctrine checks: the
+// review-side companion to the Sanderson's-Laws doctrine injected into the
+// universe-expansion generation prompt. Each entry is a declarative check; see
+// ../README.md and ../checkInfra.js.
+import {
+ WORLD_COST_FREE_POWER_STAGE,
+ WORLD_UNFORESHADOWED_SOLUTION_STAGE,
+ canonWorldSummary,
+ continuityLedgerSummary,
+ runManuscriptLlmCheck,
+ z,
+} from '../checkInfra.js';
+
+// Shared config: cap findings per run so a long manuscript can't flood the review.
+const maxFindingsSchema = z.object({
+ maxFindings: z.number().int().min(1).max(50).default(12),
+});
+const maxFindingsFields = [
+ {
+ 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.',
+ },
+];
+
+export const worldChecks = [
+ {
+ id: 'world.unforeshadowed-solution',
+ sources: ['manuscript', 'canon', 'continuityBible'],
+ label: 'Unforeshadowed solution (worldbuilding deus ex machina)',
+ description:
+ "LLM scan — the worldbuilding sibling of the plot-level deus ex machina (plot.structure-momentum). Flags a plot problem resolved by a rule, power, property, or artifact the reader was NEVER shown before it saves the day (Sanderson's First Law: the ability to solve problems with magic is proportional to how well the reader understands it). Reconciles the prose against the established world canon (named artifacts/objects + places) and the continuity-bible world-rule facts, so a rule that WAS planted earlier is NOT flagged. Because a solution can be foreshadowed pages earlier, whole-arc verdicts land on the final manuscript part with the earlier plants carried in the setup digest; degrades to a prose-only scan when no canon or world-rules exist.",
+ scope: 'series',
+ kind: 'llm',
+ category: 'world',
+ // Fallback severity when the model omits one — 'medium' to match the sibling
+ // plot/continuity LLM checks. The prompt directs the model to mark a climactic
+ // solution built on a wholly-unplanted rule 'high' per finding.
+ severityDefault: 'medium',
+ defaultEnabled: true,
+ needsManuscript: true,
+ configSchema: maxFindingsSchema,
+ configFields: maxFindingsFields,
+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,
+ run: (ctx) => {
+ // Both blocks are fixed per-call overhead (re-sent on each chunk) and pure
+ // context: the world canon names the artifacts/powers/places a solution may
+ // legitimately draw on, and the continuity-bible world-rule facts add the
+ // established mechanics. The check degrades gracefully — no canon ⇒
+ // {{#canonWorld}} renders nothing; no world-rule facts ⇒ {{#worldRules}}
+ // renders nothing and the model reasons from the prose's own setups.
+ const canonWorld = canonWorldSummary(ctx.canon);
+ const worldRules = continuityLedgerSummary(ctx.continuityBible);
+ return runManuscriptLlmCheck(ctx, {
+ stage: WORLD_UNFORESHADOWED_SOLUTION_STAGE,
+ category: 'world',
+ context: { canonWorld, worldRules },
+ buildVars: (manuscript, meta, c) => ({
+ manuscript,
+ canonWorld: c.canonWorld,
+ worldRules: c.worldRules,
+ finalPart: meta?.isFinal ? 'true' : '',
+ }),
+ // A solution's setup can be planted chapters before it fires — the findings
+ // digest keeps prior findings in view so a later chunk doesn't re-flag, and
+ // the clean-setup digest rolls forward every rule/power/artifact the prose
+ // has ESTABLISHED so the final part can tell an unforeshadowed solution from
+ // one whose plant simply sits in an earlier chunk. `isFinal` gates the
+ // verdict — a non-final chunk can't know a rule used here is established later.
+ crossChunkDigest: true,
+ crossChunkSetup: true,
+ // The verdict is gated to the final part and anchored on the carried set of
+ // established rules, so reserve room for the digest in the packed final chunk.
+ reserveSetupDigest: true,
+ setupFocus:
+ 'Track every magic/tech rule, power, property, or artifact the prose has ESTABLISHED so far (introduced, demonstrated, or explained to the reader) and where it was planted. Carry these forward so the final part can tell a solution built on an established-and-planted rule (fine) from one that draws on a capability the reader was never shown before it resolved the problem (unforeshadowed).',
+ });
+ },
+ },
+ {
+ id: 'world.cost-free-power',
+ sources: ['manuscript', 'canon', 'continuityBible'],
+ label: 'Cost-free power (limitation-free ability at a decisive moment)',
+ description:
+ "LLM scan — flags an ability, technology, or magic used at a DECISIVE moment (resolving a conflict, escaping danger, turning a scene) with no cost, limitation, or price paid on the page (Sanderson's Second Law: limitations are more interesting than powers). A power that always works, at any scale, with no drawback drains tension from every scene it touches. Reconciles against the established world canon and continuity-bible world-rule facts, so a use that DOES pay the established cost — or a power the canon defines as genuinely limitless for a reason — is not flagged. Judges each decisive use in place; a per-scene finding, so it runs per chunk without a whole-arc gate.",
+ scope: 'series',
+ kind: 'llm',
+ category: 'world',
+ severityDefault: 'medium',
+ defaultEnabled: true,
+ needsManuscript: true,
+ configSchema: maxFindingsSchema,
+ configFields: maxFindingsFields,
+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,
+ run: (ctx) => {
+ // Both blocks are fixed per-call overhead (re-sent on each chunk) and pure
+ // context: the world canon + continuity world-rule facts state the costs and
+ // limitations each system is SUPPOSED to carry, so the model can tell a use
+ // that skips the established price from a system that legitimately has none.
+ const canonWorld = canonWorldSummary(ctx.canon);
+ const worldRules = continuityLedgerSummary(ctx.continuityBible);
+ return runManuscriptLlmCheck(ctx, {
+ stage: WORLD_COST_FREE_POWER_STAGE,
+ category: 'world',
+ context: { canonWorld, worldRules },
+ buildVars: (manuscript, _meta, c) => ({
+ manuscript,
+ canonWorld: c.canonWorld,
+ worldRules: c.worldRules,
+ }),
+ // A cost-free use is judged in place (a decisive beat with no price paid),
+ // so this stays a plain per-chunk run — but the setup digest carries each
+ // power's established cost forward so a later chunk knows what price a use
+ // was supposed to pay, and the findings digest stops a re-flag of the same
+ // power across chunks.
+ crossChunkDigest: true,
+ crossChunkSetup: true,
+ setupFocus:
+ 'For each magic/tech power or ability the prose features, note the cost, limitation, or price the story has established it carries (fuel, blood, memory, time, reputation, physical toll, a hard cap on scale/range). Carry these forward so a later chunk can tell a decisive use that pays the established price from one that skips it.',
+ });
+ },
+ },
+];
diff --git a/server/lib/editorial/checks/world.test.js b/server/lib/editorial/checks/world.test.js
new file mode 100644
index 0000000000..376740d683
--- /dev/null
+++ b/server/lib/editorial/checks/world.test.js
@@ -0,0 +1,120 @@
+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 { canonWorldSummary, listChecks, getCheck } from '../checkRegistry.js';
+import { worldChecks } from './world.js';
+
+const STAGE_DIR = join(dirname(fileURLToPath(import.meta.url)), '../../../../data.reference/prompts/stages');
+const readStage = (file) => readFileSync(join(STAGE_DIR, file), 'utf-8');
+
+describe('worldbuilding-doctrine checks — registration (#2175)', () => {
+ it('registers both world.* checks as enabled series-scope LLM checks', () => {
+ const ids = worldChecks.map((c) => c.id).sort();
+ expect(ids).toEqual(['world.cost-free-power', 'world.unforeshadowed-solution']);
+ for (const id of ids) {
+ const check = getCheck(id);
+ expect(check, id).toBeTruthy();
+ expect(check.scope, id).toBe('series');
+ expect(check.kind, id).toBe('llm');
+ expect(check.category, id).toBe('world');
+ expect(check.defaultEnabled, id).toBe(true);
+ expect(check.needsManuscript, id).toBe(true);
+ // Reconciles against canon + the continuity-bible world-rule facts so an
+ // established rule is not flagged.
+ expect(check.sources, id).toContain('canon');
+ expect(check.sources, id).toContain('continuityBible');
+ }
+ });
+
+ it('both checks appear in the assembled registry (ordered slot present)', () => {
+ const all = new Set(listChecks().map((c) => c.id));
+ expect(all.has('world.unforeshadowed-solution')).toBe(true);
+ expect(all.has('world.cost-free-power')).toBe(true);
+ });
+
+ it('both checks gate off when the manuscript is empty', () => {
+ for (const check of worldChecks) {
+ expect(check.gate({ manuscript: '' }), check.id).toBe(false);
+ expect(check.gate({ manuscript: 'He drew the blade.' }), check.id).toBe(true);
+ }
+ });
+});
+
+describe('canonWorldSummary (#2175)', () => {
+ it('returns empty string when no objects or places carry usable content', () => {
+ expect(canonWorldSummary(null)).toBe('');
+ expect(canonWorldSummary({})).toBe('');
+ expect(canonWorldSummary({ objects: [], places: [] })).toBe('');
+ // Nameless rows are skipped.
+ expect(canonWorldSummary({ objects: [{ significance: 'x' }], places: [{ description: 'y' }] })).toBe('');
+ });
+
+ it('summarizes named artifacts with significance and places with recurring details', () => {
+ const out = canonWorldSummary({
+ objects: [{ name: 'The Ember Key', significance: 'burns the bearer to open a door' }],
+ places: [{ name: 'The Ashfall', recurringDetails: 'perpetual grey snow' }],
+ });
+ expect(out).toContain('World canon');
+ expect(out).toContain('The Ember Key: burns the bearer to open a door');
+ expect(out).toContain('The Ashfall: perpetual grey snow');
+ expect(out).toContain('Established artifacts / objects');
+ expect(out).toContain('Established places');
+ });
+
+ it('falls back to description and slugline, and tolerates non-string fields', () => {
+ const out = canonWorldSummary({
+ objects: [{ name: 'Relic', description: 'a cracked orb' }],
+ places: [{ slugline: 'EXT. THE VOID', recurringDetails: 42 }],
+ });
+ expect(out).toContain('Relic: a cracked orb');
+ // Non-string recurringDetails is dropped; the slugline still names the place.
+ expect(out).toContain('- EXT. THE VOID');
+ expect(out).not.toContain('42');
+ });
+});
+
+describe('worldbuilding-doctrine prompt rendering (#2175)', () => {
+ it('unforeshadowed-solution: shows canon + world rules, and the final-part gate', () => {
+ const prompt = readStage('pipeline-editorial-world-unforeshadowed-solution.md');
+ const out = applyTemplate(prompt, {
+ manuscript: '# Issue 1\n\nThe orb saved them.',
+ canonWorld: 'CANON_BLOCK',
+ worldRules: 'RULES_BLOCK',
+ finalPart: 'true',
+ });
+ expect(out).toContain("Sanderson's First Law");
+ expect(out).toContain('CANON_BLOCK');
+ expect(out).toContain('RULES_BLOCK');
+ expect(out).toContain('final part');
+ expect(out).not.toContain('{{');
+ });
+
+ it('unforeshadowed-solution: hides canon block and shows the non-final PARTS warning when empty', () => {
+ const prompt = readStage('pipeline-editorial-world-unforeshadowed-solution.md');
+ const out = applyTemplate(prompt, {
+ manuscript: '# Issue 1\n\nThe orb saved them.',
+ canonWorld: '',
+ worldRules: '',
+ finalPart: '',
+ });
+ expect(out).not.toContain('World canon (already established)');
+ expect(out).toContain('reading the manuscript in PARTS');
+ expect(out).not.toContain('{{');
+ });
+
+ it('cost-free-power: shows canon + world rules and cites the Second Law', () => {
+ const prompt = readStage('pipeline-editorial-world-cost-free-power.md');
+ const out = applyTemplate(prompt, {
+ manuscript: '# Issue 1\n\nShe teleported the army home, effortlessly.',
+ canonWorld: 'CANON_BLOCK',
+ worldRules: 'RULES_BLOCK',
+ });
+ expect(out).toContain("Sanderson's Second Law");
+ expect(out).toContain('CANON_BLOCK');
+ expect(out).toContain('RULES_BLOCK');
+ expect(out).not.toContain('{{');
+ });
+});
diff --git a/server/services/universeBuilderExpand.js b/server/services/universeBuilderExpand.js
index 4603e08184..f15043da89 100644
--- a/server/services/universeBuilderExpand.js
+++ b/server/services/universeBuilderExpand.js
@@ -168,6 +168,16 @@ Concrete compositeSheets examples:
- Universe pitch poster prompts must include a clear editorial poster structure: universe title/subtitle/logline area, dominant hero panorama, inset environment/culture/creature images, visual-language strip, color palette, materials/textures, light/atmosphere, themes/icons, and concise labeled blocks for universe, feel, aesthetic, environments, cultures, and tone. Mention that body copy should be short, clean, and readable; avoid dense tiny text.
- If the universe needs pitch posters, do not put "text" in the avoid influences. Prefer "watermark", "logo", "unreadable tiny text", "text artifacts" so title/section typography remains possible.
- When "Current universe state" is provided above: treat it as the established universe. Fields marked [LOCKED] MUST be echoed in your output exactly as given — do not reword, expand, or trim them. Unlocked current-state fields are starting points; you may refine them, but stay consistent with locked fields, the starter idea, and influences.
+
+# Worldbuilding craft doctrine (apply to premise + canon — this is what separates a lived-in world from set dressing)
+- **Limitations over powers.** What a magic/tech system CAN'T do is more interesting than what it can. Define the hard limits, costs, and rules FIRST; the powers follow.
+- **Costs must drive plot, not decorate it.** Every power/technology exacts a price (fuel, blood, memory, time, reputation) that forces hard choices on the page — not flavor text. If a capability has no cost that ever complicates a decision, cut it or give it teeth.
+- **Foreshadow before you resolve.** A problem solved using an established rule/power must have shown that rule to the reader earlier. Plant the mechanism before it saves the day, or the resolution reads as a cheat.
+- **Iceberg depth.** Imply far more history/culture/systems than you state outright — a few concrete specifics (a saying, a scar, a ruin) signal a deep world without an encyclopedia.
+- **Interconnection.** Systems, factions, geography, and economy should link so that pulling one thread visibly moves the others — a drought shifts a faction, which reprices a resource, which pressures the protagonist.
+- **Societal implications.** For each major system (magic, tech, resource), name 2–3 concrete downstream effects on daily life, class, law, or belief — who benefits, who is exploited, what taboo or ritual grew up around it.
+- **Sensory signature per location.** Give each key place one distinct sensory anchor (a smell, a sound, a quality of light) that recurs so the reader re-enters it instantly.
+
- Output JUST the JSON object. No prose before or after.`;
}
diff --git a/server/services/universeBuilderExpand.test.js b/server/services/universeBuilderExpand.test.js
index d535a83e8b..66b0b8311f 100644
--- a/server/services/universeBuilderExpand.test.js
+++ b/server/services/universeBuilderExpand.test.js
@@ -388,6 +388,21 @@ describe("universeBuilderExpand.EXPANSION_PROMPT", () => {
expect(EXPANSION_PROMPT).toContain("styleNotes:");
});
+ it("injects the worldbuilding craft doctrine (Sanderson's Laws + iceberg/interconnection) (#2175)", () => {
+ // Prevention up-front: the doctrine steers the writer model toward
+ // limitation-first systems, planted solutions, and interconnected worlds so
+ // the review-side world.* checks have less to catch. If this fails, the
+ // generation prompt has regressed to producing decorative, cost-free systems.
+ expect(EXPANSION_PROMPT).toContain("Worldbuilding craft doctrine");
+ expect(EXPANSION_PROMPT).toContain("Limitations over powers");
+ expect(EXPANSION_PROMPT).toContain("Costs must drive plot");
+ expect(EXPANSION_PROMPT).toContain("Foreshadow before you resolve");
+ expect(EXPANSION_PROMPT).toContain("Iceberg depth");
+ expect(EXPANSION_PROMPT).toContain("Interconnection");
+ expect(EXPANSION_PROMPT).toContain("Societal implications");
+ expect(EXPANSION_PROMPT).toContain("Sensory signature per location");
+ });
+
it("asks the LLM to emit structured influences alongside the prose prompts", () => {
// The renderer prepends embrace / avoid lists deterministically, so the
// schema contract must instruct the LLM to populate them.