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([issue-1309]): editorial checks for sensory balance + white-room scenes

Adam Eivy55ebc72d9145
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 727bbe673d..ca66f54d42 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **[issue-1309] Editorial checks flag thin sensory writing and ungrounded "white-room" scenes.** Two new prose checks (Create → Editorial Checks) target two of the most common reader gripes about flat scene writing. **Sensory balance** reads your drafted manuscript and flags scenes that lean almost entirely on sight while sound, smell, touch, and taste go neglected, plus sensory-bare scenes with almost no concrete grounding at all — naming exactly which sense is missing and suggesting a grounding detail to add. **White-room / ungrounded scene** flags "talking heads in a void": dialogue and action playing out with no setting, no physical blocking, and no spatial grounding the reader can stand in — distinct from sensory balance (which is about *senses*) and scene-component balance (narrative/action/dialogue mix) in that the gap here is specifically *place*. Both read your reverse-outline scene segmentation as context (using each scene's recorded setting as a white-room signal) and **degrade gracefully** to a whole-issue manuscript scan when no outline has been generated yet. Each finding anchors a verbatim quote + issue number so you can jump straight to the spot. Two new stage prompts (`pipeline-editorial-sensory-balance`, `pipeline-editorial-white-room`) ship + migrate for existing installs. (#1309)
+
- **[issue-1407] The LoRA-training form now exposes the per-run base-quant and low-RAM overrides.** The `baseQuant` (bf16 / 8-bit / 4-bit) and `lowRam` request params landed server-side under #1321 — schema, route threading, and the `LORA_TRAIN_MAX_QUANT_BITS` cap — but the training form had no controls for them, so opting a single run into a heavier or lighter frozen base than its memory-derived tier still meant a code change. The Train-LoRA panel now has two **Base quant** and **Low RAM spill** selects (both defaulting to **Auto**); an explicit pick overrides the tier — still clamped by the install's `LORA_TRAIN_MAX_QUANT_BITS` ceiling — while "Auto" sends an explicit `null` that forces the memory-derived tier. (The `null` is a deliberate clear, not an omitted key: the server re-merges `settings.loraTraining.defaults` into every run, so an omitted key would silently keep a *saved* default — `null` lets "Auto" actually beat one.) The controls only show when the mflux engine is the one that'll run; the torch/FLUX2 path trains the bf16 base and ignores them. (`client/src/components/loraTraining/TrainingPanel.jsx`, `server/lib/validation.js`, #1407)
- **Each managed app now declares where its autonomous work items live — PLAN.md, GitHub issues, GitLab issues, or JIRA.** Previously the CoS could only claim work from PLAN.md (`plan-task`) or GitHub issues (`claim-issue`) via separate per-app toggles. A new per-app **Work Tracker** setting (App settings → Edit) makes the work *source* a single explicit choice. It defaults to **Auto**, which resolves from the app's git `origin` host: a github.com remote → GitHub issues, a gitlab.* remote (incl. self-hosted) → GitLab issues, anything else → PLAN.md (JIRA is always an explicit opt-in). A new **`claim-work`** scheduled task is the single-source router: one toggle that, at dispatch, resolves the app's tracker and delegates to the matching claim flow — so the same agent still creates its own `claim/<slug>` worktree, opens its own PR/MR, and cleans up. **GitLab issue claiming is genuinely new**: a `claim-issue-gitlab` prompt drives the full 7-phase `/claim --issues` flow over `glab` issues + merge requests (the GitHub `claim-issue` flow is untouched). The legacy `plan-task` / `claim-issue` / `jira-sprint-manager` task types remain for backward compatibility. New `GET /api/apps/:id/work-tracker` resolves the effective tracker for the UI. (`server/lib/workTracker.js`, `server/services/{cosTaskGenerator,taskSchedule,apps}.js`, `server/services/taskPromptDefaults/prompts.js`, `server/routes/apps.js`, `client/src/components/apps/EditAppModal.jsx`)
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index 4b850b16f6..4c2d649486 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -513,6 +513,20 @@
"returnsJson": true,
"variables": []
},
+ "pipeline-editorial-sensory-balance": {
+ "name": "Pipeline — Editorial Check: Sensory balance",
+ "description": "Editorial check (#1309): flags scenes that lean almost entirely on sight while sound, smell, touch, and taste are neglected, and sensory-bare scenes with almost no concrete grounding. Reads the stitched manuscript plus the reverse-outline scene segmentation (degrading to a whole-issue scan when absent), naming the missing sense per finding. Returns issue-anchored findings.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
+ },
+ "pipeline-editorial-white-room": {
+ "name": "Pipeline — Editorial Check: White-room / ungrounded scene",
+ "description": "Editorial check (#1309): flags \"white-room\" scenes — dialogue and action in an undescribed void with no setting, blocking, or spatial grounding. Reads the stitched manuscript plus the reverse-outline scene segmentation (using each scene's recorded setting as a candidate signal, degrading to a whole-issue scan when absent). Returns issue-anchored findings.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
+ },
"pipeline-editorial-object-motivation": {
"name": "Pipeline — Editorial Check: Unmotivated object interaction",
"description": "Editorial check (#1288): flags moments where a character treats an object as significant without earned motivation — no recorded attachment and no on-page setup. Reads the stitched manuscript plus the canon object↔character attachments. Returns issue-anchored findings.",
diff --git a/data.reference/prompts/stages/pipeline-editorial-sensory-balance.md b/data.reference/prompts/stages/pipeline-editorial-sensory-balance.md
new file mode 100644
index 0000000000..8551014001
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-editorial-sensory-balance.md
@@ -0,0 +1,81 @@
+# Pipeline — Editorial Check: Sensory balance
+
+You are a developmental editor doing a single focused pass for ONE problem:
+**sensory imbalance** — prose that leans almost entirely on sight while sound,
+smell, touch, and taste go neglected, or scenes that are sensory-bare (events
+narrated with almost no concrete sensory grounding at all). Vivid prose engages
+more than the eye; an over-visual or sensory-thin scene reads flat and distant.
+
+For each scene, judge which senses the prose actually engages and flag:
+
+- **All-visual scenes** — everything is *seen* (looked, saw, watched, the colors,
+ the light) with no sound, smell, touch, or taste, where the moment plainly
+ invites another sense (a kitchen with no smell, a storm with no sound, an
+ embrace with no touch).
+- **Sensory-bare scenes** — action or dialogue narrated abstractly with almost no
+ concrete sensory detail of any kind, so the reader has nothing physical to hold.
+
+Do NOT flag: a deliberately spare or clinical scene whose restraint is clearly
+intentional; a brief transitional beat where dense sensory detail would drag; a
+scene that already mixes at least two or three senses in proportion to its
+length. The bar is a real scene where a missing sense (or near-total sensory
+absence) leaves the moment thin where it should be grounded.
+
+{{#sceneMap}}
+## Scene segmentation
+
+The reverse outline below segments the manuscript into scenes (with the recorded
+setting, characters present, and dominant modes). Use it to attribute each
+finding to a scene and its issue; judge the senses from the prose itself, not
+from this list.
+
+```
+{{sceneMap}}
+```
+{{/sceneMap}}
+
+## 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`. If no scene
+segmentation is provided above, scan the manuscript issue by issue instead.
+
+```
+{{manuscript}}
+```
+
+## Task
+
+Find the scenes whose sensory palette is thinnest — all-visual where another
+sense is called for, or sensory-bare. For each, quote a short verbatim anchor
+from the text (≤ 200 characters) so the editor can jump to it, name the issue
+number it appears in, name in the `location` which sense is missing or that the
+scene is sensory-bare (e.g. `Issue 3 — sound`, `Issue 3 — all-visual`,
+`Issue 5 — sensory-bare`), explain the imbalance, and suggest a concrete
+grounding detail to add. Set severity by how immersive the scene should be — a
+flat sensory palette in a pivotal, atmosphere-heavy scene is more serious than
+in a brief functional beat.
+
+Be specific and cite the text. If the manuscript engages the senses in balance
+throughout, 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": 3,
+ "location": "string — the missing sense or sensory-bare label + where (e.g. 'Issue 3 — sound')",
+ "problem": "1–3 sentences naming the sensory imbalance and why the scene needs the missing sense",
+ "suggestion": "1–3 sentences proposing a concrete grounding detail to add",
+ "anchorQuote": "short verbatim quote from the manuscript (≤ 200 chars)"
+ }
+ ]
+}
+```
diff --git a/data.reference/prompts/stages/pipeline-editorial-white-room.md b/data.reference/prompts/stages/pipeline-editorial-white-room.md
new file mode 100644
index 0000000000..b39aa403d8
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-editorial-white-room.md
@@ -0,0 +1,88 @@
+# Pipeline — Editorial Check: White-room / ungrounded scene
+
+You are a developmental editor doing a single focused pass for ONE problem:
+**white-room syndrome** — scenes with dialogue and action playing out in an
+undescribed void, with no setting, no physical blocking, and no spatial
+grounding. The reader can't tell *where* the characters are, what the space looks
+like, or how they move through it. Talking heads floating in white space.
+
+For each scene, judge whether the prose grounds it physically and flag:
+
+- **No setting** — the scene never establishes where it takes place (room, street,
+ landscape), so it reads as a void.
+- **No blocking / spatial grounding** — characters speak and act but never move,
+ touch the space, or relate to objects and distances around them; there's no
+ sense of bodies in a place.
+- **Setting stated but inert** — a location is named once and then never felt
+ again; the prose stops grounding the scene almost immediately.
+
+This is distinct from sensory balance (which asks whether a scene engages senses
+beyond sight) and from scene-component balance (which asks whether a scene mixes
+narrative/action/dialogue) — here the specific gap is *spatial* grounding: a
+place the reader can stand in.
+
+Do NOT flag: a scene whose disorientation/void is clearly deliberate (a dream, a
+sensory-deprivation beat, a deliberately abstract interlude); a brief
+transitional beat that doesn't need grounding; a scene that is already grounded
+in a place the reader can picture. The bar is a real dialogue/action scene the
+reader cannot physically locate.
+
+{{#sceneMap}}
+## Scene segmentation
+
+The reverse outline below segments the manuscript into scenes, including each
+scene's recorded `setting` and the characters present. A scene with dialogue or
+action but a blank or vague `setting` is a strong white-room candidate — confirm
+it against the prose. Judge grounding from the prose itself, not from this list
+alone.
+
+```
+{{sceneMap}}
+```
+{{/sceneMap}}
+
+## 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`. If no scene
+segmentation is provided above, scan the manuscript issue by issue instead.
+
+```
+{{manuscript}}
+```
+
+## Task
+
+Find the scenes that play out in an ungrounded void. For each, quote a short
+verbatim anchor from the text (≤ 200 characters) so the editor can jump to it,
+name the issue number it appears in, classify the gap in the `location` (e.g.
+`Issue 3 — no setting`, `Issue 4 — no blocking`, `Issue 2 — setting inert`),
+explain why the scene reads as a white room, and suggest a concrete grounding
+beat to add (establish the space, give a character a physical action in it,
+anchor the dialogue to objects or distance). Set severity by how long and
+central the ungrounded scene is — a pivotal scene with no place is more serious
+than a short exchange.
+
+Be specific and cite the text. If every scene is grounded in a place the reader
+can picture, 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": 3,
+ "location": "string — the grounding gap + where (e.g. 'Issue 3 — no setting')",
+ "problem": "1–3 sentences naming why the scene reads as an ungrounded white room",
+ "suggestion": "1–3 sentences proposing a concrete grounding beat to add",
+ "anchorQuote": "short verbatim quote from the manuscript (≤ 200 chars)"
+ }
+ ]
+}
+```
diff --git a/scripts/migrations/103-editorial-sensory-grounding-stages.js b/scripts/migrations/103-editorial-sensory-grounding-stages.js
new file mode 100644
index 0000000000..777831b7fe
--- /dev/null
+++ b/scripts/migrations/103-editorial-sensory-grounding-stages.js
@@ -0,0 +1,93 @@
+/**
+ * Seed the two scene-grounding editorial-check stages into existing installs
+ * (#1309).
+ *
+ * Mirrors `094-object-attachment-check-stages.js`: seeds BOTH new stages in one
+ * pass — copies each `.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 these
+ * stages unseeded and the `sensory.balance` / `scene.white-room` editorial checks
+ * would throw "Stage not found" the first time they run.
+ */
+
+import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';
+import { dirname, join } from 'path';
+
+const STAGES = [
+ 'pipeline-editorial-sensory-balance',
+ 'pipeline-editorial-white-room',
+];
+
+export default {
+ async up({ rootDir }) {
+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ await mkdir(stagesDir, { recursive: true });
+
+ // 1) Copy each prompt template if it isn't already present.
+ for (const stageKey of STAGES) {
+ const filename = `${stageKey}.md`;
+ const dataPath = join(stagesDir, filename);
+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', filename);
+
+ const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);
+ if (exists) {
+ console.log(`📝 ${stageKey} prompt: already present`);
+ continue;
+ }
+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
+ if (!sampleExists) {
+ console.warn(`⚠️ ${stageKey}: sample missing for ${filename} — skipping copy`);
+ continue;
+ }
+ try {
+ await copyFile(samplePath, dataPath);
+ console.log(`✅ seeded ${filename}`);
+ } catch (err) {
+ console.warn(`⚠️ ${stageKey}: copy failed for ${filename}: ${err.message}`);
+ }
+ }
+
+ // 2) Merge each stage-config entry (skip any already present).
+ const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);
+ if (!sampleConfigExists) {
+ console.warn('⚠️ 103-editorial-sensory-grounding-stages: data.reference stage-config.json missing — cannot resolve entries; skipping config write');
+ return;
+ }
+ try {
+ const sample = JSON.parse(await readFile(sampleConfigPath, 'utf8'));
+ const installedExists = await access(installedConfigPath, constants.F_OK).then(() => true, () => false);
+ const installed = installedExists
+ ? JSON.parse(await readFile(installedConfigPath, 'utf8'))
+ : { stages: {} };
+ installed.stages = installed.stages || {};
+
+ let added = 0;
+ for (const stageKey of STAGES) {
+ if (installed.stages[stageKey]) {
+ console.log(`📝 ${stageKey} stage-config: already present`);
+ continue;
+ }
+ if (!sample?.stages?.[stageKey]) {
+ console.warn(`⚠️ 103-editorial-sensory-grounding-stages: sample stage-config missing ${stageKey} — skipping`);
+ continue;
+ }
+ installed.stages[stageKey] = sample.stages[stageKey];
+ added += 1;
+ }
+
+ if (added === 0) {
+ console.log('📝 103-editorial-sensory-grounding-stages: no stage-config entries to add');
+ return;
+ }
+ await mkdir(dirname(installedConfigPath), { recursive: true });
+ await writeFile(installedConfigPath, JSON.stringify(installed, null, 2) + '\n', 'utf8');
+ const action = installedExists ? 'merged' : 'created';
+ console.log(`📝 103-editorial-sensory-grounding-stages stage-config (${action}): ${added} added`);
+ } catch (err) {
+ console.warn(`⚠️ 103-editorial-sensory-grounding-stages: stage-config merge failed: ${err.message}`);
+ }
+ },
+};
diff --git a/scripts/migrations/103-editorial-sensory-grounding-stages.test.js b/scripts/migrations/103-editorial-sensory-grounding-stages.test.js
new file mode 100644
index 0000000000..ce09292ca2
--- /dev/null
+++ b/scripts/migrations/103-editorial-sensory-grounding-stages.test.js
@@ -0,0 +1,104 @@
+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 './103-editorial-sensory-grounding-stages.js';
+
+// scripts/migrations/<this> → ../.. is the repo root (matches _testHelpers.js).
+const repoRoot = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
+
+// First-shipment seed migration (mirrors 094/095's two-file seed test) — no MD5
+// bookkeeping, so the seed/no-clobber behavior is asserted directly.
+
+const FILES = [
+ { filename: 'pipeline-editorial-sensory-balance.md', stageKey: 'pipeline-editorial-sensory-balance', body: '# Sensory balance\n\nshipped body\n', returnsJson: true },
+ { filename: 'pipeline-editorial-white-room.md', stageKey: 'pipeline-editorial-white-room', body: '# White room\n\nshipped body\n', returnsJson: true },
+];
+
+describe('migration 103 — seed scene-grounding editorial stages', () => {
+ 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-103-'));
+ 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 both .md templates and merges both stage-config entries 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-sensory-balance']).toMatchObject({ returnsJson: true });
+ expect(installed.stages['pipeline-editorial-white-room']).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' });
+ expect(installed.stages[FILES[1].stageKey]).toMatchObject({ name: FILES[1].stageKey });
+ });
+
+ 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/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.js
index a00126bf07..0b1ee147da 100644
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@ -159,6 +159,16 @@ export function authoredSetupPayoffSummary(readerMap) {
// deterministic siblings (prose.cliches, prose.modifier-stacking) need no stage.
export const DEAD_METAPHOR_STAGE = 'pipeline-editorial-dead-metaphor';
+// Stage names for the two scene-grounding LLM checks (#1309): sensory balance
+// (all-visual / sensory-bare scenes) and white-room (ungrounded, setting-less
+// scenes). Each prompt ships in data.reference/prompts/stages/ + stage-config.json
+// (fresh installs via setup-data.js) and migrates to existing installs via
+// migration 103 (boot runs migrations but NOT setup-data, so the migration is
+// required). Both consume the reverse-outline scene segmentation as context and
+// degrade to a whole-issue manuscript scan when no outline exists.
+export const SENSORY_BALANCE_STAGE = 'pipeline-editorial-sensory-balance';
+export const WHITE_ROOM_STAGE = 'pipeline-editorial-white-room';
+
// 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
@@ -905,6 +915,35 @@ const sceneLabel = (s) => {
return heading || summary || `scene ${seq}`;
};
+// Render the reverse-outline scenes into a compact text block the scene-grounding
+// LLM checks (#1309) pass alongside the manuscript so the model can attribute
+// findings to scenes and reason about each scene's recorded setting / characters.
+// Pure + deterministic so it's unit-testable and its token cost can be counted
+// into the per-chunk overhead. Returns '' when there are no scenes (the prompt's
+// `{{#sceneMap}}` section then renders nothing and the check degrades to a plain
+// whole-issue manuscript scan). Type-guarded throughout — the reverse outline
+// rides peer sync (#1348), so a hand-edited / older-peer scene could carry a
+// non-string field that a bare `.trim()` would throw on.
+export function sceneGroundingSummary(scenes) {
+ const list = Array.isArray(scenes) ? scenes : [];
+ const lines = list.map((s) => {
+ if (!s || typeof s !== 'object') return '';
+ const label = sceneLabel(s);
+ const issueNumber = Number.isInteger(s.issueNumber) ? s.issueNumber : null;
+ const where = issueNumber != null ? `Issue ${issueNumber}` : 'Scene';
+ const setting = typeof s.setting === 'string' ? s.setting.trim() : '';
+ const chars = Array.isArray(s.charactersPresent)
+ ? s.charactersPresent.filter((n) => typeof n === 'string' && n.trim()).map((n) => n.trim())
+ : [];
+ const parts = [`- ${where}: ${label}`];
+ parts.push(setting ? `setting: ${setting}` : 'setting: (none recorded)');
+ if (chars.length) parts.push(`present: ${chars.join(', ')}`);
+ return parts.join(' — ');
+ }).filter(Boolean);
+ if (!lines.length) return '';
+ return `Scenes (from the reverse outline):\n${lines.join('\n')}`;
+}
+
// ---------------------------------------------------------------------------
// Registry entries.
// ---------------------------------------------------------------------------
@@ -1289,6 +1328,92 @@ export const EDITORIAL_CHECKS = [
return findings;
},
},
+ {
+ id: 'sensory.balance',
+ sources: ['manuscript', 'reverseOutline'],
+ label: 'Sensory balance (all-visual / sensory-bare scenes)',
+ description:
+ 'Flags scenes that lean almost entirely on sight while sound, smell, touch, and taste are neglected, and sensory-bare scenes with almost no concrete grounding. Reads the stitched manuscript plus the reverse-outline scene segmentation as context, naming the missing sense per finding.',
+ scope: 'scene',
+ kind: 'llm',
+ category: 'style',
+ severityDefault: 'low',
+ defaultEnabled: true,
+ // Reads the stitched manuscript corpus — so the runner only pays the
+ // section-collection I/O when a manuscript-consuming check is enabled.
+ needsManuscript: true,
+ configSchema: z.object({
+ // Cap findings per run so a long manuscript can't flood the review.
+ maxFindings: z.number().int().min(1).max(50).default(12),
+ }),
+ configFields: [
+ {
+ key: 'maxFindings',
+ label: 'Max findings per run',
+ type: 'number',
+ min: 1,
+ max: 50,
+ step: 1,
+ help: 'Cap findings so a long manuscript can not flood the review.',
+ },
+ ],
+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,
+ run: (ctx) => {
+ // The scene map is fixed per-call overhead (re-sent on each chunk). It's
+ // context only — the check degrades gracefully to a whole-issue scan when
+ // no reverse outline exists (the prompt's {{#sceneMap}} renders nothing).
+ const sceneMap = sceneGroundingSummary(ctx.reverseOutline);
+ return runManuscriptLlmCheck(ctx, {
+ stage: SENSORY_BALANCE_STAGE,
+ category: 'style',
+ overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS + estimateTokens(sceneMap),
+ buildVars: (manuscript) => ({ manuscript, sceneMap }),
+ });
+ },
+ },
+ {
+ id: 'scene.white-room',
+ sources: ['manuscript', 'reverseOutline'],
+ label: 'White-room / ungrounded scene',
+ description:
+ 'Flags "white-room" scenes — dialogue and action in an undescribed void with no setting, blocking, or spatial grounding. Reads the stitched manuscript plus the reverse-outline scene segmentation, using each scene\'s recorded setting as a candidate signal. Distinct from sensory balance (senses) and scene-component balance (narrative/action/dialogue mix) — the gap here is specifically spatial grounding.',
+ scope: 'scene',
+ kind: 'llm',
+ category: 'style',
+ severityDefault: 'medium',
+ defaultEnabled: true,
+ // Reads the stitched manuscript corpus — so the runner only pays the
+ // section-collection I/O when a manuscript-consuming check is enabled.
+ needsManuscript: true,
+ configSchema: z.object({
+ // Cap findings per run so a long manuscript can't flood the review.
+ maxFindings: z.number().int().min(1).max(50).default(12),
+ }),
+ configFields: [
+ {
+ key: 'maxFindings',
+ label: 'Max findings per run',
+ type: 'number',
+ min: 1,
+ max: 50,
+ step: 1,
+ help: 'Cap findings so a long manuscript can not flood the review.',
+ },
+ ],
+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,
+ run: (ctx) => {
+ // The scene map is fixed per-call overhead (re-sent on each chunk). Each
+ // scene's recorded `setting` is a strong white-room signal (blank ⇒ likely
+ // ungrounded); the check degrades to a whole-issue scan when no outline exists.
+ const sceneMap = sceneGroundingSummary(ctx.reverseOutline);
+ return runManuscriptLlmCheck(ctx, {
+ stage: WHITE_ROOM_STAGE,
+ category: 'style',
+ overheadTokens: EDITORIAL_PROMPT_OVERHEAD_TOKENS + estimateTokens(sceneMap),
+ buildVars: (manuscript) => ({ manuscript, sceneMap }),
+ });
+ },
+ },
{
id: 'pov.justified',
sources: ['reverseOutline', 'editorialArcs'],
diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.js
index b53e35e021..f403fc7b0e 100644
--- a/server/lib/editorial/checkRegistry.test.js
+++ b/server/lib/editorial/checkRegistry.test.js
@@ -29,6 +29,7 @@ import {
EDITORIAL_SETUP_DIGEST_SOURCE,
authoredSetupPayoffSummary,
authoredCliffhangerSummary,
+ sceneGroundingSummary,
} from './checkRegistry.js';
const NAMING = 'naming.dissimilar-names';
@@ -37,6 +38,8 @@ const INTERIORITY = 'interiority.protagonist';
const CHEKHOV = 'chekhov.setups-payoffs';
const ENDINGS_CLIFF = 'endings.cliffhanger';
const POV_SWITCH = 'endings.pov-switch';
+const SENSORY_BALANCE = 'sensory.balance';
+const WHITE_ROOM = 'scene.white-room';
// A minimal valid stored custom-check definition.
const customDef = (over = {}) => ({
@@ -279,6 +282,113 @@ describe('prose.info-dumping — LLM check', () => {
});
});
+describe('sceneGroundingSummary (#1309)', () => {
+ it('renders each scene with its setting and characters present', () => {
+ const summary = sceneGroundingSummary([
+ { sequence: 0, issueNumber: 1, heading: 'The kitchen', setting: 'a cramped galley kitchen', charactersPresent: ['Mara', 'Joss'] },
+ { sequence: 1, issueNumber: 2, heading: 'On the call', setting: '', charactersPresent: ['Mara'] },
+ ]);
+ expect(summary).toContain('Scenes (from the reverse outline):');
+ expect(summary).toContain('Issue 1: The kitchen — setting: a cramped galley kitchen — present: Mara, Joss');
+ // A blank setting renders the explicit "(none recorded)" marker (the white-room signal).
+ expect(summary).toContain('Issue 2: On the call — setting: (none recorded) — present: Mara');
+ });
+
+ it('returns "" for an empty / non-array outline so the prompt section renders nothing', () => {
+ expect(sceneGroundingSummary([])).toBe('');
+ expect(sceneGroundingSummary(null)).toBe('');
+ expect(sceneGroundingSummary(undefined)).toBe('');
+ });
+
+ it('tolerates malformed scenes (peer-sync resilience) without throwing', () => {
+ const summary = sceneGroundingSummary([
+ null,
+ { sequence: 2, heading: 42, setting: 99, charactersPresent: 'not-an-array' },
+ { sequence: 3, summary: 'falls back to summary label' },
+ ]);
+ // Non-string heading falls back to the sequence label; bad setting → "(none recorded)".
+ expect(summary).toContain('scene 3 — setting: (none recorded)');
+ expect(summary).toContain('falls back to summary label');
+ expect(() => sceneGroundingSummary([{ charactersPresent: [1, 2, null] }])).not.toThrow();
+ });
+});
+
+describe.each([
+ { id: SENSORY_BALANCE, severityDefault: 'low', label: 'sensory.balance' },
+ { id: WHITE_ROOM, severityDefault: 'medium', label: 'scene.white-room' },
+])('$label — scene-grounding LLM check (#1309)', ({ id, severityDefault }) => {
+ const wholeCtx = (overrides = {}) => ({
+ manuscript: '# Issue 1\n\n"We have to go," she said.',
+ reverseOutline: [{ sequence: 0, issueNumber: 1, heading: 'The void', setting: '', charactersPresent: ['Mara'] }],
+ config: { maxFindings: 12 },
+ severityDefault,
+ planManuscriptChunks: async () => [overrides.manuscript ?? '# Issue 1\n\n"We have to go," she said.'],
+ callStagedLLM: async () => ({ content: { findings: [] } }),
+ ...overrides,
+ });
+
+ it('is registered as a manuscript+reverseOutline LLM check with category style', () => {
+ const check = getCheck(id);
+ expect(check.kind).toBe('llm');
+ expect(check.scope).toBe('scene');
+ expect(check.category).toBe('style');
+ expect(check.needsManuscript).toBe(true);
+ expect(check.sources).toEqual(expect.arrayContaining(['manuscript', 'reverseOutline']));
+ expect(check.severityDefault).toBe(severityDefault);
+ });
+
+ it('gates on a non-empty manuscript', () => {
+ const check = getCheck(id);
+ expect(check.gate({ manuscript: '' })).toBe(false);
+ expect(check.gate({ manuscript: '# Issue 1\n\nprose' })).toBeTruthy();
+ });
+
+ it('injects the scene map into the prompt vars and counts it into the chunk overhead', async () => {
+ let seenVars = null;
+ let seenOverhead = 0;
+ const ctx = wholeCtx({
+ planManuscriptChunks: async (_stage, opts) => {
+ seenOverhead = opts.overheadTokens;
+ return ['# Issue 1\n\nchunk'];
+ },
+ callStagedLLM: async (_stage, vars) => {
+ seenVars = vars;
+ return { content: { findings: [{ severity: severityDefault, issueNumber: 1, problem: 'flat scene', anchorQuote: 'go' }] } };
+ },
+ });
+ const findings = await getCheck(id).run(ctx);
+ // The scene map rode along as a prompt var and inflated the overhead budget.
+ expect(seenVars.sceneMap).toContain('Issue 1: The void');
+ expect(seenOverhead).toBeGreaterThan(0);
+ expect(findings).toHaveLength(1);
+ expect(findings[0].category).toBe('style');
+ expect(findings[0].issueNumber).toBe(1);
+ });
+
+ it('degrades to a whole-issue scan (empty scene map) when no reverse outline exists', async () => {
+ let seenVars = null;
+ const ctx = wholeCtx({
+ reverseOutline: undefined,
+ callStagedLLM: async (_stage, vars) => {
+ seenVars = vars;
+ return { content: { findings: [] } };
+ },
+ });
+ await getCheck(id).run(ctx);
+ expect(seenVars.sceneMap).toBe('');
+ });
+
+ it('respects maxFindings as a whole-run cap', async () => {
+ const many = Array.from({ length: 30 }, (_, i) => ({ severity: 'low', problem: `p${i}`, anchorQuote: `a${i}` }));
+ const ctx = wholeCtx({
+ config: { maxFindings: 4 },
+ callStagedLLM: async () => ({ content: { findings: many } }),
+ });
+ const findings = await getCheck(id).run(ctx);
+ expect(findings).toHaveLength(4);
+ });
+});
+
describe('interiority.protagonist — LLM check (#1294)', () => {
const wholeCtx = (overrides = {}) => ({
manuscript: '# Issue 1\n\nShe walked into the room and sat down.',