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-1284]): editorial check registry + runner backbone

[._.]/ Adam Eivy1050f701dba1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 45e71aafc9..73be4df34c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **Editorial checks — an extensible editorial-review system for the series pipeline.** Editorial rules (name confusability, exposition dumps, and more to come) previously had no shared home — each was a one-off. A new **editorial check registry + runner** lets each rule plug in, declare what it examines, and emit findings into the same manuscript-review comment set you already work through in the editor (jump-to, AI fix, accept/dismiss). This first release ships two reference checks: **Character name dissimilarity** (flags character names a reader could confuse — sharing a first letter, length, vowel pattern, opening, or ending) and **Info-dumping** (flags "as-you-know-Bob" exposition — backstory bricks, maid-and-butler dialogue, front-loaded world rules — with a suggestion to dramatize or trim each). Each check can be enabled/disabled and configured, and runs on demand for a series (with live progress) or automatically as part of Series Autopilot's editorial pass. Findings are tagged by which check raised them, so re-running never duplicates them and a dismissal stays dismissed for that check. New endpoints: `GET/PATCH /api/pipeline/editorial/checks` (catalog + enable/config) and `POST /api/pipeline/series/:id/editorial/checks/run` (run + SSE progress). (#1284)
+
- **Series Autopilot — drive a whole series end-to-end autonomously.** A new `POST /api/pipeline/series/:id/autopilot/start` runs a *conductor* that inspects the series' current state and walks every missing step in order — generate arc → generate episodes per volume → verify arc → per-issue beat sheets → per-issue text stages (prose + scripts) → structural comic-script gate → series-level editorial review → **canon descriptive-integrity gate** → **draft cover + back cover + all interior comic pages** — by composing the existing pipeline service functions (it never re-implements generation). The "what's next" decision is a **pure resolver over the canonical records**, so it is non-destructive and resumable: anything already `ready`/`edited`/rendered is skipped (every pass runs `force:false`), and on restart you just start again and it picks up at the first still-missing step (a partially-built series is never clobbered). Progress streams over SSE (`/autopilot/progress`); `/autopilot/cancel` stops it (propagating to the active child runner); `/autopilot/status` exposes a thin persisted `series.autopilot` marker for resume/paused UI. Gated on the **cos** autonomy domain: `off` rejects the start (409), `dry-run` emits a no-side-effect `plan` of what it would do, `execute` runs and meters the daily cos action budget (pausing when exhausted — every draft render is one budget-gated action, since a comic is many GPU jobs). The arc-verify and editorial loops are **bounded** and **pause for human review** when they can't converge (arc verification can surface fresh findings every pass) — the residual findings are persisted on the marker. Draft renders are fire-and-forget proof-quality jobs whose in-flight job ids are persisted onto each cover/page slot (so a resumed run never re-renders an already-queued slot). Boot recovery demotes a marker stuck at `running` to `paused`. With opt-in `fileGaps`, capability/quality gaps the run can't resolve on its own — an unparseable script, a failing render, a stalled verify/editorial gate, a run-ending error — are filed as **deduped CoS tasks** (scoped to the pipeline app) so they're tracked rather than silently swallowed. The per-issue script gate runs two checks: a structural parse gate (does the script become pages/panels) and a craft-level LLM verify (`pipeline-script-verify` — un-renderable panels, panel-to-panel flow, dialogue/art balance, within-issue continuity, page-turn placement); the craft gate is advisory (surfaces + files blocking findings without hard-pausing, since the gating quality pass is the series-level editorial review). Before any visual production it also runs a **canon descriptive-integrity gate**: every canon noun (character/place/object) that appears where it would be *drawn* — the comic-script panel descriptions, not prose narration — must have a description, or the run **pauses for human review** (an artist can't render a name). The visual-source distinction is deliberate: an off-page character named only in narration is never drawn, so it's a Nouns-stage quality note, not a production blocker. The same check is exposed for the pipeline UI via `GET /api/pipeline/issues/:id/canon-readiness` and `GET /api/pipeline/series/:id/canon-readiness` (read-only, deterministic — reuses the committed canon name-matchers and `getSeriesCanon`). The whole feature is surfaced in the UI by an **Autonomous mode panel** on the series page (`AutopilotPanel`): a Run/Resume button with a run-options popover (draft visuals, file-gaps), live SSE step progress (with the dry-run plan when the cos domain is in dry-run), a Stop control, a paused/done/error banner driven by the persisted marker that lists the residual findings, and a one-click "production readiness" canon check that links each undescribed drawn noun to its issue's Nouns stage. (`server/services/pipeline/seriesAutopilot.js`, `server/services/pipeline/scriptVerify.js`, `server/services/pipeline/canonReadiness.js`, `server/routes/pipeline/canon.js`, `data.reference/prompts/stages/pipeline-script-verify.md`, `scripts/migrations/090-script-verify-stage.js`, `server/routes/pipeline/autopilot.js`, `server/routes/pipeline/index.js`, `server/services/pipeline/series.js`, `server/index.js`, `client/src/components/pipeline/AutopilotPanel.jsx`, `client/src/pages/PipelineSeries.jsx`, `client/src/services/apiPipeline.js`)
- **"Describe from prose" button on the Nouns stage backfills missing descriptions — and flags the nouns the manuscript can't describe.** Extracted nouns (characters/places/objects) often land with a name but no description, so a generated reference image has nothing to work from but the name. The new button writes a description for every undescribed noun that appears in the issue, using **only** what the prose actually establishes — and, crucially, it does **not** invent. This is the inverse of "Extract from prose" (which commits opinionated, renderable choices when the prose is silent so it never leaves a blank): a noun the manuscript names but never describes comes back graded `none` and stays blank, surfacing in a persistent red-flag banner ("The manuscript is thin on description for N nouns…") rather than being papered over with a fabricated look. Nouns the prose describes only in passing are graded `thin` (the grounded fragment is filled, with a note on what's missing). Strictly prose-grounded descriptions double as a manuscript-quality check: if the story can't describe its own people and places, that's a signal the prose needs enriching, not the bible. Fills only empty, unlocked entries (never clobbers an existing description or a locked one), re-reads freshest state at write time, and persists the gap report on the prose stage so the banner survives reload. Driven by a new strictly-grounded `pipeline-canon-describe-from-prose` stage prompt. (`data.reference/prompts/stages/pipeline-canon-describe-from-prose.md`, `scripts/migrations/089-canon-describe-from-prose-stage.js`, `server/services/universeCanon.js`, `server/routes/pipeline/issues.js`, `server/services/pipeline/issues.js`, `client/src/services/apiPipeline.js`, `client/src/components/pipeline/stages/NounsStage.jsx`)
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index 67932d213d..0da26433d3 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -463,6 +463,13 @@
"model": "default",
"returnsJson": true,
"variables": []
+ },
+ "pipeline-editorial-info-dumping": {
+ "name": "Pipeline — Editorial Check: Info-dumping",
+ "description": "Editorial check (#1284): flags info-dumping / 'as you know, Bob' exposition in the drafted manuscript — backstory bricks, maid-and-butler dialogue, front-loaded world rules — and suggests how to dramatize or trim each instead. Returns issue-anchored findings.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
}
}
}
diff --git a/data.reference/prompts/stages/pipeline-editorial-info-dumping.md b/data.reference/prompts/stages/pipeline-editorial-info-dumping.md
new file mode 100644
index 0000000000..6358fa55cc
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-editorial-info-dumping.md
@@ -0,0 +1,58 @@
+# Pipeline — Editorial Check: Info-dumping / "as you know, Bob"
+
+You are a developmental editor doing a single focused pass for ONE problem:
+**info-dumping** — passages that deliver backstory, world rules, or character
+history through unnatural exposition instead of letting the story reveal them.
+
+Watch for:
+
+- **"As you know, Bob"** — a character telling another character something they
+ both already know, purely for the reader's benefit.
+- **Backstory bricks** — paragraphs that pause the scene to explain history,
+ lore, or mechanics the moment doesn't need yet.
+- **Maid-and-butler dialogue** — characters narrating their world to each other.
+- **Front-loaded world rules** — dumping how the magic/tech/politics works
+ before the reader has any reason to care.
+
+Do NOT flag: tension-bearing revelation, earned exposition woven into action,
+or a character genuinely learning something new.
+
+## Manuscript
+
+The manuscript is stitched from the drafted issues. Each section begins with a
+header like `# Issue 3 — Title (prose)`; use the issue number in that header to
+attribute each finding to its `issueNumber`.
+
+```
+{{manuscript}}
+```
+
+## Task
+
+Identify the worst info-dumping passages. 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, explain the problem, and suggest how to dramatize or
+trim the exposition instead.
+
+Be specific and cite the text. If the manuscript has no real info-dumping
+problems, 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 — where in the issue (scene/paragraph)",
+ "problem": "1–3 sentences naming the info-dump and why it stalls the story",
+ "suggestion": "1–3 sentences on how to reveal it through action/conflict instead",
+ "anchorQuote": "short verbatim quote from the manuscript (≤ 200 chars)"
+ }
+ ]
+}
+```
diff --git a/docs/plans/2026-06-16-editorial-check-registry-runner.md b/docs/plans/2026-06-16-editorial-check-registry-runner.md
new file mode 100644
index 0000000000..9a626f1724
--- /dev/null
+++ b/docs/plans/2026-06-16-editorial-check-registry-runner.md
@@ -0,0 +1,134 @@
+# Plan — #1284 Editorial check registry + runner (backbone)
+
+## Context
+
+PortOS's series pipeline has editorial logic scattered across `manuscriptReview.js`,
+`completenessPass.js`, `editorialAnalysis.js`, and `canonReadiness.js` with **no shared
+way** to register a new "check," declare its scope, run it, and collect findings. Every
+new editorial rule the roadmap wants (name similarity, scene balance, POV-without-arc,
+info-dumping, …) currently has no home.
+
+#1284 is the **backbone** of epic #1283: a single extensible **check registry + runner**
+(mirroring `apiRegistry.js` / `navManifest.js` / `widgetRegistry.jsx`) that lets each
+editorial rule — deterministic or LLM-driven — plug in, declare scope, emit findings into
+the **existing `manuscriptReview` store**, be toggled/configured, and run inside
+`seriesAutopilot`. The dedicated management **UI is a separate issue (#1285)** — this PR
+makes findings land in the *existing* manuscript-review store/UI; it ships **no new React
+page**. Two reference checks (1 deterministic, 1 LLM) prove both paths.
+
+## Scope decisions (defaults — adjust at approval)
+
+- **Backbone only, no new UI page.** Findings surface in the existing manuscript-review UI
+ via the store. The Editorial Checks catalog/config/triage page is #1285.
+- **Two reference checks:**
+ - `naming.dissimilar-names` — **deterministic**, scope `series`, category `naming`.
+ Flags character-name pairs that are too similar (shared first letter / same length /
+ similar vowel skeleton) from canon characters. Configurable thresholds.
+ - `prose.info-dumping` — **LLM**, scope `issue`, category `exposition`. Flags
+ "as-you-know-Bob" exposition dumps in drafted prose via a new prompt stage.
+- **`checkId` on findings.** Add an optional `checkId` field to the manuscript-review
+ comment shape and fold it into the dedup key so findings group per-check and dismissals
+ stay suppressed per-check. Additive + optional ⇒ backward-compatible with synced
+ `manuscript-review.json` and with existing completeness findings (absent → `''`).
+
+## Key reuse (verified)
+
+- **Findings store:** `server/services/pipeline/manuscriptReview.js` —
+ `seedReviewFromFindings(seriesId, findings, { runId, mode })` (serialized per-series write
+ queue + `findingKey` dedup + dismiss-suppression), `getReview(seriesId)`,
+ `sanitizeComment` (the shape), `findingKey` (`${issueNumber??''}|${anchorQuote}|${problem}`).
+- **Registry + fail-fast guard pattern:** `server/lib/navManifest.js` (module-load loop that
+ throws on missing fields / bad enum / dup id) and `server/lib/apiRegistry.js` (static array
+ + resolver merging persisted state).
+- **LLM call:** `runStagedLLM(stageName, vars, { providerOverride, modelOverride, returnsJson, source })`
+ from `server/lib/stageRunner.js` (same path `completenessPass.js` uses). Provider/model
+ resolved via `getActiveProvider()` + `resolveModel()`; supports local + API providers.
+- **Manuscript assembly + ctx:** `collectManuscriptSections(seriesId)` + `sectionsCorpus(sections)`
+ + `buildArcBaseContext` / `getSeriesCanon` from `server/services/pipeline/arcPlanner/context.js`
+ & `completenessPass.js`. Canon characters via `getSeriesCanon(series)`.
+- **SSE run-tracking:** `server/services/pipeline/manuscriptCompletenessRunner.js` +
+ `server/lib/sseUtils.js` (`attachSseClient`, `broadcastSse`, run-record `Map`).
+- **Routes:** `server/routes/pipeline/editorial.js` (Router, `asyncHandler`, `validateRequest`,
+ `mapServiceError`, `seriesSvc.getSeries`), mounted under `/api/pipeline/` by
+ `server/routes/pipeline/index.js`.
+- **Autopilot loop:** `server/services/pipeline/seriesAutopilot.js` `runEditorial()` (~L539–594),
+ `buildDryRunPlan()` (~L840–863), `providerOverrideOpts(record)`.
+- **Settings:** `getSettings()` / `saveSettings()` from `server/services/settings.js`;
+ per-check state under `settings.pipelineEditorialChecks.checks[id] = { enabled, config }`.
+- **Stage propagation (no migration needed):** `scripts/setup-data.js` `JSON_MERGE_TARGETS`
+ merges new `stages` entries from `data.reference/prompts/stage-config.json` into existing
+ installs, and copies missing `.md` files. Migrations are only for *modifying* shipped
+ prompts — a brand-new stage is fully covered by the existing merge/copy.
+
+## New files
+
+1. **`server/lib/editorial/checkRegistry.js`**
+ - `EDITORIAL_CHECKS` array. Entry: `{ id, label, description, scope, kind, category,
+ severityDefault, configSchema (Zod), gate?(ctx), run(ctx) }`.
+ - Module-load fail-fast guards (mirror navManifest): missing required fields; `scope ∈
+ {series,issue,scene,noun}`; `kind ∈ {deterministic,llm}`; duplicate id.
+ - The two reference checks (deterministic `naming.dissimilar-names` computes inline;
+ LLM `prose.info-dumping` calls `runStagedLLM('pipeline-editorial-info-dumping', …)`).
+ - Helpers: `getCheck(id)`, `listChecks()`, `resolveCheckState(settings)` (registry
+ defaults merged with persisted enabled/config, validated through each `configSchema`),
+ `getEnabledChecks(settings, subsetIds?)`.
+2. **`server/lib/editorial/index.js`** — barrel (`export * from './checkRegistry.js'`).
+3. **`server/lib/editorial/README.md`** — catalog rows (Module Organization rule).
+4. **`server/services/pipeline/editorial/checkRunner.js`**
+ - `runEditorialChecks(seriesId, { checkIds?, providerOverride, modelOverride, signal, onProgress })`:
+ build shared ctx once (`series, issues, universe canon, manuscript`), run each enabled
+ check (deterministic inline; llm via stage), tag every finding with `checkId`, persist
+ via `seedReviewFromFindings(seriesId, findings, { runId, mode: 'merge' })`. Returns
+ `{ runId, findings, perCheck }`.
+ - SSE run-tracking mirroring `manuscriptCompletenessRunner.js`: `startRun`,
+ `attachSseClient`, `getStatus`, `cancelRun`; frames `start | check:start | check:complete
+ | complete | error | canceled`.
+ - `buildEditorialCheckPlan(seriesId, settings)` — dry-run plan (which checks would run).
+5. **`data.reference/prompts/stages/pipeline-editorial-info-dumping.md`** — LLM stage prompt
+ (returns JSON findings). New file → auto-copied to installs.
+6. **Tests:**
+ - `server/lib/editorial/checkRegistry.test.js` — shape invariants, dup-id throw,
+ invalid-enum throw, `gate` filtering, deterministic naming-check output.
+ - `server/services/pipeline/editorial/checkRunner.test.js` — re-run dedup (no dupes),
+ `checkId` present on findings, dry-run plan shape.
+
+## Modified files
+
+7. **`server/services/pipeline/manuscriptReview.js`** — add optional `checkId` to
+ `sanitizeComment` (default `null`); fold into `findingKey`
+ (`${checkId??''}|${issueNumber??''}|${anchorQuote}|${problem}`). Keep existing
+ completeness findings deduping unchanged (absent checkId → `''`).
+8. **`server/routes/pipeline/editorial.js`** — add:
+ - `GET /editorial/checks` → registry + resolved enabled/config state.
+ - `PATCH /editorial/checks/:id` → enable/disable/config (Zod-validated).
+ - `POST /series/:id/editorial/checks/run` → start run (body: optional `checkIds`), SSE.
+ - `GET /series/:id/editorial/checks/run/progress` (SSE attach), `.../status`, `.../cancel`
+ (mirror the existing analyze endpoints).
+9. **`server/services/pipeline/seriesAutopilot.js`** — add the check-runner pass into the
+ bounded editorial loop (after manuscriptCompleteness, behind the same round/budget gates);
+ add a `kind: 'editorialChecks'` line to `buildDryRunPlan()`.
+10. **`server/lib/validation.js`** — `editorialCheckConfigSchema` (PATCH: `enabled?`,
+ `config?`), `editorialChecksRunSchema` (`checkIds?: string[]`),
+ `pipelineEditorialChecksSettingsSchema`; wire the settings slice into the existing
+ `PUT /api/settings` partial-validation pattern (`server/routes/settings.js`).
+11. **`server/lib/index.js`** + **`server/lib/README.md`** — export + document `editorial/`.
+12. **`.changelog/NEXT.md`** — user-facing entry under the appropriate heading.
+
+## Verification
+
+- `cd server && npm test` — new registry + runner suites pass; existing manuscriptReview /
+ autopilot / validation / `lib/index.test.js` (barrel) suites stay green.
+- `node -e "import('./server/lib/editorial/index.js').then(()=>console.log('ok'))"` — confirms
+ the new module + barrel load (catches missing-import / cross-module link bugs that vitest
+ false-greens).
+- Boot guard: a temporarily-malformed registry entry throws at module load (manual sanity).
+- Manual end-to-end (dev box, optional): `GET /api/pipeline/editorial/checks` lists both
+ checks with default state; `POST /api/pipeline/series/:id/editorial/checks/run` streams SSE
+ and the resulting findings appear in the existing manuscript-review for that series with
+ `checkId` set; a re-run does not duplicate them.
+
+## Ship
+
+`/do:next` Phase 5–7: re-sync `main`, log changelog, `/simplify` + `/do:pr --no-merge
+--review-with=…` (multi-file feature → external review), gate merge on a clean status, merge
+with `Closes #1284`, clean up worktree + close issue.
diff --git a/server/lib/README.md b/server/lib/README.md
index 9f11f1958d..e2e508b3ed 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -44,6 +44,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`. |
| `storyArc.js` | Canonical Arc + Season + Reader-Map shapes for pipeline arc planning. |
| `storyBuilderSteps.js` | Unified Story Builder ordered step definitions + helpers (`STEPS`, `STEP_IDS`, `STEP_STATUSES`, `isValidStepId`, `stepIndex`). |
diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.md
new file mode 100644
index 0000000000..3e7772a017
--- /dev/null
+++ b/server/lib/editorial/README.md
@@ -0,0 +1,23 @@
+# server/lib/editorial — editorial check registry
+
+The backbone of the extensible editorial-review system (#1284, epic #1283): a
+declarative registry of "editorial checks" that plug into the series pipeline.
+Each check declares its scope, kind, default severity, a Zod config schema, an
+optional gate, and a `run(ctx)` that returns findings shaped for the existing
+`manuscriptReview` comment store. The runner that builds the shared `ctx`, runs
+the enabled checks, and seeds findings lives at
+`server/services/pipeline/editorial/checkRunner.js`.
+
+This directory is **pure** (no side-effecting imports). LLM-kind checks get
+their model caller through `ctx.callStagedLLM`, injected by the runner.
+
+## Discovery rule
+
+Before adding an editorial rule, check whether an existing registry entry covers
+it. To add a new check, append an entry to `EDITORIAL_CHECKS` in
+`checkRegistry.js` (the fail-fast guards enforce shape, enum, and unique-id).
+
+| Module | Purpose |
+|---|---|
+| `checkRegistry.js` | `EDITORIAL_CHECKS` array + fail-fast guards + lookup/state helpers (`getCheck`, `listChecks`, `resolveCheckState`, `getEnabledChecks`, `resolveCheckConfig`). Ships two reference checks: `naming.dissimilar-names` (deterministic) and `prose.info-dumping` (LLM). |
+| `index.js` | Barrel re-export of the above. |
diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.js
new file mode 100644
index 0000000000..23339d5fa7
--- /dev/null
+++ b/server/lib/editorial/checkRegistry.js
@@ -0,0 +1,237 @@
+/**
+ * Editorial Check Registry (#1284) — the backbone of the extensible
+ * editorial-review system (epic #1283).
+ *
+ * Mirrors `server/lib/navManifest.js` and `server/lib/apiRegistry.js`: a static
+ * array of declarative entries with fail-fast guards at module load so a
+ * malformed check blocks boot instead of silently breaking the runner. Each
+ * entry declares its scope, kind, default severity, a Zod `configSchema`, an
+ * optional `gate`, and a `run(ctx)` that returns findings shaped for the
+ * existing `manuscriptReview` comment store.
+ *
+ * This module is intentionally PURE — it imports nothing with side effects
+ * (only `zod`). LLM-kind checks receive their model caller through
+ * `ctx.callStagedLLM`, injected by `server/services/pipeline/editorial/checkRunner.js`,
+ * so the registry stays side-effect-free and unit-testable in isolation.
+ *
+ * A finding returned by `run(ctx)` is a partial `manuscriptReview` comment:
+ * { severity?, category?, location?, problem (required), suggestion?,
+ * anchorQuote?, issueNumber? }
+ * The runner stamps each finding's `checkId` (and `sourceRunId`) before seeding
+ * the review, so checks never set those themselves.
+ */
+
+import { z } from 'zod';
+
+export const CHECK_SCOPES = Object.freeze(['series', 'issue', 'scene', 'noun']);
+export const CHECK_KINDS = Object.freeze(['deterministic', 'llm']);
+const SEVERITIES = Object.freeze(['high', 'medium', 'low']);
+
+// Stage name for the info-dumping LLM check. The prompt ships in
+// data.reference/prompts/stages/ and its config in stage-config.json; both
+// propagate to existing installs via setup-data.js (missing-file copy +
+// JSON_MERGE_TARGETS stage merge), so no migration is needed for a NEW stage.
+export const INFO_DUMPING_STAGE = 'pipeline-editorial-info-dumping';
+
+// ---------------------------------------------------------------------------
+// Deterministic helpers for the character-name dissimilarity check.
+// ---------------------------------------------------------------------------
+
+const letters = (s) => String(s || '').toLowerCase().replace(/[^a-z]/g, '');
+const vowelSkeleton = (s) => letters(s).replace(/[^aeiou]/g, '');
+
+// The similarity signals two character names can share. Two names that trip
+// enough of these are easy for a reader to confuse on the page.
+function nameSimilaritySignals(a, b) {
+ const la = letters(a);
+ const lb = letters(b);
+ if (!la || !lb) return [];
+ const signals = [];
+ if (la[0] === lb[0]) signals.push('same first letter');
+ if (la.length === lb.length) signals.push('same length');
+ if (vowelSkeleton(a) && vowelSkeleton(a) === vowelSkeleton(b)) signals.push('same vowel pattern');
+ if (la.length >= 3 && lb.length >= 3 && la.slice(0, 3) === lb.slice(0, 3)) signals.push('same opening');
+ if (la.endsWith(lb.slice(-2)) && la.slice(-2) === lb.slice(-2)) signals.push('same ending');
+ return signals;
+}
+
+// ---------------------------------------------------------------------------
+// Registry entries.
+// ---------------------------------------------------------------------------
+
+export const EDITORIAL_CHECKS = [
+ {
+ id: 'naming.dissimilar-names',
+ label: 'Character name dissimilarity',
+ description:
+ 'Flags pairs of character names a reader could confuse — sharing a first letter, length, vowel pattern, opening, or ending.',
+ scope: 'series',
+ kind: 'deterministic',
+ category: 'naming',
+ severityDefault: 'low',
+ defaultEnabled: true,
+ configSchema: z.object({
+ // How many similarity signals two names must share before they're flagged.
+ minSharedSignals: z.number().int().min(1).max(5).default(2),
+ }),
+ run: (ctx) => {
+ const min = ctx.config?.minSharedSignals ?? 2;
+ const names = (ctx.canon?.characters || [])
+ .map((c) => (typeof c?.name === 'string' ? c.name.trim() : ''))
+ .filter(Boolean);
+ const findings = [];
+ for (let i = 0; i < names.length; i += 1) {
+ for (let j = i + 1; j < names.length; j += 1) {
+ if (names[i].toLowerCase() === names[j].toLowerCase()) continue;
+ const signals = nameSimilaritySignals(names[i], names[j]);
+ if (signals.length < min) continue;
+ findings.push({
+ severity: ctx.severityDefault,
+ category: 'naming',
+ location: `Characters: ${names[i]} / ${names[j]}`,
+ problem: `Character names "${names[i]}" and "${names[j]}" are easy to confuse (${signals.join(', ')}).`,
+ suggestion: 'Rename one of these characters so readers can tell them apart at a glance.',
+ anchorQuote: names[i],
+ issueNumber: null,
+ });
+ }
+ }
+ return findings;
+ },
+ },
+ {
+ id: 'prose.info-dumping',
+ label: 'Info-dumping / "as you know, Bob" exposition',
+ description:
+ 'Flags passages that dump backstory or world rules through unnatural exposition — characters telling each other what they both already know.',
+ scope: 'issue',
+ kind: 'llm',
+ category: 'exposition',
+ severityDefault: 'medium',
+ defaultEnabled: 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),
+ }),
+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,
+ run: async (ctx) => {
+ const { content } = await ctx.callStagedLLM(
+ INFO_DUMPING_STAGE,
+ { manuscript: ctx.manuscript },
+ { returnsJson: true, source: INFO_DUMPING_STAGE },
+ );
+ const raw = Array.isArray(content?.findings) ? content.findings : [];
+ const max = ctx.config?.maxFindings ?? 12;
+ return raw.slice(0, max).map((f) => ({
+ severity: SEVERITIES.includes(f?.severity) ? f.severity : ctx.severityDefault,
+ category: 'exposition',
+ location: typeof f?.location === 'string' ? f.location : '',
+ problem: typeof f?.problem === 'string' ? f.problem : '',
+ suggestion: typeof f?.suggestion === 'string' ? f.suggestion : '',
+ anchorQuote: typeof f?.anchorQuote === 'string' ? f.anchorQuote : '',
+ issueNumber: Number.isInteger(f?.issueNumber) ? f.issueNumber : null,
+ })).filter((f) => f.problem);
+ },
+ },
+];
+
+// ---------------------------------------------------------------------------
+// Fail-fast guards (mirror navManifest.js). Runs at module load on the real
+// registry so a bad entry blocks server boot instead of silently breaking the
+// runner; exported so the invariant tests can exercise the throw paths the
+// valid built-in array can't reach.
+// ---------------------------------------------------------------------------
+
+export function assertValidChecks(checks) {
+ const seen = new Set();
+ for (const check of checks) {
+ if (!check.id || !check.label || !check.scope || !check.kind || !check.category) {
+ throw new Error(`checkRegistry: malformed entry ${JSON.stringify(check)}`);
+ }
+ if (!CHECK_SCOPES.includes(check.scope)) {
+ throw new Error(`checkRegistry: invalid scope "${check.scope}" for ${check.id} (must be one of ${CHECK_SCOPES.join(', ')})`);
+ }
+ if (!CHECK_KINDS.includes(check.kind)) {
+ throw new Error(`checkRegistry: invalid kind "${check.kind}" for ${check.id} (must be one of ${CHECK_KINDS.join(', ')})`);
+ }
+ if (!SEVERITIES.includes(check.severityDefault)) {
+ throw new Error(`checkRegistry: invalid severityDefault "${check.severityDefault}" for ${check.id}`);
+ }
+ if (typeof check.run !== 'function') {
+ throw new Error(`checkRegistry: ${check.id} is missing a run() function`);
+ }
+ if (!check.configSchema || typeof check.configSchema.safeParse !== 'function') {
+ throw new Error(`checkRegistry: ${check.id} is missing a Zod configSchema`);
+ }
+ if (seen.has(check.id)) throw new Error(`checkRegistry: duplicate id ${check.id}`);
+ seen.add(check.id);
+ }
+}
+
+assertValidChecks(EDITORIAL_CHECKS);
+
+// ---------------------------------------------------------------------------
+// Lookup + state resolution helpers.
+// ---------------------------------------------------------------------------
+
+const CHECK_BY_ID = new Map(EDITORIAL_CHECKS.map((c) => [c.id, c]));
+
+export const getCheck = (id) => CHECK_BY_ID.get(id) || null;
+
+export const listChecks = () => EDITORIAL_CHECKS.slice();
+
+// Validate (and default-fill) a persisted per-check config blob through the
+// check's Zod schema. Falls back to the schema's defaults when the stored blob
+// is absent or invalid, so a hand-edited settings.json can't make a check throw.
+export function resolveCheckConfig(check, storedConfig) {
+ const parsed = check.configSchema.safeParse(storedConfig || {});
+ if (parsed.success) return parsed.data;
+ // Re-parse an empty object to materialize the schema defaults.
+ const defaults = check.configSchema.safeParse({});
+ return defaults.success ? defaults.data : {};
+}
+
+const readChecksSlice = (settings) => {
+ const slice = settings?.pipelineEditorialChecks?.checks;
+ return slice && typeof slice === 'object' && !Array.isArray(slice) ? slice : {};
+};
+
+/**
+ * Merge the static registry with persisted per-check state from settings.
+ * Returns one row per registered check:
+ * { id, label, description, scope, kind, category, severityDefault,
+ * enabled, config }
+ * `enabled` falls back to the check's `defaultEnabled`; `config` is validated
+ * through the check's schema (with defaults).
+ */
+export function resolveCheckState(settings) {
+ const stored = readChecksSlice(settings);
+ return EDITORIAL_CHECKS.map((check) => {
+ const row = stored[check.id] || {};
+ const enabled = typeof row.enabled === 'boolean' ? row.enabled : check.defaultEnabled !== false;
+ return {
+ id: check.id,
+ label: check.label,
+ description: check.description,
+ scope: check.scope,
+ kind: check.kind,
+ category: check.category,
+ severityDefault: check.severityDefault,
+ enabled,
+ config: resolveCheckConfig(check, row.config),
+ };
+ });
+}
+
+/**
+ * The checks that should actually run for a given settings + optional subset.
+ * Returns `{ check, config }` pairs (the live registry entry + its resolved
+ * config) for every enabled check, narrowed to `subsetIds` when provided.
+ */
+export function getEnabledChecks(settings, subsetIds = null) {
+ const subset = Array.isArray(subsetIds) && subsetIds.length ? new Set(subsetIds) : null;
+ return resolveCheckState(settings)
+ .filter((row) => row.enabled && (!subset || subset.has(row.id)))
+ .map((row) => ({ check: getCheck(row.id), config: row.config }))
+ .filter((x) => x.check);
+}
diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.js
new file mode 100644
index 0000000000..0288efc0eb
--- /dev/null
+++ b/server/lib/editorial/checkRegistry.test.js
@@ -0,0 +1,144 @@
+import { describe, it, expect } from 'vitest';
+import { z } from 'zod';
+import {
+ EDITORIAL_CHECKS,
+ CHECK_SCOPES,
+ CHECK_KINDS,
+ getCheck,
+ listChecks,
+ assertValidChecks,
+ resolveCheckConfig,
+ resolveCheckState,
+ getEnabledChecks,
+} from './checkRegistry.js';
+
+const NAMING = 'naming.dissimilar-names';
+const INFODUMP = 'prose.info-dumping';
+
+describe('editorial check registry — shape invariants', () => {
+ it('every entry has a valid shape', () => {
+ for (const check of EDITORIAL_CHECKS) {
+ expect(check.id, 'id').toBeTruthy();
+ expect(check.label, `${check.id} label`).toBeTruthy();
+ expect(CHECK_SCOPES, `${check.id} scope`).toContain(check.scope);
+ expect(CHECK_KINDS, `${check.id} kind`).toContain(check.kind);
+ expect(['high', 'medium', 'low'], `${check.id} severity`).toContain(check.severityDefault);
+ expect(typeof check.run, `${check.id} run`).toBe('function');
+ expect(typeof check.configSchema?.safeParse, `${check.id} configSchema`).toBe('function');
+ }
+ });
+
+ it('ships both reference checks (one deterministic, one llm)', () => {
+ const ids = listChecks().map((c) => c.id);
+ expect(ids).toContain(NAMING);
+ expect(ids).toContain(INFODUMP);
+ expect(getCheck(NAMING).kind).toBe('deterministic');
+ expect(getCheck(INFODUMP).kind).toBe('llm');
+ });
+
+ it('getCheck returns null for an unknown id', () => {
+ expect(getCheck('does.not-exist')).toBeNull();
+ });
+});
+
+describe('editorial check registry — fail-fast guards', () => {
+ const valid = {
+ id: 'x.ok', label: 'ok', scope: 'series', kind: 'deterministic',
+ category: 'naming', severityDefault: 'low', configSchema: z.object({}), run: () => [],
+ };
+
+ it('accepts a valid set', () => {
+ expect(() => assertValidChecks([valid])).not.toThrow();
+ });
+
+ it('throws on a missing required field', () => {
+ expect(() => assertValidChecks([{ ...valid, label: '' }])).toThrow(/malformed/);
+ });
+
+ it('throws on an invalid scope', () => {
+ expect(() => assertValidChecks([{ ...valid, scope: 'galaxy' }])).toThrow(/invalid scope/);
+ });
+
+ it('throws on an invalid kind', () => {
+ expect(() => assertValidChecks([{ ...valid, kind: 'magic' }])).toThrow(/invalid kind/);
+ });
+
+ it('throws on an invalid severityDefault', () => {
+ expect(() => assertValidChecks([{ ...valid, severityDefault: 'critical' }])).toThrow(/severityDefault/);
+ });
+
+ it('throws on a missing run()', () => {
+ expect(() => assertValidChecks([{ ...valid, run: undefined }])).toThrow(/run\(\)/);
+ });
+
+ it('throws on a missing configSchema', () => {
+ expect(() => assertValidChecks([{ ...valid, configSchema: undefined }])).toThrow(/configSchema/);
+ });
+
+ it('throws on a duplicate id', () => {
+ expect(() => assertValidChecks([valid, { ...valid }])).toThrow(/duplicate id/);
+ });
+});
+
+describe('editorial check registry — config + state resolution', () => {
+ it('resolveCheckConfig fills schema defaults', () => {
+ const cfg = resolveCheckConfig(getCheck(NAMING), undefined);
+ expect(cfg.minSharedSignals).toBe(2);
+ });
+
+ it('resolveCheckConfig falls back to defaults on an invalid blob', () => {
+ const cfg = resolveCheckConfig(getCheck(NAMING), { minSharedSignals: 'lots' });
+ expect(cfg.minSharedSignals).toBe(2);
+ });
+
+ it('resolveCheckState merges persisted enable/config over defaults', () => {
+ const rows = resolveCheckState({
+ pipelineEditorialChecks: { checks: { [NAMING]: { enabled: false, config: { minSharedSignals: 3 } } } },
+ });
+ const naming = rows.find((r) => r.id === NAMING);
+ expect(naming.enabled).toBe(false);
+ expect(naming.config.minSharedSignals).toBe(3);
+ // Unconfigured check keeps its default-enabled state.
+ expect(rows.find((r) => r.id === INFODUMP).enabled).toBe(true);
+ });
+
+ it('getEnabledChecks honors disable + subset narrowing', () => {
+ const settings = { pipelineEditorialChecks: { checks: { [INFODUMP]: { enabled: false } } } };
+ const enabled = getEnabledChecks(settings).map((x) => x.check.id);
+ expect(enabled).toContain(NAMING);
+ expect(enabled).not.toContain(INFODUMP);
+
+ const subset = getEnabledChecks({}, [NAMING]).map((x) => x.check.id);
+ expect(subset).toEqual([NAMING]);
+ });
+});
+
+describe('naming.dissimilar-names — deterministic check', () => {
+ const run = (characters, config = { minSharedSignals: 2 }) =>
+ getCheck(NAMING).run({ canon: { characters }, config, severityDefault: 'low' });
+
+ it('flags confusable name pairs', () => {
+ const findings = run([{ name: 'Alina' }, { name: 'Alana' }, { name: 'Zog' }]);
+ expect(findings.length).toBeGreaterThan(0);
+ const f = findings[0];
+ expect(f.category).toBe('naming');
+ expect(f.anchorQuote).toBeTruthy();
+ expect(f.problem).toMatch(/confuse/i);
+ });
+
+ it('does not flag clearly distinct names', () => {
+ const findings = run([{ name: 'Alina' }, { name: 'Zog' }, { name: 'Bree' }]);
+ expect(findings).toEqual([]);
+ });
+
+ it('respects the minSharedSignals threshold', () => {
+ const chars = [{ name: 'Sam' }, { name: 'Sun' }]; // share first letter + length
+ expect(run(chars, { minSharedSignals: 2 }).length).toBe(1);
+ expect(run(chars, { minSharedSignals: 4 }).length).toBe(0);
+ });
+
+ it('tolerates empty / nameless canon', () => {
+ expect(run([])).toEqual([]);
+ expect(run([{}, { name: '' }])).toEqual([]);
+ });
+});
diff --git a/server/lib/editorial/index.js b/server/lib/editorial/index.js
new file mode 100644
index 0000000000..cc454619ef
--- /dev/null
+++ b/server/lib/editorial/index.js
@@ -0,0 +1,3 @@
+// Barrel for server/lib/editorial/ — the extensible editorial-check registry
+// (#1284). See README.md for the catalog. Re-export every public module here.
+export * from './checkRegistry.js';
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 1a5a978a6e..7e7bca34e4 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -984,6 +984,31 @@ export const writersRoomLiveSuggestSchema = z.object({
// payload (e.g. an attempt to smuggle a usage counter) instead of ignoring it.
export const writersRoomLiveRenderPreviewSchema = z.object({}).strict();
+// =============================================================================
+// EDITORIAL CHECKS (#1284) — registry-driven editorial review
+// =============================================================================
+// Per-check enable/config. `config` is a free-form blob validated a second time
+// against the check's own Zod `configSchema` in the registry (resolveCheckConfig)
+// — this gate just bounds the wire shape so a malformed PATCH can't write junk.
+export const editorialCheckConfigSchema = z.object({
+ enabled: z.boolean().optional(),
+ config: z.record(z.unknown()).optional(),
+}).strict();
+
+// POST .../editorial/checks/run — run all enabled checks, or a named subset.
+// providerId/model are optional overrides forwarded to LLM-kind checks.
+export const editorialChecksRunSchema = z.object({
+ checkIds: z.array(z.string().trim().min(1).max(120)).max(50).optional(),
+ providerId: z.string().trim().max(80).optional(),
+ model: z.string().trim().max(200).optional(),
+}).strict();
+
+// settings.pipelineEditorialChecks slice (validated on PUT /api/settings when
+// present). `checks` maps a checkId → its persisted enable/config.
+export const pipelineEditorialChecksSettingsSchema = z.object({
+ checks: z.record(editorialCheckConfigSchema).optional(),
+}).strict();
+
// Cursor-context payload for the CD-bridge suggest route — identical shape to
// the live continuation suggest (the server only needs a window around the
// cursor, not the whole manuscript).
diff --git a/server/routes/pipeline/editorial.js b/server/routes/pipeline/editorial.js
index cec6f70a88..00eab03842 100644
--- a/server/routes/pipeline/editorial.js
+++ b/server/routes/pipeline/editorial.js
@@ -6,11 +6,14 @@
import { Router } from 'express';
import { z } from 'zod';
import { asyncHandler, ServerError } from '../../lib/errorHandler.js';
-import { validateRequest } from '../../lib/validation.js';
+import { validateRequest, editorialCheckConfigSchema, editorialChecksRunSchema } from '../../lib/validation.js';
+import { getCheck, resolveCheckState } from '../../lib/editorial/index.js';
import * as seriesSvc from '../../services/pipeline/series.js';
import * as issuesSvc from '../../services/pipeline/issues.js';
import * as editorialAnalysis from '../../services/pipeline/editorialAnalysis.js';
import * as editorialRunner from '../../services/pipeline/editorialAnalysisRunner.js';
+import * as checkRunner from '../../services/pipeline/editorial/checkRunner.js';
+import { getSettings, updateSettingsWith } from '../../services/settings.js';
import { mapServiceError } from './shared.js';
const router = Router();
@@ -71,4 +74,71 @@ router.post('/series/:id/editorial/analyze/cancel', asyncHandler(async (req, res
res.json({ canceled });
}));
+// ---------------------------------------------------------------------------
+// Editorial checks (#1284) — registry-driven editorial review.
+// ---------------------------------------------------------------------------
+
+// The full check catalog merged with persisted enable/config state.
+router.get('/editorial/checks', asyncHandler(async (req, res) => {
+ const settings = await getSettings();
+ res.json({ checks: resolveCheckState(settings) });
+}));
+
+// Enable/disable a check or update its config. Config is validated against the
+// check's own Zod schema before persisting (the wire shape is gated by
+// editorialCheckConfigSchema first).
+router.patch('/editorial/checks/:id', asyncHandler(async (req, res) => {
+ const check = getCheck(req.params.id);
+ if (!check) throw new ServerError(`Unknown editorial check: ${req.params.id}`, { status: 404 });
+ const body = validateRequest(editorialCheckConfigSchema, req.body ?? {});
+ if (body.config !== undefined) {
+ const parsed = check.configSchema.safeParse(body.config);
+ if (!parsed.success) {
+ throw new ServerError(`Invalid config for ${check.id}: ${parsed.error.issues?.[0]?.message || 'validation failed'}`, { status: 400 });
+ }
+ }
+ const updated = await updateSettingsWith((current) => {
+ const slice = current.pipelineEditorialChecks && typeof current.pipelineEditorialChecks === 'object'
+ ? current.pipelineEditorialChecks : {};
+ const checks = slice.checks && typeof slice.checks === 'object' ? slice.checks : {};
+ const prev = checks[check.id] && typeof checks[check.id] === 'object' ? checks[check.id] : {};
+ const nextEntry = { ...prev };
+ if (body.enabled !== undefined) nextEntry.enabled = body.enabled;
+ if (body.config !== undefined) nextEntry.config = body.config;
+ return { ...current, pipelineEditorialChecks: { ...slice, checks: { ...checks, [check.id]: nextEntry } } };
+ });
+ res.json(resolveCheckState(updated).find((r) => r.id === check.id));
+}));
+
+// Run all enabled checks (or a named subset) for a series — progress via SSE.
+router.post('/series/:id/editorial/checks/run', asyncHandler(async (req, res) => {
+ const body = validateRequest(editorialChecksRunSchema, req.body ?? {});
+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const result = checkRunner.startEditorialChecksRun(req.params.id, {
+ checkIds: body.checkIds,
+ providerOverride: body.providerId,
+ modelOverride: body.model,
+ });
+ res.json({
+ ...result,
+ sseUrl: `/api/pipeline/series/${req.params.id}/editorial/checks/run/progress`,
+ });
+}));
+
+router.get('/series/:id/editorial/checks/run/progress', (req, res) => {
+ const attached = checkRunner.attachClient(req.params.id, res);
+ if (!attached) {
+ throw new ServerError('No active editorial checks run for this series', { status: 404 });
+ }
+});
+
+// Lightweight probe so a (re)mounting client can re-attach to an in-flight run.
+router.get('/series/:id/editorial/checks/run/status', (req, res) => {
+ res.json({ active: checkRunner.isEditorialChecksActive(req.params.id) });
+});
+
+router.post('/series/:id/editorial/checks/run/cancel', asyncHandler(async (req, res) => {
+ res.json({ canceled: checkRunner.cancelEditorialChecks(req.params.id) });
+}));
+
export default router;
diff --git a/server/routes/pipeline/editorial.test.js b/server/routes/pipeline/editorial.test.js
new file mode 100644
index 0000000000..4155d29510
--- /dev/null
+++ b/server/routes/pipeline/editorial.test.js
@@ -0,0 +1,107 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../../lib/testHelper.js';
+import { errorMiddleware } from '../../lib/errorHandler.js';
+
+// In-memory settings store the route's updateSettingsWith mutates.
+let settingsStore = {};
+vi.mock('../../services/settings.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ getSettings: vi.fn(async () => settingsStore),
+ updateSettingsWith: vi.fn(async (mutate) => {
+ settingsStore = await mutate(settingsStore);
+ return settingsStore;
+ }),
+}));
+
+// Series resolution — resolve known ids, reject the rest with a NOT_FOUND code
+// that mapServiceError turns into a 404.
+vi.mock('../../services/pipeline/series.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ getSeries: vi.fn(async (id) => {
+ if (id === 'missing') throw Object.assign(new Error('nope'), { code: 'PIPELINE_SERIES_NOT_FOUND' });
+ return { id };
+ }),
+}));
+vi.mock('../../services/pipeline/issues.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ getIssue: vi.fn(async (id) => ({ id })),
+}));
+
+const startEditorialChecksRun = vi.fn(() => ({ runId: 'run-1', alreadyRunning: false }));
+vi.mock('../../services/pipeline/editorial/checkRunner.js', () => ({
+ startEditorialChecksRun: (...a) => startEditorialChecksRun(...a),
+ attachClient: vi.fn(() => false),
+ isEditorialChecksActive: vi.fn(() => false),
+ cancelEditorialChecks: vi.fn(() => true),
+}));
+
+const editorialRoutes = (await import('./editorial.js')).default;
+
+const app = express();
+app.use(express.json());
+app.use('/api/pipeline', editorialRoutes);
+app.use(errorMiddleware);
+
+beforeEach(() => {
+ settingsStore = {};
+ startEditorialChecksRun.mockClear();
+});
+
+describe('GET /api/pipeline/editorial/checks', () => {
+ it('returns the merged check catalog', async () => {
+ const res = await request(app).get('/api/pipeline/editorial/checks');
+ expect(res.status).toBe(200);
+ const ids = res.body.checks.map((c) => c.id);
+ expect(ids).toContain('naming.dissimilar-names');
+ expect(ids).toContain('prose.info-dumping');
+ expect(res.body.checks.every((c) => typeof c.enabled === 'boolean')).toBe(true);
+ });
+});
+
+describe('PATCH /api/pipeline/editorial/checks/:id', () => {
+ it('persists an enable/disable toggle', async () => {
+ const res = await request(app)
+ .patch('/api/pipeline/editorial/checks/prose.info-dumping')
+ .send({ enabled: false });
+ expect(res.status).toBe(200);
+ expect(res.body.id).toBe('prose.info-dumping');
+ expect(res.body.enabled).toBe(false);
+ expect(settingsStore.pipelineEditorialChecks.checks['prose.info-dumping'].enabled).toBe(false);
+ });
+
+ it('does not clobber a sibling check on a second patch', async () => {
+ await request(app).patch('/api/pipeline/editorial/checks/prose.info-dumping').send({ enabled: false });
+ await request(app).patch('/api/pipeline/editorial/checks/naming.dissimilar-names').send({ enabled: false });
+ expect(settingsStore.pipelineEditorialChecks.checks['prose.info-dumping'].enabled).toBe(false);
+ expect(settingsStore.pipelineEditorialChecks.checks['naming.dissimilar-names'].enabled).toBe(false);
+ });
+
+ it('validates config against the check schema (400 on bad config)', async () => {
+ const res = await request(app)
+ .patch('/api/pipeline/editorial/checks/naming.dissimilar-names')
+ .send({ config: { minSharedSignals: 99 } });
+ expect(res.status).toBe(400);
+ });
+
+ it('404s an unknown check id', async () => {
+ const res = await request(app).patch('/api/pipeline/editorial/checks/nope.nope').send({ enabled: true });
+ expect(res.status).toBe(404);
+ });
+});
+
+describe('POST /api/pipeline/series/:id/editorial/checks/run', () => {
+ it('starts a run and returns an sseUrl', async () => {
+ const res = await request(app).post('/api/pipeline/series/s1/editorial/checks/run').send({});
+ expect(res.status).toBe(200);
+ expect(res.body.runId).toBe('run-1');
+ expect(res.body.sseUrl).toContain('/editorial/checks/run/progress');
+ expect(startEditorialChecksRun).toHaveBeenCalledWith('s1', expect.any(Object));
+ });
+
+ it('404s a missing series', async () => {
+ const res = await request(app).post('/api/pipeline/series/missing/editorial/checks/run').send({});
+ expect(res.status).toBe(404);
+ expect(startEditorialChecksRun).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/routes/settings.js b/server/routes/settings.js
index 4ef859cb20..4764bdc47c 100644
--- a/server/routes/settings.js
+++ b/server/routes/settings.js
@@ -9,7 +9,7 @@ import {
CODEX_PARALLEL_DEFAULT,
} from '../services/mediaJobQueue/index.js';
import { asyncHandler } from '../lib/errorHandler.js';
-import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, validateRequest } from '../lib/validation.js';
+import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, validateRequest } from '../lib/validation.js';
const router = Router();
@@ -108,6 +108,12 @@ router.put('/', asyncHandler(async (req, res) => {
if (req.body?.apiAccess !== undefined) {
validateRequest(apiAccessSettingsSchema.partial(), req.body.apiAccess);
}
+ // Editorial-check enable/config slice (#1284) — validate when present so a
+ // malformed save can't write a non-boolean enabled / non-object config the
+ // registry would then choke on.
+ if (req.body?.pipelineEditorialChecks !== undefined) {
+ validateRequest(pipelineEditorialChecksSettingsSchema.partial(), req.body.pipelineEditorialChecks);
+ }
// User-defined catalog types moved out of settings.json into PostgreSQL
// (`catalog_user_types`, #1001). The `/api/catalog/types` routes are the only
// write path; a `catalogUserTypes` key in a PUT /api/settings body (legacy
diff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.js
new file mode 100644
index 0000000000..8f8611a5a8
--- /dev/null
+++ b/server/services/pipeline/editorial/checkRunner.js
@@ -0,0 +1,233 @@
+/**
+ * Pipeline — Editorial Check Runner (#1284).
+ *
+ * Loads the enabled editorial checks (+ per-check config) from settings, builds
+ * the shared `ctx` once (series, issues, universe canon, stitched manuscript),
+ * runs each check, and seeds the resulting findings into the existing
+ * `manuscriptReview` store — each finding stamped with its `checkId` so the
+ * editor groups/filters by check and a dismissal stays suppressed per-check.
+ *
+ * Deterministic checks run inline; LLM checks reuse the staged-LLM provider
+ * plumbing via the `ctx.callStagedLLM` injected here (the registry stays pure).
+ *
+ * The SSE wrapper at the bottom mirrors manuscriptCompletenessRunner.js: a
+ * single in-memory `runs` map keyed by seriesId, terminal-frame replay for
+ * late-connecting clients via lib/sseUtils.js.
+ */
+
+import { randomUUID } from 'crypto';
+import { broadcastSse, attachSseClient, SSE_CLEANUP_DELAY_MS } from '../../../lib/sseUtils.js';
+import { runStagedLLM } from '../../../lib/stageRunner.js';
+import { getEnabledChecks, resolveCheckState } from '../../../lib/editorial/index.js';
+import { getSettings } from '../../settings.js';
+import { getSeries } from '../series.js';
+import { listIssues } from '../issues.js';
+import { getSeriesCanon } from '../seriesCanon.js';
+import { collectManuscriptSections, sectionsCorpus } from '../arcPlanner.js';
+import { seedReviewFromFindings } from '../manuscriptReview.js';
+
+/**
+ * Run the enabled editorial checks for a series and seed their findings into the
+ * manuscript review.
+ *
+ * @param {string} seriesId
+ * @param {object} [options]
+ * - checkIds: string[] — run only this subset (default: all enabled)
+ * - settings: object — pre-loaded settings (default: read fresh)
+ * - providerOverride / modelOverride — forwarded to LLM checks
+ * - signal: AbortSignal — checked between checks for cancellation
+ * - onProgress: (event) => void — { type: 'check:start'|'check:complete', ... }
+ * @returns {Promise<{ runId, findings, perCheck, canceled }>}
+ */
+export async function runEditorialChecks(seriesId, options = {}) {
+ const { checkIds = null, providerOverride, modelOverride, signal, onProgress } = options;
+ const settings = options.settings || await getSettings();
+ const enabled = getEnabledChecks(settings, checkIds);
+
+ const runId = randomUUID();
+ if (enabled.length === 0) {
+ return { runId, findings: [], perCheck: [], canceled: false };
+ }
+
+ // Build the shared context once — every check reads from this.
+ const series = await getSeries(seriesId);
+ const [sections, canon, issues] = await Promise.all([
+ collectManuscriptSections(seriesId),
+ getSeriesCanon(series),
+ listIssues({ seriesId }).catch(() => []),
+ ]);
+ const manuscript = sectionsCorpus(sections);
+ const baseCtx = {
+ seriesId,
+ series,
+ issues,
+ sections,
+ manuscript,
+ canon,
+ providerOverride,
+ modelOverride,
+ // Injected LLM caller — keeps server/lib/editorial pure. Forwards the
+ // provider/model overrides so an LLM check honors the autopilot's choice.
+ callStagedLLM: (stage, vars, opts = {}) =>
+ runStagedLLM(stage, vars, { providerOverride, modelOverride, ...opts }),
+ };
+
+ const findings = [];
+ const perCheck = [];
+ let canceled = false;
+ for (const { check, config } of enabled) {
+ if (signal?.aborted) { canceled = true; break; }
+ onProgress?.({ type: 'check:start', checkId: check.id, label: check.label });
+ const ctx = { ...baseCtx, config, severityDefault: check.severityDefault };
+ // Boundary try/catch: a check's run() calls into arbitrary logic / LLM
+ // providers — one bad check must not abort the whole pass (mirrors the
+ // per-comment fix guard in seriesAutopilot.runEditorial).
+ try {
+ if (typeof check.gate === 'function' && !check.gate(ctx)) {
+ perCheck.push({ checkId: check.id, count: 0, skipped: true });
+ onProgress?.({ type: 'check:complete', checkId: check.id, count: 0, skipped: true });
+ continue;
+ }
+ const raw = (await check.run(ctx)) || [];
+ const stamped = raw.map((f) => ({ ...f, checkId: check.id }));
+ findings.push(...stamped);
+ perCheck.push({ checkId: check.id, count: stamped.length });
+ onProgress?.({ type: 'check:complete', checkId: check.id, count: stamped.length });
+ } catch (err) {
+ const message = (err?.message || String(err)).slice(0, 500);
+ console.error(`❌ editorial check ${check.id} failed — series=${String(seriesId).slice(0, 12)} ${message}`);
+ perCheck.push({ checkId: check.id, error: message });
+ onProgress?.({ type: 'check:complete', checkId: check.id, error: message });
+ }
+ }
+
+ // Seed in 'merge' mode (never 'fresh'): a per-series seed of only the editorial
+ // checks' findings must not auto-dismiss completeness or other-check open
+ // comments. Merge dedups via findingKey (which now includes checkId) and keeps
+ // dismissed findings suppressed per-check.
+ if (findings.length) {
+ await seedReviewFromFindings(seriesId, findings, { runId, mode: 'merge' });
+ }
+ return { runId, findings, perCheck, canceled };
+}
+
+/**
+ * Dry-run preview: which checks would run for the current settings (+ optional
+ * subset), without executing them. Used by the run route's plan response and by
+ * callers that want to show the user what's enabled.
+ */
+export async function buildEditorialCheckPlan(seriesId, { checkIds = null, settings } = {}) {
+ const resolved = settings || await getSettings();
+ const subset = Array.isArray(checkIds) && checkIds.length ? new Set(checkIds) : null;
+ const checks = resolveCheckState(resolved)
+ .filter((row) => row.enabled && (!subset || subset.has(row.id)))
+ .map((row) => ({ id: row.id, label: row.label, kind: row.kind, scope: row.scope }));
+ return { seriesId, checks, enabledCount: checks.length };
+}
+
+// ---------------------------------------------------------------------------
+// SSE run-tracking (mirrors manuscriptCompletenessRunner.js).
+// ---------------------------------------------------------------------------
+
+// runs: Map<seriesId, { runId, clients[], lastPayload, cancelRequested, finished, cleanupTimer, startedAt, abort }>
+const runs = new Map();
+
+export function isEditorialChecksActive(seriesId) {
+ const run = runs.get(seriesId);
+ return !!run && !run.finished;
+}
+
+function scheduleCleanup(seriesId, record) {
+ record.cleanupTimer = setTimeout(() => {
+ if (runs.get(seriesId) !== record) return;
+ for (const c of record.clients) c.end();
+ runs.delete(seriesId);
+ }, SSE_CLEANUP_DELAY_MS);
+}
+
+export function attachClient(seriesId, res) {
+ return attachSseClient(runs, seriesId, res);
+}
+
+export function cancelEditorialChecks(seriesId) {
+ const run = runs.get(seriesId);
+ if (!run) return false;
+ run.cancelRequested = true;
+ run.abort?.abort();
+ return true;
+}
+
+function broadcast(seriesId, payload) {
+ const run = runs.get(seriesId);
+ if (!run) return;
+ broadcastSse(run, payload);
+}
+
+/**
+ * Kick off a streamed editorial-checks run. Returns the runId immediately;
+ * progress lands via SSE. Re-calling while a run is in flight resolves to the
+ * existing runId.
+ */
+export function startEditorialChecksRun(seriesId, options = {}) {
+ const existing = runs.get(seriesId);
+ if (existing && !existing.finished) {
+ return { runId: existing.runId, alreadyRunning: true };
+ }
+ if (existing) {
+ if (existing.cleanupTimer) clearTimeout(existing.cleanupTimer);
+ for (const c of existing.clients) c.end();
+ }
+ const runId = randomUUID();
+ const abort = new AbortController();
+ const record = {
+ runId,
+ clients: [],
+ lastPayload: null,
+ cancelRequested: false,
+ finished: false,
+ cleanupTimer: null,
+ startedAt: new Date().toISOString(),
+ abort,
+ };
+ runs.set(seriesId, record);
+
+ // Fire-and-forget coordinator. The try/catch is the permitted boundary use:
+ // an unhandled LLM rejection here would crash the process on Node ≥15.
+ (async () => {
+ try {
+ broadcast(seriesId, { type: 'start', runId });
+ const result = await runEditorialChecks(seriesId, {
+ checkIds: options.checkIds,
+ providerOverride: options.providerOverride,
+ modelOverride: options.modelOverride,
+ signal: abort.signal,
+ onProgress: (event) => broadcast(seriesId, { ...event, runId }),
+ });
+ if (record.cancelRequested || result.canceled) {
+ broadcast(seriesId, { type: 'canceled', runId, canceledAt: new Date().toISOString() });
+ console.log(`📝 editorial checks canceled — series=${String(seriesId).slice(0, 12)}`);
+ return;
+ }
+ broadcast(seriesId, {
+ type: 'complete',
+ runId,
+ findingCount: result.findings.length,
+ perCheck: result.perCheck,
+ completedAt: new Date().toISOString(),
+ });
+ console.log(`📝 editorial checks complete — series=${String(seriesId).slice(0, 12)} findings=${result.findings.length}`);
+ } catch (err) {
+ const message = (err?.message || String(err)).slice(0, 1000);
+ console.error(`❌ editorial checks failed — series=${String(seriesId).slice(0, 12)} ${message}`);
+ broadcast(seriesId, { type: 'error', runId, error: message, failedAt: new Date().toISOString() });
+ } finally {
+ record.finished = true;
+ scheduleCleanup(seriesId, record);
+ }
+ })();
+
+ return { runId, alreadyRunning: false };
+}
+
+// Export internals for tests.
+export const __testing = { runs };
diff --git a/server/services/pipeline/editorial/checkRunner.test.js b/server/services/pipeline/editorial/checkRunner.test.js
new file mode 100644
index 0000000000..98226f4c11
--- /dev/null
+++ b/server/services/pipeline/editorial/checkRunner.test.js
@@ -0,0 +1,125 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Mock the data sources + LLM + seed, but use the REAL registry so the runner
+// exercises the actual reference checks (deterministic naming + LLM info-dump).
+vi.mock('../../settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));
+vi.mock('../series.js', () => ({ getSeries: vi.fn(async () => ({ id: 's1', universeId: 'u1' })) }));
+vi.mock('../issues.js', () => ({ listIssues: vi.fn(async () => []) }));
+vi.mock('../seriesCanon.js', () => ({
+ getSeriesCanon: vi.fn(async () => ({
+ characters: [{ name: 'Alina' }, { name: 'Alana' }, { name: 'Zog' }],
+ places: [],
+ objects: [],
+ })),
+}));
+vi.mock('../arcPlanner.js', () => ({
+ collectManuscriptSections: vi.fn(async () => [
+ { number: 1, title: 'Pilot', stageId: 'prose', content: 'As you know, Bob, the kingdom fell.' },
+ ]),
+ sectionsCorpus: vi.fn((sections) => sections.map((s) => s.content).join('\n')),
+}));
+vi.mock('../../../lib/stageRunner.js', () => ({
+ runStagedLLM: vi.fn(async () => ({
+ runId: 'llm-run',
+ content: {
+ findings: [
+ { severity: 'medium', issueNumber: 1, location: 'p1', problem: 'Info dump in opening', suggestion: 'Dramatize it', anchorQuote: 'As you know, Bob' },
+ ],
+ },
+ })),
+}));
+
+// A real-ish seed that applies the same checkId-aware dedup key the store uses,
+// so the runner-dedup test reflects production behavior.
+const seedStore = [];
+const findingKey = (c) => `${c.checkId ?? ''}|${c.issueNumber ?? ''}|${c.anchorQuote}|${c.problem}`;
+const seedReviewFromFindings = vi.fn(async (_seriesId, findings) => {
+ const seen = new Set(seedStore.map(findingKey));
+ for (const f of findings) {
+ const k = findingKey(f);
+ if (!seen.has(k)) { seedStore.push(f); seen.add(k); }
+ }
+ return { comments: seedStore };
+});
+vi.mock('../manuscriptReview.js', () => ({ seedReviewFromFindings: (...a) => seedReviewFromFindings(...a) }));
+
+const { runEditorialChecks, buildEditorialCheckPlan } = await import('./checkRunner.js');
+const { runStagedLLM } = await import('../../../lib/stageRunner.js');
+
+beforeEach(() => {
+ seedStore.length = 0;
+ seedReviewFromFindings.mockClear();
+ runStagedLLM.mockClear();
+});
+
+describe('runEditorialChecks', () => {
+ it('runs enabled checks, stamps checkId, and seeds findings', async () => {
+ const result = await runEditorialChecks('s1');
+ // Naming finds the Alina/Alana pair; info-dump returns one LLM finding.
+ expect(result.findings.length).toBeGreaterThanOrEqual(2);
+ for (const f of result.findings) {
+ expect(f.checkId, 'every finding carries its checkId').toBeTruthy();
+ }
+ expect(result.findings.some((f) => f.checkId === 'naming.dissimilar-names')).toBe(true);
+ expect(result.findings.some((f) => f.checkId === 'prose.info-dumping')).toBe(true);
+
+ // Seeded once, in 'merge' mode (never auto-dismiss other checks' findings).
+ expect(seedReviewFromFindings).toHaveBeenCalledTimes(1);
+ expect(seedReviewFromFindings.mock.calls[0][2]).toMatchObject({ mode: 'merge' });
+ });
+
+ it('reports per-check counts', async () => {
+ const result = await runEditorialChecks('s1');
+ const naming = result.perCheck.find((p) => p.checkId === 'naming.dissimilar-names');
+ expect(naming.count).toBeGreaterThan(0);
+ });
+
+ it('re-running dedups findings (checkId-aware key)', async () => {
+ await runEditorialChecks('s1');
+ const afterFirst = seedStore.length;
+ expect(afterFirst).toBeGreaterThan(0);
+ await runEditorialChecks('s1');
+ expect(seedStore.length, 're-run adds no duplicates').toBe(afterFirst);
+ });
+
+ it('runs only the requested subset', async () => {
+ const result = await runEditorialChecks('s1', { checkIds: ['naming.dissimilar-names'] });
+ expect(runStagedLLM).not.toHaveBeenCalled(); // info-dump (the only LLM check) skipped
+ expect(result.findings.every((f) => f.checkId === 'naming.dissimilar-names')).toBe(true);
+ });
+
+ it('skips disabled checks', async () => {
+ const settings = { pipelineEditorialChecks: { checks: { 'prose.info-dumping': { enabled: false } } } };
+ const result = await runEditorialChecks('s1', { settings });
+ expect(runStagedLLM).not.toHaveBeenCalled();
+ expect(result.findings.every((f) => f.checkId === 'naming.dissimilar-names')).toBe(true);
+ });
+
+ it('returns an empty result when no checks are enabled', async () => {
+ const settings = {
+ pipelineEditorialChecks: {
+ checks: { 'naming.dissimilar-names': { enabled: false }, 'prose.info-dumping': { enabled: false } },
+ },
+ };
+ const result = await runEditorialChecks('s1', { settings });
+ expect(result.findings).toEqual([]);
+ expect(seedReviewFromFindings).not.toHaveBeenCalled();
+ });
+
+ it('one failing check does not abort the pass', async () => {
+ runStagedLLM.mockRejectedValueOnce(new Error('provider down'));
+ const result = await runEditorialChecks('s1');
+ // Naming still produced findings; info-dump recorded an error in perCheck.
+ expect(result.findings.some((f) => f.checkId === 'naming.dissimilar-names')).toBe(true);
+ const infodump = result.perCheck.find((p) => p.checkId === 'prose.info-dumping');
+ expect(infodump.error).toMatch(/provider down/);
+ });
+});
+
+describe('buildEditorialCheckPlan', () => {
+ it('lists enabled checks for a dry run', async () => {
+ const plan = await buildEditorialCheckPlan('s1');
+ expect(plan.enabledCount).toBe(plan.checks.length);
+ expect(plan.checks.map((c) => c.id)).toContain('naming.dissimilar-names');
+ });
+});
diff --git a/server/services/pipeline/manuscriptReview.js b/server/services/pipeline/manuscriptReview.js
index 21ccc95f14..094c2fb2ad 100644
--- a/server/services/pipeline/manuscriptReview.js
+++ b/server/services/pipeline/manuscriptReview.js
@@ -109,6 +109,11 @@ function sanitizeComment(raw) {
? raw.replacementStrategy
: replacementStrategyForCategory(category),
anchorQuote: clampStr(raw.anchorQuote, 400),
+ // Which editorial check produced this finding (#1284). `null` for findings
+ // from the manuscript-completeness pass (and older peers / legacy records)
+ // — those predate the registry, so they group as a single un-checked set.
+ // Optional + additive, so the synced review doc stays backward-compatible.
+ checkId: typeof raw.checkId === 'string' && raw.checkId ? raw.checkId : null,
status: STATUS_SET.has(raw.status) ? raw.status : 'open',
fix: sanitizeFix(raw.fix),
sourceRunId: typeof raw.sourceRunId === 'string' ? raw.sourceRunId : null,
@@ -143,9 +148,13 @@ export async function getReview(seriesId) {
return readReview(seriesId);
}
-// Stable identity for a finding so re-running completeness doesn't duplicate a
-// still-open comment the user hasn't acted on yet.
-const findingKey = (c) => `${c.issueNumber ?? ''}|${c.anchorQuote}|${c.problem}`;
+// Stable identity for a finding so re-running completeness (or an editorial
+// check) doesn't duplicate a still-open comment the user hasn't acted on yet.
+// `checkId` is part of the key so the same anchor flagged by two different
+// checks stays as two distinct findings, and a dismissed finding only stays
+// suppressed for the check that raised it. Completeness findings carry no
+// checkId (→ '' prefix), so their existing dedup is unchanged.
+const findingKey = (c) => `${c.checkId ?? ''}|${c.issueNumber ?? ''}|${c.anchorQuote}|${c.problem}`;
/**
* Merge a fresh set of shaped completeness findings into the review.
diff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.js
index 4cb3d4cc15..3ef882d770 100644
--- a/server/services/pipeline/seriesAutopilot.js
+++ b/server/services/pipeline/seriesAutopilot.js
@@ -90,6 +90,7 @@ import {
import * as volumeBeatsRunner from './volumeBeatsRunner.js';
import * as autoRunner from './autoRunner.js';
import { seedReviewFromFindings, getReview } from './manuscriptReview.js';
+import { runEditorialChecks } from './editorial/checkRunner.js';
import { generateManuscriptFix, acceptManuscriptFix } from './manuscriptFix.js';
import { verifyComicScript } from './scriptVerify.js';
import { checkSeriesCanonReadiness } from './canonReadiness.js';
@@ -272,6 +273,13 @@ export function resolveNextStep(series, issues, runState = {}, options = {}) {
return { kind: 'editorialReview', reason: 'editorial review not yet run this run' };
}
+ // STEP 5.2 — registry-driven editorial checks (#1284). Runs the enabled
+ // editorial checks once per run and seeds their findings into the same
+ // manuscript-review comment set. A no-op when no checks are enabled.
+ if (!runState.editorialChecksReviewed) {
+ return { kind: 'editorialChecks', reason: 'editorial checks not yet run this run' };
+ }
+
// STEP 5.5 — canon descriptive integrity. Before ANY visual production, every
// canon noun that appears where it'd be drawn must be described (an artist
// can't render a name). Runs once per run; the gate blocks (pauses) on
@@ -593,6 +601,27 @@ async function runEditorial(sId, record) {
return {};
}
+// STEP 5.2 — run the registry-driven editorial checks once per run, seeding
+// their findings into the same manuscript-review comment set. LLM-kind checks
+// cost tokens, so gate on the daily budget first; a no-op when no checks are
+// enabled (the runner returns zero findings). Failures are surfaced (logged)
+// but never block the run — editorial checks are advisory.
+async function runEditorialChecksPass(sId, record) {
+ if (record.cancelRequested) return { canceled: true };
+ const beforeChecks = await budgetPause();
+ if (beforeChecks) return beforeChecks;
+ const result = await runEditorialChecks(sId, providerOverrideOpts(record)).catch((err) => {
+ console.log(`⚠️ autopilot: editorial checks failed for ${sId.slice(0, 12)}: ${err.message}`);
+ return null;
+ });
+ if (result) {
+ await recordDomainUsage('cos', { actions: 1 });
+ broadcast(sId, { type: 'verify:round', scope: 'editorialChecks', round: 1, findings: result.findings.length, blocking: 0 });
+ }
+ record.runState.editorialChecksReviewed = true;
+ return {};
+}
+
// Turn a render-enqueue result into the { slotKey, slot } pair the render
// routes persist (proof → proofImage, final → finalImage).
const slotFromRenderResult = (result) => {
@@ -820,6 +849,8 @@ async function dispatchStep(sId, step, record) {
return runScriptVerify(sId, step.issueId, record);
case 'editorialReview':
return runEditorial(sId, record);
+ case 'editorialChecks':
+ return runEditorialChecksPass(sId, record);
case 'canonVerify':
return runCanonVerify(sId, record);
case 'visualDraft':
@@ -855,6 +886,7 @@ function buildDryRunPlan(series, issues, options) {
if (textNeeded) plan.push({ kind: 'textStages', count: textNeeded });
if (isComicTarget(series)) plan.push({ kind: 'scriptVerify', count: ordered.length });
plan.push({ kind: 'editorialReview', count: 1, note: `up to ${MAX_EDITORIAL_ROUNDS} rounds` });
+ plan.push({ kind: 'editorialChecks', count: 1, note: 'enabled editorial checks (#1284)' });
if (VISUAL_DRAFT_ENABLED && wantsVisual(options) && isComicTarget(series)) {
plan.push({ kind: 'canonVerify', count: 1, note: 'descriptive integrity of drawn nouns' });
const visualNeeded = ordered.filter((i) => !visualReady(i)).length;
@@ -906,6 +938,7 @@ export async function startSeriesAutopilot(sId, options = {}) {
arcAttempted: false,
arcVerified: false,
editorialReviewed: false,
+ editorialChecksReviewed: false,
canonVerified: false,
episodesAttempted: new Set(),
beatsAttempted: new Set(),
diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
index e49d308abb..5bcd319302 100644
--- a/server/services/pipeline/seriesAutopilot.test.js
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -70,6 +70,9 @@ vi.mock('./manuscriptReview.js', () => ({
seedReviewFromFindings: vi.fn(async () => ({ comments: [] })),
getReview: vi.fn(async () => ({ comments: [] })),
}));
+vi.mock('./editorial/checkRunner.js', () => ({
+ runEditorialChecks: vi.fn(async () => ({ runId: 'ec', findings: [], perCheck: [], canceled: false })),
+}));
vi.mock('./manuscriptFix.js', () => ({
generateManuscriptFix: vi.fn(async () => ({})),
acceptManuscriptFix: vi.fn(async () => ({})),
@@ -218,13 +221,23 @@ describe('resolveNextStep (pure)', () => {
expect(step.kind).toBe('editorialReview');
});
- it('is done once editorial review has run (no visuals requested)', () => {
+ it('asks for editorial checks after editorial review, before done/visuals', () => {
const step = resolveNextStep(
comic,
[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
{ arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true },
{ includeVisual: false },
);
+ expect(step.kind).toBe('editorialChecks');
+ });
+
+ it('is done once editorial review has run (no visuals requested)', () => {
+ const step = resolveNextStep(
+ comic,
+ [issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
+ { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true },
+ { includeVisual: false },
+ );
expect(step.kind).toBe('done');
});
@@ -232,7 +245,7 @@ describe('resolveNextStep (pure)', () => {
const step = resolveNextStep(
comic,
[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
- { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true },
+ { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true },
{ includeVisual: true, target: 'text' },
);
expect(step.kind).toBe('done');
@@ -242,7 +255,7 @@ describe('resolveNextStep (pure)', () => {
const step = resolveNextStep(
comic,
[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
- { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true },
+ { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true },
{ includeVisual: true },
);
expect(step.kind).toBe('canonVerify');
@@ -252,7 +265,7 @@ describe('resolveNextStep (pure)', () => {
const step = resolveNextStep(
comic,
[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],
- { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, canonVerified: true },
+ { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true, canonVerified: true },
{ includeVisual: true },
);
expect(step).toMatchObject({ kind: 'visualDraft', issueId: 'iss1' });
@@ -271,7 +284,7 @@ describe('resolveNextStep (pure)', () => {
const step = resolveNextStep(
comic,
[issue({ stages: renderedStages })],
- { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, canonVerified: true },
+ { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true, canonVerified: true },
{ includeVisual: true },
);
expect(step.kind).toBe('done');