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-1285]): Editorial Checks UI — catalog, config, run, triage

[._.]/ Adam Eivy96f4e26bb10d
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 06825fc968..9abea991c6 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -91,6 +91,7 @@ const Importer = lazyWithReload(() => import('./pages/Importer'));
const StoryBuilder = lazyWithReload(() => import('./pages/StoryBuilder'));
const PipelineSeries = lazyWithReload(() => import('./pages/PipelineSeries'));
const PipelineSeriesRoadmap = lazyWithReload(() => import('./pages/PipelineSeriesRoadmap'));
+const PipelineEditorialChecks = lazyWithReload(() => import('./pages/PipelineEditorialChecks'));
const PipelineManuscriptEditor = lazyWithReload(() => import('./pages/PipelineManuscriptEditor'));
const PipelineIssue = lazyWithReload(() => import('./pages/PipelineIssue'));
const Login = lazyWithReload(() => import('./pages/Login'));
@@ -309,6 +310,7 @@ export default function App() {
<Route path="story-builder/:storyId/:step" element={<StoryBuilder />} />
<Route path="authors" element={<Authors />} />
<Route path="pipeline" element={<Pipeline />} />
+ <Route path="pipeline/editorial-checks" element={<PipelineEditorialChecks />} />
<Route path="pipeline/series/:seriesId" element={<PipelineSeries />} />
<Route path="pipeline/series/:seriesId/roadmap" element={<PipelineSeriesRoadmap />} />
{/* Splat (not a :param route) so navigating between issues reuses the
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 90315fe863..c52d76e61d 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -49,6 +49,7 @@ import {
Cigarette,
HeartPulse,
ClipboardList,
+ ListChecks,
Compass,
Scale,
LayoutDashboard,
@@ -199,6 +200,7 @@ const navItems = [
children: [
{ to: '/authors', label: 'Authors', icon: FilePen },
{ to: '/catalog', label: 'Catalog', icon: Sparkles },
+ { to: '/pipeline/editorial-checks', label: 'Editorial Checks', icon: ListChecks },
{ to: '/importer', label: 'Importer', icon: FileInput },
{ to: '/media', label: 'Media Gen', icon: Layers },
{ to: '/pipeline', label: 'Series Pipeline', icon: WorkflowIcon, dynamic: 'pipelineSeries' },
diff --git a/client/src/components/pipeline/editorial/EditorialCheckCard.jsx b/client/src/components/pipeline/editorial/EditorialCheckCard.jsx
new file mode 100644
index 0000000000..0cddc2d066
--- /dev/null
+++ b/client/src/components/pipeline/editorial/EditorialCheckCard.jsx
@@ -0,0 +1,140 @@
+/**
+ * One catalog row in the Editorial Checks page (#1285): a registered editorial
+ * check with its enable toggle, kind/severity badges, and an expandable config
+ * form built from the check's `configFields` render descriptors.
+ *
+ * Presentational — all persistence is lifted to PipelineEditorialChecks:
+ * onToggle(checkId, nextEnabled) → optimistic enable/disable PATCH
+ * onConfigSave(checkId, nextConfig) → PATCH the full config blob (Promise)
+ * The card only owns the in-progress *input* draft; committed values come back
+ * down through `check.config`.
+ */
+import { useEffect, useState } from 'react';
+import { ChevronDown, ChevronRight, Loader2, Sliders } from 'lucide-react';
+import ToggleSwitch from '../../ToggleSwitch';
+
+const KIND_BADGE = {
+ deterministic: 'bg-sky-500/15 text-sky-300 border-sky-500/30',
+ llm: 'bg-purple-500/15 text-purple-300 border-purple-500/30',
+};
+const SEVERITY_BADGE = {
+ high: 'bg-rose-500/15 text-rose-300',
+ medium: 'bg-amber-500/15 text-amber-300',
+ low: 'bg-gray-500/15 text-gray-300',
+};
+
+function ConfigField({ checkId, field, value, disabled, onCommit }) {
+ const inputId = `cfg-${checkId}-${field.key}`;
+ const [draft, setDraft] = useState(value);
+ // Re-seed when the committed value changes underneath us (e.g. save resolved).
+ useEffect(() => { setDraft(value); }, [value]);
+
+ if (field.type === 'boolean') {
+ return (
+ <div className="flex items-center justify-between gap-3">
+ <label htmlFor={inputId} className="text-xs text-gray-300">{field.label}</label>
+ <ToggleSwitch
+ size="sm"
+ enabled={!!draft}
+ disabled={disabled}
+ ariaLabel={field.label}
+ onChange={() => { const next = !draft; setDraft(next); onCommit(field.key, next); }}
+ />
+ </div>
+ );
+ }
+
+ const commit = () => {
+ let next = draft;
+ if (field.type === 'number') {
+ next = Number(draft);
+ if (!Number.isFinite(next)) { setDraft(value); return; }
+ if (typeof field.min === 'number') next = Math.max(field.min, next);
+ if (typeof field.max === 'number') next = Math.min(field.max, next);
+ setDraft(next);
+ }
+ if (next !== value) onCommit(field.key, next);
+ };
+
+ return (
+ <div className="flex flex-col gap-1">
+ <label htmlFor={inputId} className="text-xs text-gray-300">{field.label}</label>
+ <input
+ id={inputId}
+ type={field.type === 'number' ? 'number' : 'text'}
+ value={draft ?? ''}
+ min={field.min}
+ max={field.max}
+ step={field.step}
+ disabled={disabled}
+ onChange={(e) => setDraft(e.target.value)}
+ onBlur={commit}
+ onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); e.currentTarget.blur(); } }}
+ className="w-full rounded border border-port-border bg-port-bg px-2 py-1 text-sm text-gray-100 focus:border-port-accent focus:outline-none disabled:opacity-50"
+ />
+ {field.help ? <p className="text-[11px] text-gray-500">{field.help}</p> : null}
+ </div>
+ );
+}
+
+export default function EditorialCheckCard({ check, saving = false, onToggle, onConfigSave }) {
+ const [expanded, setExpanded] = useState(false);
+ const hasConfig = Array.isArray(check.configFields) && check.configFields.length > 0;
+
+ return (
+ <div className="rounded-lg border border-port-border bg-port-card p-3 space-y-2">
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0 space-y-1">
+ <div className="flex flex-wrap items-center gap-1.5">
+ <span className="text-sm font-medium text-gray-100">{check.label}</span>
+ <span className={`text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded border ${KIND_BADGE[check.kind] || KIND_BADGE.deterministic}`}>
+ {check.kind === 'llm' ? 'LLM' : 'rule'}
+ </span>
+ <span className={`text-[10px] px-1.5 py-0.5 rounded ${SEVERITY_BADGE[check.severityDefault] || SEVERITY_BADGE.low}`}>
+ {check.severityDefault}
+ </span>
+ </div>
+ <p className="text-xs text-gray-400">{check.description}</p>
+ </div>
+ <div className="flex items-center gap-2 shrink-0">
+ {saving ? <Loader2 size={14} className="animate-spin text-gray-500" /> : null}
+ <ToggleSwitch
+ enabled={check.enabled}
+ disabled={saving}
+ ariaLabel={`${check.enabled ? 'Disable' : 'Enable'} ${check.label}`}
+ onChange={() => onToggle(check.id, !check.enabled)}
+ />
+ </div>
+ </div>
+
+ {hasConfig ? (
+ <div className="border-t border-port-border/60 pt-2">
+ <button
+ type="button"
+ onClick={() => setExpanded((v) => !v)}
+ className="flex items-center gap-1 text-[11px] text-gray-400 hover:text-gray-200"
+ aria-expanded={expanded}
+ >
+ {expanded ? <ChevronDown size={13} /> : <ChevronRight size={13} />}
+ <Sliders size={12} />
+ Configure ({check.configFields.length})
+ </button>
+ {expanded ? (
+ <div className="mt-2 space-y-2.5">
+ {check.configFields.map((field) => (
+ <ConfigField
+ key={field.key}
+ checkId={check.id}
+ field={field}
+ value={check.config?.[field.key]}
+ disabled={saving}
+ onCommit={(key, val) => onConfigSave(check.id, { ...check.config, [key]: val })}
+ />
+ ))}
+ </div>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/client/src/components/pipeline/editorial/EditorialCheckCard.test.jsx b/client/src/components/pipeline/editorial/EditorialCheckCard.test.jsx
new file mode 100644
index 0000000000..0f8c926b2c
--- /dev/null
+++ b/client/src/components/pipeline/editorial/EditorialCheckCard.test.jsx
@@ -0,0 +1,45 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, fireEvent } from '@testing-library/react';
+import EditorialCheckCard from './EditorialCheckCard';
+
+const check = {
+ id: 'naming.dissimilar-names',
+ label: 'Character name dissimilarity',
+ description: 'Flags confusable names.',
+ scope: 'series',
+ kind: 'deterministic',
+ severityDefault: 'low',
+ enabled: true,
+ config: { minSharedSignals: 2 },
+ configFields: [
+ { key: 'minSharedSignals', label: 'Minimum shared signals to flag', type: 'number', min: 1, max: 5, step: 1 },
+ ],
+};
+
+describe('EditorialCheckCard', () => {
+ it('toggles enable through onToggle with the negated value', () => {
+ const onToggle = vi.fn();
+ render(<EditorialCheckCard check={check} onToggle={onToggle} onConfigSave={vi.fn()} />);
+ fireEvent.click(screen.getByRole('switch', { name: /disable character name/i }));
+ expect(onToggle).toHaveBeenCalledWith('naming.dissimilar-names', false);
+ });
+
+ it('commits a clamped config value on blur, merged onto the existing config', () => {
+ const onConfigSave = vi.fn();
+ render(<EditorialCheckCard check={check} onToggle={vi.fn()} onConfigSave={onConfigSave} />);
+ fireEvent.click(screen.getByRole('button', { name: /configure/i }));
+ const input = screen.getByLabelText('Minimum shared signals to flag');
+ fireEvent.change(input, { target: { value: '9' } }); // above max 5
+ fireEvent.blur(input);
+ expect(onConfigSave).toHaveBeenCalledWith('naming.dissimilar-names', { minSharedSignals: 5 });
+ });
+
+ it('does not save when the committed value is unchanged', () => {
+ const onConfigSave = vi.fn();
+ render(<EditorialCheckCard check={check} onToggle={vi.fn()} onConfigSave={onConfigSave} />);
+ fireEvent.click(screen.getByRole('button', { name: /configure/i }));
+ const input = screen.getByLabelText('Minimum shared signals to flag');
+ fireEvent.blur(input); // still 2
+ expect(onConfigSave).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx b/client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx
new file mode 100644
index 0000000000..06e93cb586
--- /dev/null
+++ b/client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx
@@ -0,0 +1,96 @@
+/**
+ * Findings triage for the Editorial Checks page (#1285): the check-sourced
+ * comments seeded into the manuscript review store, grouped by check with
+ * severity counts. Each finding deep-links into the manuscript editor (which
+ * opens its comment card via the `?comment=` param) where the existing
+ * Accept / Dismiss / Generate-fix flow lives — this view is read + navigate
+ * only, so triage logic stays in one place.
+ */
+import { Link } from 'react-router-dom';
+import { ChevronDown, ChevronRight, ExternalLink } from 'lucide-react';
+import { useState } from 'react';
+import { groupFindingsByCheck, findingManuscriptLink, openFindingsTotal } from '../../../lib/editorialChecks';
+
+const SEVERITY_DOT = {
+ high: 'bg-rose-400',
+ medium: 'bg-amber-400',
+ low: 'bg-gray-400',
+};
+const STATUS_TONE = {
+ open: 'text-gray-200',
+ accepted: 'text-emerald-400 line-through',
+ dismissed: 'text-gray-600 line-through',
+};
+
+function CountPills({ counts }) {
+ return (
+ <span className="flex items-center gap-1.5">
+ {['high', 'medium', 'low'].map((sev) => (counts[sev] ? (
+ <span key={sev} className="flex items-center gap-1 text-[10px] text-gray-400">
+ <span className={`h-2 w-2 rounded-full ${SEVERITY_DOT[sev]}`} />
+ {counts[sev]}
+ </span>
+ ) : null))}
+ </span>
+ );
+}
+
+function CheckGroup({ seriesId, group }) {
+ const [open, setOpen] = useState(group.open > 0);
+ return (
+ <div className="rounded-lg border border-port-border bg-port-card">
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ className="flex w-full items-center justify-between gap-2 p-2.5 text-left"
+ aria-expanded={open}
+ >
+ <span className="flex items-center gap-1.5 min-w-0">
+ {open ? <ChevronDown size={14} className="shrink-0" /> : <ChevronRight size={14} className="shrink-0" />}
+ <span className="text-sm font-medium text-gray-100 truncate">{group.label}</span>
+ <span className="text-[10px] text-gray-500 shrink-0">{group.open} open · {group.total} total</span>
+ </span>
+ <CountPills counts={group.counts} />
+ </button>
+ {open ? (
+ <ul className="divide-y divide-port-border/60 border-t border-port-border/60">
+ {group.comments.map((c) => (
+ <li key={c.id} className="p-2.5">
+ <Link
+ to={findingManuscriptLink(seriesId, c)}
+ className="group flex items-start justify-between gap-2"
+ >
+ <span className="min-w-0 space-y-0.5">
+ <span className={`block text-xs ${STATUS_TONE[c.status] || STATUS_TONE.open}`}>
+ <span className={`mr-1.5 inline-block h-2 w-2 rounded-full align-middle ${SEVERITY_DOT[c.severity] || SEVERITY_DOT.low}`} />
+ {c.problem}
+ </span>
+ {c.location ? <span className="block text-[11px] text-gray-500">{c.location}</span> : null}
+ </span>
+ <ExternalLink size={13} className="mt-0.5 shrink-0 text-gray-600 group-hover:text-port-accent" />
+ </Link>
+ </li>
+ ))}
+ </ul>
+ ) : null}
+ </div>
+ );
+}
+
+export default function EditorialFindingsTriage({ seriesId, comments = [], checksById = {} }) {
+ const groups = groupFindingsByCheck(comments, checksById);
+ if (!groups.length) {
+ return (
+ <p className="rounded-lg border border-dashed border-port-border p-4 text-center text-xs text-gray-500">
+ No editorial-check findings yet. Run the enabled checks to populate this list.
+ </p>
+ );
+ }
+ const totalOpen = openFindingsTotal(groups);
+ return (
+ <div className="space-y-2">
+ <p className="text-[11px] text-gray-500">{totalOpen} open finding{totalOpen === 1 ? '' : 's'} across {groups.length} check{groups.length === 1 ? '' : 's'}</p>
+ {groups.map((g) => <CheckGroup key={g.checkId} seriesId={seriesId} group={g} />)}
+ </div>
+ );
+}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index cea1a08b5d..36d605f2fe 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -93,6 +93,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `colorMatch.js` | Pure grading core for the song system's color-match training mode: `buildColorMatchTimeline(score, { bpm })` → `{ notes, totalMs, msPerQuarter, bpm }` (each note's target frequency + onset/offset window in ms, keyed by the same global note index the renderer flattens, timing mirroring `scorePlayback`); `gradeNote(hz, targetHz)` classifies a sung pitch against a target into `in-tune`/`close`/`off`/`missed` (octave-folded, thresholds `MATCH_IN_TUNE_CENTS`/`MATCH_CLOSE_CENTS`); `noteAtTime(timeline, tMs, fromIdx)` finds the active note for a rAF cursor; `summarizeAccuracy(grades)` → `{ graded, counts, percentInTune, perNote }` per-take summary (`perNote` is the ordered grade list a saved take persists, mirroring the server sanitizer); `gradesFromPerNote(timeline, perNote)` is its inverse — rebuilds the noteIndex→grade map to repaint a saved take's grading on open without re-grading audio; plus `centsBetween` and the `GRADE` enum. No React, no audio — the `useColorMatch` hook drives it. |
| `pitchDetect.js` | Dependency-free vocal pitch-detection core for the song system (tuner / color-match / sing-to-score). `detectFrequency(frame, { sampleRate })` → `{ hz, clarity }` (McLeod NSDF; clarity gate rejects silence/noise); `frequencyToNote(hz, { a4 })` → `{ letter, accidental, octave, step, cents }` (cents ∈ [-50,+50], sharp positive; `step` reuses `scoreNotation`'s `diatonicStep` so detected notes align with the renderer); `noteToFrequency(note, { a4 })` inverse (color-match targets); `createPitchTracker(analyser, { onUpdate })` → `{ stop }` rAF/interval loop with median+EMA smoothing to kill octave jumps; `tuningQuality(cents)` → `{ level, label }` buckets a cents deviation into `in-tune`/`close`/`off`/`none` (thresholds `IN_TUNE_CENTS`/`CLOSE_CENTS`) for the tuner color readout. |
| `universeBuilderExpand.js` | `mergeExpandIntoDraft(draft, result)` — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with `kind` precedence, canon dedupe by name/slugline/alias). Also exports `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` for callers that need the building blocks (per-category Generate, save-time refetch+merge). |
+| `editorialChecks.js` | Pure helpers for the Editorial Checks page (`/pipeline/editorial-checks`, #1285): `groupChecksByScope(checks)` buckets catalog rows into ordered Noun/Scene/Issue/Series sections; `groupFindingsByCheck(comments, rowsById)` groups check-sourced review comments per check with open/total + severity counts; `openFindingsTotal(groups)` sums open findings; `findingManuscriptLink(seriesId, comment)` builds the `?comment=` deep-link into the manuscript editor; plus `scopeLabel` and the `CHECK_SCOPE_ORDER`/`CHECK_SCOPE_LABELS` tables. No React/window — the page and its tests share them. |
| `metronome.js` | Sample-accurate Web Audio metronome — the shared timing grid for the song system and first consumer of the song `tempo` field. `createMetronome({ bpm, beatsPerBar, countInBars, onBeat, onCountInComplete })` lookahead-schedules accented click tones on the shared `AudioContext` clock (same pattern as `songPlayback.js`), emits `{ beat, bar, accent, countIn, whenAudioTime }` per beat (the beat-clock callback color-match/sing-to-score subscribe to), and tears down all timers on `stop()`. Plus `clampBpm` (20–320), `secondsPerBeat`, `timeSignatureFromScore`, `beatDescriptor`. |
| `pianoKeyboard.js` | Piano-keyboard geometry for the song system's Synthesia-style piano-roll visualizer (`<PianoRoll>`). Pure math, no canvas/React. `keyboardRange(midis, { minSemitones })` → `{ lowMidi, highMidi }` padded out to whole C–B octaves (min 2) so the keyboard always starts on a C / ends on a B and never collapses for a one-note part; `buildKeyboardLayout({ lowMidi, highMidi, width })` → `{ keys:[{midi,isBlack,x,w}], whiteWidth, blackWidth }` (white keys tiled edge-to-edge, black keys overlaid centered on the boundary, narrower); plus `isBlackKey(midi)`, `midiNoteName(midi)` (sharps spelling), and the `BLACK_KEY_RATIO`/`BLACK_KEY_HEIGHT_RATIO` constants. Pairs with `scorePlayback`'s per-note `midi` field. |
| `scoreNotation.js` | Parser for the PortOS lead-sheet notation — a dependency-free text format for melody + chords + lyrics that the `<ScoreSheet>` SVG renderer draws (no abcjs / VexFlow / OSMD). `parseScore(text)` → `{ clef, key, keySig, time, tempo, measures, errors }`; plus `parsePitch`, `diatonicStep`, `durationBeats`, `keySignature`, `DURATIONS`, and `scoreHasMusic(text)`. Forgiving: bad tokens collect into `errors` and are skipped, never thrown. Pure — the renderer only does geometry. |
diff --git a/client/src/lib/editorialChecks.js b/client/src/lib/editorialChecks.js
new file mode 100644
index 0000000000..1103eb2827
--- /dev/null
+++ b/client/src/lib/editorialChecks.js
@@ -0,0 +1,103 @@
+// Pure helpers for the Editorial Checks page (#1285) — catalog grouping,
+// findings triage grouping, and manuscript deep-link building. No React, no
+// window: the page component and its unit tests both consume these.
+
+// Scope display order + labels (mirrors server CHECK_SCOPES). A check whose
+// scope isn't one of these still renders, bucketed under its raw scope last.
+export const CHECK_SCOPE_ORDER = Object.freeze(['noun', 'scene', 'issue', 'series']);
+export const CHECK_SCOPE_LABELS = Object.freeze({
+ noun: 'Noun',
+ scene: 'Scene',
+ issue: 'Issue',
+ series: 'Series',
+});
+
+export const scopeLabel = (scope) =>
+ CHECK_SCOPE_LABELS[scope] || (scope ? scope[0].toUpperCase() + scope.slice(1) : 'Other');
+
+const SEVERITY_ORDER = Object.freeze(['high', 'medium', 'low']);
+
+/**
+ * Group catalog rows into ordered scope sections for the catalog view.
+ * Returns `[{ scope, label, checks }]` in CHECK_SCOPE_ORDER, with any unknown
+ * scope appended after the known ones (alphabetical). Empty scopes are omitted.
+ */
+export function groupChecksByScope(checks = []) {
+ const byScope = new Map();
+ for (const check of checks) {
+ const scope = check?.scope || 'other';
+ if (!byScope.has(scope)) byScope.set(scope, []);
+ byScope.get(scope).push(check);
+ }
+ const known = CHECK_SCOPE_ORDER.filter((s) => byScope.has(s));
+ const unknown = [...byScope.keys()].filter((s) => !CHECK_SCOPE_ORDER.includes(s)).sort();
+ return [...known, ...unknown].map((scope) => ({
+ scope,
+ label: scopeLabel(scope),
+ checks: byScope.get(scope),
+ }));
+}
+
+const emptyCounts = () => ({ high: 0, medium: 0, low: 0 });
+
+/**
+ * Group review comments that came from an editorial check into per-check
+ * sections for the triage view. Only comments carrying a `checkId` are
+ * included (completeness findings have none). Returns
+ * `[{ checkId, label, scope, kind, comments, open, total, counts }]`
+ * ordered by the catalog's scope order then label, with `counts` tallying the
+ * OPEN comments by severity. `rowsById` is a Map/object of catalog rows so each
+ * group can show its human label even when the check is currently disabled.
+ */
+export function groupFindingsByCheck(comments = [], rowsById = {}) {
+ const lookup = rowsById instanceof Map ? rowsById : new Map(Object.entries(rowsById || {}));
+ const groups = new Map();
+ for (const c of comments) {
+ if (!c?.checkId) continue;
+ if (!groups.has(c.checkId)) {
+ const row = lookup.get(c.checkId) || null;
+ groups.set(c.checkId, {
+ checkId: c.checkId,
+ label: row?.label || c.checkId,
+ scope: row?.scope || 'other',
+ kind: row?.kind || null,
+ comments: [],
+ open: 0,
+ total: 0,
+ counts: emptyCounts(),
+ });
+ }
+ const g = groups.get(c.checkId);
+ g.comments.push(c);
+ g.total += 1;
+ if (c.status === 'open') {
+ g.open += 1;
+ const sev = SEVERITY_ORDER.includes(c.severity) ? c.severity : 'low';
+ g.counts[sev] += 1;
+ }
+ }
+ const scopeRank = (s) => {
+ const i = CHECK_SCOPE_ORDER.indexOf(s);
+ return i === -1 ? CHECK_SCOPE_ORDER.length : i;
+ };
+ return [...groups.values()].sort((a, b) =>
+ scopeRank(a.scope) - scopeRank(b.scope) || a.label.localeCompare(b.label));
+}
+
+/** Total OPEN check-sourced findings across all groups — drives the header badge. */
+export const openFindingsTotal = (groups = []) =>
+ groups.reduce((sum, g) => sum + g.open, 0);
+
+/**
+ * Deep-link a finding into the manuscript editor: focuses the finding's issue
+ * (when it has one) and opens its comment card via the `?comment=` param the
+ * editor honors. Series-scoped findings (no issueNumber) land on the bare
+ * manuscript route with the card opened from the review sidebar.
+ */
+export function findingManuscriptLink(seriesId, comment) {
+ const base = `/pipeline/series/${encodeURIComponent(seriesId)}/manuscript`;
+ const path = Number.isInteger(comment?.issueNumber)
+ ? `${base}/${comment.issueNumber}`
+ : base;
+ return comment?.id ? `${path}?comment=${encodeURIComponent(comment.id)}` : path;
+}
diff --git a/client/src/lib/editorialChecks.test.js b/client/src/lib/editorialChecks.test.js
new file mode 100644
index 0000000000..7bb2e48132
--- /dev/null
+++ b/client/src/lib/editorialChecks.test.js
@@ -0,0 +1,91 @@
+import { describe, it, expect } from 'vitest';
+import {
+ groupChecksByScope,
+ groupFindingsByCheck,
+ openFindingsTotal,
+ findingManuscriptLink,
+ scopeLabel,
+} from './editorialChecks.js';
+
+const checks = [
+ { id: 'a.series', label: 'Series check', scope: 'series', kind: 'deterministic' },
+ { id: 'b.issue', label: 'Issue check', scope: 'issue', kind: 'llm' },
+ { id: 'c.noun', label: 'Noun check', scope: 'noun', kind: 'deterministic' },
+ { id: 'd.weird', label: 'Weird scope', scope: 'galaxy', kind: 'deterministic' },
+];
+
+describe('groupChecksByScope', () => {
+ it('orders known scopes noun→scene→issue→series and appends unknown last', () => {
+ const groups = groupChecksByScope(checks);
+ expect(groups.map((g) => g.scope)).toEqual(['noun', 'issue', 'series', 'galaxy']);
+ expect(groups.map((g) => g.label)).toEqual(['Noun', 'Issue', 'Series', 'Galaxy']);
+ });
+
+ it('omits scopes with no checks and tolerates an empty list', () => {
+ expect(groupChecksByScope([{ id: 'x', scope: 'noun' }]).map((g) => g.scope)).toEqual(['noun']);
+ expect(groupChecksByScope()).toEqual([]);
+ });
+});
+
+describe('groupFindingsByCheck', () => {
+ const rows = {
+ 'a.series': { label: 'Series check', scope: 'series', kind: 'deterministic' },
+ 'b.issue': { label: 'Issue check', scope: 'issue', kind: 'llm' },
+ };
+ const comments = [
+ { id: '1', checkId: 'a.series', status: 'open', severity: 'high' },
+ { id: '2', checkId: 'a.series', status: 'open', severity: 'low' },
+ { id: '3', checkId: 'a.series', status: 'dismissed', severity: 'high' },
+ { id: '4', checkId: 'b.issue', status: 'open', severity: 'medium' },
+ { id: '5', status: 'open', severity: 'high' }, // completeness finding — no checkId, excluded
+ ];
+
+ it('groups only check-sourced comments and tallies open by severity', () => {
+ const groups = groupFindingsByCheck(comments, rows);
+ // issue scope sorts before series scope.
+ expect(groups.map((g) => g.checkId)).toEqual(['b.issue', 'a.series']);
+ const series = groups.find((g) => g.checkId === 'a.series');
+ expect(series.total).toBe(3);
+ expect(series.open).toBe(2);
+ expect(series.counts).toEqual({ high: 1, medium: 0, low: 1 });
+ });
+
+ it('falls back to the checkId as label when the check is unknown', () => {
+ const groups = groupFindingsByCheck([{ id: '9', checkId: 'gone.check', status: 'open', severity: 'low' }], {});
+ expect(groups[0].label).toBe('gone.check');
+ });
+
+ it('accepts a Map of rows as well as a plain object', () => {
+ const groups = groupFindingsByCheck(comments, new Map(Object.entries(rows)));
+ expect(groups.find((g) => g.checkId === 'b.issue').label).toBe('Issue check');
+ });
+
+ it('openFindingsTotal sums open findings across groups', () => {
+ expect(openFindingsTotal(groupFindingsByCheck(comments, rows))).toBe(3);
+ });
+});
+
+describe('findingManuscriptLink', () => {
+ it('targets the finding\'s issue and opens its comment when it has an issueNumber', () => {
+ expect(findingManuscriptLink('ser-1', { id: 'c9', issueNumber: 5 }))
+ .toBe('/pipeline/series/ser-1/manuscript/5?comment=c9');
+ });
+
+ it('lands on the bare manuscript route for series-scoped findings (no issueNumber)', () => {
+ expect(findingManuscriptLink('ser-1', { id: 'c9', issueNumber: null }))
+ .toBe('/pipeline/series/ser-1/manuscript?comment=c9');
+ });
+
+ it('omits the comment param when the finding has no id', () => {
+ expect(findingManuscriptLink('ser-1', { issueNumber: 2 }))
+ .toBe('/pipeline/series/ser-1/manuscript/2');
+ });
+});
+
+describe('scopeLabel', () => {
+ it('maps known scopes and title-cases unknown ones', () => {
+ expect(scopeLabel('series')).toBe('Series');
+ expect(scopeLabel('galaxy')).toBe('Galaxy');
+ expect(scopeLabel('')).toBe('Other');
+ });
+});
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index c70f783b89..3d9f08af2b 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -59,6 +59,7 @@ export * from './voiceLabel.js';
// === Page-scoped pure helpers ===
export * from './cityPlaybackFrame.js';
export * from './colorMatch.js';
+export * from './editorialChecks.js';
export * from './metronome.js';
export * from './pianoKeyboard.js';
export * from './pitchDetect.js';
diff --git a/client/src/pages/PipelineEditorialChecks.jsx b/client/src/pages/PipelineEditorialChecks.jsx
new file mode 100644
index 0000000000..2d22972615
--- /dev/null
+++ b/client/src/pages/PipelineEditorialChecks.jsx
@@ -0,0 +1,298 @@
+/**
+ * Editorial Checks (#1285) — the catalog / config / run / triage surface for the
+ * registry-driven editorial-review system (epic #1283, backbone #1284).
+ *
+ * The check CATALOG (enable + per-check config) is global (settings-backed), so
+ * it loads independent of any series. RUNS and FINDINGS are per-series: pick a
+ * series, run the enabled checks (or a selected subset) with SSE progress, then
+ * triage the findings — which are seeded into the manuscript review store and
+ * deep-link into the manuscript editor's existing Accept/Dismiss/fix flow.
+ *
+ * Deep-linkable at /pipeline/editorial-checks (optionally ?series=<id> to
+ * preselect a series, e.g. from a series page).
+ */
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { Link, useSearchParams } from 'react-router-dom';
+import { ArrowLeft, ListChecks, Loader2, Play, Square } from 'lucide-react';
+import toast from '../components/ui/Toast';
+import EditorialCheckCard from '../components/pipeline/editorial/EditorialCheckCard';
+import EditorialFindingsTriage from '../components/pipeline/editorial/EditorialFindingsTriage';
+import { groupChecksByScope } from '../lib/editorialChecks';
+import { usePipelineProgress } from '../hooks/usePipelineProgress';
+import {
+ listPipelineSeries,
+ getEditorialChecks,
+ patchEditorialCheck,
+ startEditorialChecksRun,
+ cancelEditorialChecksRun,
+ getEditorialChecksRunStatus,
+ editorialChecksRunSseUrl,
+ getPipelineManuscriptReview,
+} from '../services/api';
+
+export default function PipelineEditorialChecks() {
+ const [searchParams, setSearchParams] = useSearchParams();
+ const [checks, setChecks] = useState([]);
+ const [loadingCatalog, setLoadingCatalog] = useState(true);
+ const [savingIds, setSavingIds] = useState(() => new Set());
+ const [selectedIds, setSelectedIds] = useState(() => new Set());
+
+ const [series, setSeries] = useState([]);
+ const seriesId = searchParams.get('series') || '';
+ const [comments, setComments] = useState([]);
+ const [loadingFindings, setLoadingFindings] = useState(false);
+
+ const [runActive, setRunActive] = useState(false);
+ const [runStarting, setRunStarting] = useState(false);
+ const [runStage, setRunStage] = useState('');
+
+ const checksById = useMemo(
+ () => Object.fromEntries(checks.map((c) => [c.id, c])),
+ [checks],
+ );
+ const enabledCount = useMemo(() => checks.filter((c) => c.enabled).length, [checks]);
+ // Config saves read server settings, so a run that fires before a save lands
+ // would use stale config — gate the run buttons while any save is in flight.
+ const anySaving = savingIds.size > 0;
+
+ // ---- Load the global catalog + series list once. ----
+ useEffect(() => {
+ let canceled = false;
+ Promise.all([
+ getEditorialChecks().catch(() => ({ checks: [] })),
+ listPipelineSeries().catch(() => []),
+ ]).then(([catalog, list]) => {
+ if (canceled) return;
+ setChecks(Array.isArray(catalog?.checks) ? catalog.checks : []);
+ setSeries(Array.isArray(list) ? list : []);
+ setLoadingCatalog(false);
+ });
+ return () => { canceled = true; };
+ }, []);
+
+ // ---- Load findings + re-attach to an in-flight run when the series changes. ----
+ const loadFindings = useCallback((id) => {
+ if (!id) { setComments([]); return; }
+ setLoadingFindings(true);
+ getPipelineManuscriptReview(id)
+ .then((review) => setComments(Array.isArray(review?.comments) ? review.comments : []))
+ .catch((err) => toast.error(err.message || 'Failed to load findings'))
+ .finally(() => setLoadingFindings(false));
+ }, []);
+
+ useEffect(() => {
+ setRunActive(false);
+ if (!seriesId) { setComments([]); return; }
+ loadFindings(seriesId);
+ let canceled = false;
+ getEditorialChecksRunStatus(seriesId, { silent: true })
+ .then((s) => { if (!canceled && s?.active) setRunActive(true); })
+ .catch(() => {});
+ return () => { canceled = true; };
+ }, [seriesId, loadFindings]);
+
+ // ---- SSE progress for the active run (mirrors the manuscript editor). ----
+ const { latest: runLatest, closed: runClosed } = usePipelineProgress(
+ editorialChecksRunSseUrl, [seriesId], { enabled: runActive && !!seriesId },
+ );
+
+ // Per-check progress frames only drive the status label.
+ useEffect(() => {
+ if (!runActive || !runLatest) return;
+ if (runLatest.type === 'check:start' && runLatest.label) setRunStage(`Running: ${runLatest.label}`);
+ }, [runActive, runLatest]);
+
+ // Terminal frame: refresh findings + tear down. Gate on `runClosed` so a stale
+ // terminal frame from a prior run can't kill a freshly-started one.
+ useEffect(() => {
+ if (!runActive || !runClosed || !runLatest) return;
+ const type = runLatest.type;
+ if (type !== 'complete' && type !== 'canceled' && type !== 'error') return;
+ setRunActive(false);
+ setRunStage('');
+ if (type === 'complete') { loadFindings(seriesId); toast.success('Editorial checks complete'); }
+ else if (type === 'canceled') toast.success('Editorial checks canceled');
+ else toast.error(runLatest.error || 'Editorial checks failed');
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [runActive, runClosed, runLatest, seriesId]);
+
+ // Recovery: the stream died WITHOUT a terminal frame — don't strand the UI;
+ // drop the active flag and re-fetch (the runner may have seeded server-side).
+ useEffect(() => {
+ if (!runActive || !runClosed) return;
+ const t = runLatest?.type;
+ if (t === 'complete' || t === 'canceled' || t === 'error') return; // handled above
+ setRunActive(false);
+ setRunStage('');
+ loadFindings(seriesId);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [runActive, runClosed, runLatest, seriesId]);
+
+ // ---- Catalog mutations (reactive local updates; the API owns the toast). ----
+ const handleToggle = (checkId, nextEnabled) => {
+ const prev = checks;
+ setChecks((rows) => rows.map((r) => (r.id === checkId ? { ...r, enabled: nextEnabled } : r)));
+ patchEditorialCheck(checkId, { enabled: nextEnabled }, { silent: true })
+ .then((row) => { if (row) setChecks((rows) => rows.map((r) => (r.id === checkId ? row : r))); })
+ .catch((err) => { setChecks(prev); toast.error(err.message || 'Failed to update check'); });
+ };
+
+ const handleConfigSave = (checkId, nextConfig) => {
+ setSavingIds((s) => new Set(s).add(checkId));
+ patchEditorialCheck(checkId, { config: nextConfig }, { silent: true })
+ .then((row) => { if (row) setChecks((rows) => rows.map((r) => (r.id === checkId ? row : r))); })
+ .catch((err) => toast.error(err.message || 'Failed to save config'))
+ .finally(() => setSavingIds((s) => { const n = new Set(s); n.delete(checkId); return n; }));
+ };
+
+ const toggleSelected = (checkId) => setSelectedIds((s) => {
+ const n = new Set(s);
+ if (n.has(checkId)) n.delete(checkId); else n.add(checkId);
+ return n;
+ });
+
+ // ---- Run / cancel. ----
+ const runChecks = (subsetIds = null) => {
+ if (!seriesId) { toast.error('Pick a series to run checks against'); return; }
+ setRunStarting(true);
+ startEditorialChecksRun(seriesId, subsetIds ? { checkIds: subsetIds } : {}, { silent: true })
+ .then((res) => {
+ if (res?.alreadyRunning) toast('A run is already in progress for this series');
+ setRunActive(true);
+ })
+ .catch((err) => toast.error(err.message || 'Failed to start checks'))
+ .finally(() => setRunStarting(false));
+ };
+
+ const cancelRun = () => {
+ cancelEditorialChecksRun(seriesId, { silent: true })
+ .catch((err) => toast.error(err.message || 'Failed to cancel'));
+ };
+
+ const onSeriesChange = (id) => {
+ const next = new URLSearchParams(searchParams);
+ if (id) next.set('series', id); else next.delete('series');
+ setSearchParams(next, { replace: true });
+ };
+
+ const scopeGroups = groupChecksByScope(checks);
+ const runDisabled = !seriesId || runActive || runStarting || anySaving;
+
+ return (
+ <div className="mx-auto max-w-6xl space-y-4">
+ {/* Header */}
+ <div className="space-y-2">
+ <Link to="/pipeline" className="inline-flex items-center gap-1 text-xs text-gray-400 hover:text-gray-200">
+ <ArrowLeft size={13} /> Series Pipeline
+ </Link>
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <h1 className="flex items-center gap-2 text-xl font-semibold text-gray-100">
+ <ListChecks size={20} className="text-port-accent" /> Editorial Checks
+ </h1>
+ <div className="flex flex-wrap items-center gap-2">
+ <label htmlFor="ec-series" className="sr-only">Series</label>
+ <select
+ id="ec-series"
+ value={seriesId}
+ onChange={(e) => onSeriesChange(e.target.value)}
+ className="rounded border border-port-border bg-port-card px-2 py-1.5 text-sm text-gray-100 focus:border-port-accent focus:outline-none"
+ >
+ <option value="">Select a series…</option>
+ {series.map((s) => (
+ <option key={s.id} value={s.id}>{s.title || s.name || s.id}</option>
+ ))}
+ </select>
+ {runActive ? (
+ <button
+ type="button"
+ onClick={cancelRun}
+ className="inline-flex items-center gap-1.5 rounded bg-port-error/20 px-3 py-1.5 text-sm text-rose-300 hover:bg-port-error/30"
+ >
+ <Square size={14} /> Cancel
+ </button>
+ ) : (
+ <button
+ type="button"
+ onClick={() => runChecks(null)}
+ disabled={runDisabled || enabledCount === 0}
+ title={enabledCount === 0 ? 'No checks enabled' : undefined}
+ className="inline-flex items-center gap-1.5 rounded bg-port-accent px-3 py-1.5 text-sm text-white hover:bg-port-accent/90 disabled:cursor-not-allowed disabled:opacity-50"
+ >
+ {runStarting ? <Loader2 size={14} className="animate-spin" /> : <Play size={14} />}
+ Run all enabled ({enabledCount})
+ </button>
+ )}
+ {!runActive && selectedIds.size > 0 ? (
+ <button
+ type="button"
+ onClick={() => runChecks([...selectedIds])}
+ disabled={runDisabled}
+ className="inline-flex items-center gap-1.5 rounded border border-port-accent px-3 py-1.5 text-sm text-port-accent hover:bg-port-accent/10 disabled:cursor-not-allowed disabled:opacity-50"
+ >
+ <Play size={14} /> Run selected ({selectedIds.size})
+ </button>
+ ) : null}
+ </div>
+ </div>
+ {runActive ? (
+ <p className="flex items-center gap-2 text-xs text-port-accent">
+ <Loader2 size={13} className="animate-spin" /> {runStage || 'Running editorial checks…'}
+ </p>
+ ) : null}
+ {!seriesId ? (
+ <p className="text-xs text-gray-500">Pick a series to run checks and triage findings. The catalog below applies to every series.</p>
+ ) : null}
+ </div>
+
+ {loadingCatalog ? (
+ <p className="flex items-center gap-2 text-sm text-gray-400"><Loader2 size={16} className="animate-spin" /> Loading checks…</p>
+ ) : (
+ <div className="grid gap-6 lg:grid-cols-2">
+ {/* Catalog */}
+ <section className="space-y-3">
+ <h2 className="text-sm font-semibold uppercase tracking-wide text-gray-400">Catalog</h2>
+ {checks.length === 0 ? (
+ <p className="rounded-lg border border-dashed border-port-border p-4 text-center text-xs text-gray-500">No editorial checks are registered.</p>
+ ) : scopeGroups.map((group) => (
+ <div key={group.scope} className="space-y-2">
+ <h3 className="text-[11px] font-medium uppercase tracking-wider text-gray-500">{group.label}</h3>
+ {group.checks.map((check) => (
+ <div key={check.id} className="flex items-start gap-2">
+ <input
+ type="checkbox"
+ id={`sel-${check.id}`}
+ checked={selectedIds.has(check.id)}
+ onChange={() => toggleSelected(check.id)}
+ aria-label={`Select ${check.label} for a targeted run`}
+ className="mt-3.5 shrink-0 accent-port-accent"
+ />
+ <div className="min-w-0 flex-1">
+ <EditorialCheckCard
+ check={check}
+ saving={savingIds.has(check.id)}
+ onToggle={handleToggle}
+ onConfigSave={handleConfigSave}
+ />
+ </div>
+ </div>
+ ))}
+ </div>
+ ))}
+ </section>
+
+ {/* Findings */}
+ <section className="space-y-3">
+ <h2 className="text-sm font-semibold uppercase tracking-wide text-gray-400">Findings</h2>
+ {!seriesId ? (
+ <p className="rounded-lg border border-dashed border-port-border p-4 text-center text-xs text-gray-500">Select a series to view its findings.</p>
+ ) : loadingFindings ? (
+ <p className="flex items-center gap-2 text-sm text-gray-400"><Loader2 size={16} className="animate-spin" /> Loading findings…</p>
+ ) : (
+ <EditorialFindingsTriage seriesId={seriesId} comments={comments} checksById={checksById} />
+ )}
+ </section>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/pages/PipelineManuscriptEditor.jsx b/client/src/pages/PipelineManuscriptEditor.jsx
index 5b7ab853d3..34ed069617 100644
--- a/client/src/pages/PipelineManuscriptEditor.jsx
+++ b/client/src/pages/PipelineManuscriptEditor.jsx
@@ -28,7 +28,7 @@
*/
import { useEffect, useMemo, useRef, useState } from 'react';
-import { Link, useParams, useNavigate } from 'react-router-dom';
+import { Link, useParams, useNavigate, useSearchParams } from 'react-router-dom';
import {
ArrowLeft, Loader2, Sparkles, FileText, Star, ClipboardCheck, Layers, PencilLine, BookOpen, GitCompare, X,
} from 'lucide-react';
@@ -67,6 +67,7 @@ export default function PipelineManuscriptEditor() {
const params = useParams();
const { seriesId } = params;
const navigate = useNavigate();
+ const [searchParams, setSearchParams] = useSearchParams();
// The issue (by number) the editor is focused on — one issue per view,
// deep-linkable at /pipeline/series/:id/manuscript/:issueNumber. Read from the
// route splat (a single splat route, not two :param routes, so issue→issue
@@ -168,6 +169,24 @@ export default function PipelineManuscriptEditor() {
return () => { canceled = true; };
}, []);
+ // Deep-link from the Editorial Checks triage view: `?comment=<id>` opens that
+ // finding's card. Wait until comments have loaded, match the id, reveal it in
+ // review mode (where the card renders inline), then strip the param so a
+ // refresh/back doesn't re-trigger it. No-op when the comment isn't present
+ // (e.g. it was already dismissed-and-pruned, or belongs to another series).
+ useEffect(() => {
+ const wanted = searchParams.get('comment');
+ if (!wanted || loading) return;
+ if (comments.some((c) => c.id === wanted)) {
+ setViewMode('review');
+ setOpenCommentId(wanted);
+ }
+ const next = new URLSearchParams(searchParams);
+ next.delete('comment');
+ setSearchParams(next, { replace: true });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [loading, comments, searchParams]);
+
const overrideProvider = providers.find((p) => p.id === overrideProviderId) || null;
const localModels = useLocalModels();
const overrideBackend = localBackendForProvider(overrideProvider);
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index 4be72ecb20..2c41095d5e 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -595,6 +595,47 @@ export const getSeriesEditorialStatus = (seriesId, options = {}) =>
export const pipelineEditorialSseUrl = (seriesId) =>
`/api/pipeline/series/${encodeURIComponent(seriesId)}/editorial/analyze/progress`;
+// ---- Editorial checks (#1284 registry-driven review) ----
+// The full check catalog merged with persisted enable/config state:
+// { checks: [{ id, label, description, scope, kind, category, severityDefault,
+// enabled, config, configFields }] }. The catalog is GLOBAL (settings-
+// backed); only the run + findings are series-scoped.
+export const getEditorialChecks = (options = {}) =>
+ request('/pipeline/editorial/checks', options);
+
+// Enable/disable a check or update its config. `patch` is { enabled?, config? };
+// `config` is validated against the check's own schema server-side. Returns the
+// updated resolved-state row. Pass { silent: true } when you own the error UI.
+export const patchEditorialCheck = (checkId, patch, options = {}) =>
+ request(`/pipeline/editorial/checks/${encodeURIComponent(checkId)}`, {
+ method: 'PATCH',
+ body: JSON.stringify(patch),
+ ...options,
+ });
+
+// Start a series-wide checks run (or a named subset). { runId, alreadyRunning,
+// sseUrl } — subscribe via editorialChecksRunSseUrl, then re-fetch the manuscript
+// review on `complete` (the runner seeds findings into the review store).
+export const startEditorialChecksRun = (seriesId, opts = {}, options = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/editorial/checks/run`, {
+ method: 'POST',
+ body: JSON.stringify(opts),
+ ...options,
+ });
+
+// { active: boolean } — lets a (re)mounting view re-attach to an in-flight run.
+export const getEditorialChecksRunStatus = (seriesId, options = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/editorial/checks/run/status`, options);
+
+export const cancelEditorialChecksRun = (seriesId, options = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/editorial/checks/run/cancel`, {
+ method: 'POST',
+ ...options,
+ });
+
+export const editorialChecksRunSseUrl = (seriesId) =>
+ `/api/pipeline/series/${encodeURIComponent(seriesId)}/editorial/checks/run/progress`;
+
// ---- Series Autopilot (full autonomous mode) ----
// Drives a series from its current state to story-ready (+ draft visuals) by
// composing every pipeline pass. SSE-backed; gated on the cos autonomy domain
diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.js
index 4321840272..b87d905b97 100644
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@ -27,6 +27,12 @@ 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']);
+// The serializable config-field types a check can declare for its UI form.
+// `configSchema` (a Zod schema) stays the validation authority on the server;
+// `configFields` is the wire-safe *render* descriptor the Editorial Checks UI
+// reads to build the per-check config form (the Zod schema can't cross the wire).
+export const CHECK_FIELD_TYPES = Object.freeze(['number', 'boolean', 'text', 'select']);
+
// 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 +
@@ -75,6 +81,17 @@ export const EDITORIAL_CHECKS = [
// How many similarity signals two names must share before they're flagged.
minSharedSignals: z.number().int().min(1).max(5).default(2),
}),
+ configFields: [
+ {
+ key: 'minSharedSignals',
+ label: 'Minimum shared signals to flag',
+ type: 'number',
+ min: 1,
+ max: 5,
+ step: 1,
+ help: 'How many similarity signals (first letter, length, vowel pattern, opening, ending) two names must share before they are flagged.',
+ },
+ ],
run: (ctx) => {
const min = ctx.config?.minSharedSignals ?? 2;
const names = (ctx.canon?.characters || [])
@@ -122,6 +139,26 @@ export const EDITORIAL_CHECKS = [
// context-window chunking (à la completenessPass) is tracked separately.
maxManuscriptChars: z.number().int().min(2000).max(200_000).default(48_000),
}),
+ 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.',
+ },
+ {
+ key: 'maxManuscriptChars',
+ label: 'Max manuscript characters analyzed',
+ type: 'number',
+ min: 2000,
+ max: 200_000,
+ step: 1000,
+ help: 'Bounds the prompt so a long series can not overflow a small provider context window.',
+ },
+ ],
gate: (ctx) => (ctx.manuscript || '').trim().length > 0,
run: async (ctx) => {
const cap = ctx.config?.maxManuscriptChars ?? 48_000;
@@ -177,6 +214,20 @@ export function assertValidChecks(checks) {
if (!check.configSchema || typeof check.configSchema.safeParse !== 'function') {
throw new Error(`checkRegistry: ${check.id} is missing a Zod configSchema`);
}
+ // configFields is optional, but when present each entry must be a renderable
+ // descriptor (key + label + known type) so the UI never has to guess a
+ // field's control. The Zod configSchema remains the validation authority —
+ // configFields only drives the form, so we don't cross-check key coverage.
+ if (check.configFields !== undefined) {
+ if (!Array.isArray(check.configFields)) {
+ throw new Error(`checkRegistry: ${check.id} configFields must be an array`);
+ }
+ for (const field of check.configFields) {
+ if (!field || !field.key || !field.label || !CHECK_FIELD_TYPES.includes(field.type)) {
+ throw new Error(`checkRegistry: ${check.id} has a malformed configField ${JSON.stringify(field)} (need key, label, type ∈ ${CHECK_FIELD_TYPES.join('/')})`);
+ }
+ }
+ }
if (seen.has(check.id)) throw new Error(`checkRegistry: duplicate id ${check.id}`);
seen.add(check.id);
}
@@ -214,9 +265,11 @@ export const readChecksSlice = (settings) => {
* 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, config, configFields }
* `enabled` falls back to the check's `defaultEnabled`; `config` is validated
- * through the check's schema (with defaults).
+ * through the check's schema (with defaults); `configFields` is the wire-safe
+ * render descriptor the UI builds its config form from (empty array when the
+ * check declares none).
*/
export function resolveCheckState(settings) {
const stored = readChecksSlice(settings);
@@ -233,6 +286,7 @@ export function resolveCheckState(settings) {
severityDefault: check.severityDefault,
enabled,
config: resolveCheckConfig(check, row.config),
+ configFields: Array.isArray(check.configFields) ? check.configFields : [],
};
});
}
diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.js
index 4369fdbafd..ed3560f8e6 100644
--- a/server/lib/editorial/checkRegistry.test.js
+++ b/server/lib/editorial/checkRegistry.test.js
@@ -78,6 +78,19 @@ describe('editorial check registry — fail-fast guards', () => {
it('throws on a duplicate id', () => {
expect(() => assertValidChecks([valid, { ...valid }])).toThrow(/duplicate id/);
});
+
+ it('accepts a check with no configFields (optional)', () => {
+ expect(() => assertValidChecks([{ ...valid, configFields: undefined }])).not.toThrow();
+ });
+
+ it('throws when configFields is not an array', () => {
+ expect(() => assertValidChecks([{ ...valid, configFields: {} }])).toThrow(/configFields must be an array/);
+ });
+
+ it('throws on a malformed configField (missing key/label or bad type)', () => {
+ expect(() => assertValidChecks([{ ...valid, configFields: [{ label: 'x', type: 'number' }] }])).toThrow(/malformed configField/);
+ expect(() => assertValidChecks([{ ...valid, configFields: [{ key: 'k', label: 'x', type: 'galaxy' }] }])).toThrow(/malformed configField/);
+ });
});
describe('editorial check registry — config + state resolution', () => {
@@ -102,6 +115,23 @@ describe('editorial check registry — config + state resolution', () => {
expect(rows.find((r) => r.id === INFODUMP).enabled).toBe(true);
});
+ it('resolveCheckState surfaces each check\'s serializable configFields', () => {
+ const rows = resolveCheckState({});
+ const naming = rows.find((r) => r.id === NAMING);
+ expect(Array.isArray(naming.configFields)).toBe(true);
+ const field = naming.configFields.find((f) => f.key === 'minSharedSignals');
+ expect(field).toMatchObject({ type: 'number', min: 1, max: 5 });
+ expect(field.label).toBeTruthy();
+ // Every declared config field is renderable (key + label + known type).
+ for (const row of rows) {
+ for (const f of row.configFields) {
+ expect(f.key, `${row.id} field key`).toBeTruthy();
+ expect(f.label, `${row.id} field label`).toBeTruthy();
+ expect(['number', 'boolean', 'text', 'select'], `${row.id} field type`).toContain(f.type);
+ }
+ }
+ });
+
it('getEnabledChecks honors disable + subset narrowing', () => {
const settings = { pipelineEditorialChecks: { checks: { [INFODUMP]: { enabled: false } } } };
const enabled = getEnabledChecks(settings).map((x) => x.check.id);
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index dba3bf3940..0670f42c13 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -25,6 +25,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.create.universe-builder', path: '/universes', label: 'Universes', section: 'Create', aliases: ['universes', 'universe', 'universe-builder', 'worldbuilder', 'worldbuild', 'world', 'lore', 'universe-canon', 'canon'], keywords: ['style template', 'sci-fi', 'fantasy', 'concept art', 'batch render', 'variations', 'characters', 'settings', 'objects', 'canon entries', 'list', 'manage'] },
{ id: 'nav.create.importer', path: '/importer', label: 'Importer', section: 'Create', aliases: ['importer', 'import'], keywords: ['paste', 'screenplay', 'novel', 'short story', 'comic script', 'analyze', 'reverse-engineer', 'extract'] },
{ id: 'nav.create.pipeline', path: '/pipeline', label: 'Series Pipeline', section: 'Create', aliases: ['series', 'pipeline', 'production', 'series-pipeline', 'production-pipeline'], keywords: ['series', 'issue', 'episode', 'comic', 'script', 'prose', 'storyboard', 'narrative', 'workflow'] },
+ { id: 'nav.create.pipeline.editorial-checks', path: '/pipeline/editorial-checks', label: 'Editorial Checks', section: 'Create', aliases: ['editorial-checks', 'editorial', 'checks', 'editorial-review', 'content-checks', 'manuscript-checks'], keywords: ['editorial', 'check', 'review', 'naming', 'exposition', 'info-dumping', 'continuity', 'quality', 'lint', 'triage', 'findings', 'deterministic', 'llm'] },
{ id: 'nav.create.sharing', path: '/sharing', label: 'Sharing', section: 'Create', aliases: ['sharing', 'share', 'buckets', 'share-buckets'], keywords: ['google drive', 'dropbox', 'icloud', 'syncthing', 'export', 'import', 'collaborate', 'federation', 'peer', 'cross-network'] },
{ id: 'nav.create.sharing-duplicates', path: '/sharing/duplicates', label: 'Duplicates', section: 'Create', aliases: ['duplicates', 'duplicate-universes', 'duplicate-series', 'dedupe', 'merge-duplicates'], keywords: ['duplicate', 'merge', 'rename', 'same name', 'two copies', 'reconcile', 'collision'] },
{ id: 'nav.create.story-builder', path: '/story-builder', label: 'Story Builder', section: 'Create', aliases: ['story-builder', 'storybuilder', 'guided', 'new-story', 'story-wizard'], keywords: ['idea', 'universe', 'arc', 'reader map', 'guided', 'wizard', 'linear', 'lock', 'front door', 'episode', 'series'] },