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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: author custom editorial LLM checks from the UI (#1346)
Adam Eivybe0d89bd3bb9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 88e2bf03b7..aca435c0c4 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **[issue-1346] Author your own editorial checks from the UI — name + prompt + scope, no code.** The Editorial Checks page (Create → Editorial Checks) gains a **New custom check** button: give it a name, describe in plain language *what to look for* in the manuscript, pick a scope/category/default severity, and save — PortOS turns it into a real LLM editorial check with no code change. You only write the *what*; the manuscript and the required findings-JSON output format are appended automatically, and the response is parsed by the same machinery the built-in checks use. Custom checks behave exactly like built-ins everywhere downstream: they appear in the catalog (with a **custom** badge + edit/delete), enable/disable and configure through the same toggle/config controls, run on demand or as part of Series Autopilot's editorial pass, chunk a long manuscript to the provider's context window, and seed findings into the manuscript review for the existing jump-to / AI-fix / accept-dismiss flow. Definitions live in your settings (`pipelineEditorialChecks.customChecks`); the authoring form is deep-linkable (`?custom=new` / `?custom=<id>`). New endpoints: `POST/PATCH/DELETE /api/pipeline/editorial/custom-checks`. (`server/lib/editorial/checkRegistry.js`, `server/lib/stageRunner.js`, `server/services/pipeline/editorial/checkRunner.js`, `server/routes/pipeline/editorial.js`, `server/lib/validation.js`, `client/src/components/pipeline/editorial/EditorialCustomCheckForm.jsx`, `client/src/components/pipeline/editorial/EditorialCheckCard.jsx`, `client/src/pages/PipelineEditorialChecks.jsx`, `client/src/services/apiPipeline.js`) (#1346)+- **[issue-1321] Override a LoRA run's base-model precision and memory mode per run.** A training run can now opt into a heavier or lighter frozen base than the one PortOS picks from your free memory, without editing any code: start a run with a **`baseQuant`** (16 = full bf16, or 8 / 4-bit QLoRA) and/or a **`lowRam`** toggle, and that run uses exactly those settings on the mflux engine. Leaving them unset keeps the existing automatic, memory-derived tier, so nothing changes for runs that don't ask. As a safety backstop, a per-run request still can't exceed an install's `LORA_TRAIN_MAX_QUANT_BITS` cap — the guard that keeps M5-class machines off the bf16 path that GPU-watchdog-panics them. (#1321)- **[issue-1330] Phase-aware stall watchdog catches a wedged GPU mid-training and auto-resumes from the newest checkpoint.** The training job queue's idle watchdog only trips on *total* silence (no runner output for 30 minutes) — but a *soft* GPU hang during mflux/FLUX.2 training is invisible to it, because the trainer's heartbeat and telemetry threads keep emitting lines while the step loop is wedged, perpetually resetting the flat timer. PortOS now runs a **phase-aware** stall detector that keys off the trainer's `STAGE:`/`STEP:` line protocol: once steps are flowing it derives a per-step budget from the *observed* step rate (a few × the slowest recent interval, floored and capped below the flat watchdog) and enforces it **only during `STAGE:training`** — model-load, dataset-encode, mid-training sampling, and inter-segment cooldown stay on the generous flat watchdog so a legitimately slow phase is never false-killed. When training genuinely stalls, the wedged child is **SIGKILLed immediately** (SIGTERM relies on the GIL the hang holds) and the run **auto-resumes from its newest checkpoint** via the existing resume path — bounded to a couple of attempts per run so a config that wedges every segment can't resume-loop forever, after which the run stays failed for manual resume. This recovers *soft* hangs faster; it does **not** address the hard-reboot kernel panics (checkpoint-resume already covers those, since the machine is gone before any userspace watchdog runs). Off-switch: `settings.loraTraining.stallWatchdog = false`. (`server/services/loraTraining/stallDetector.js`, `server/services/loraTraining/index.js`, `server/lib/validation.js`) (#1330)diff --git a/client/src/components/pipeline/editorial/EditorialCheckCard.jsx b/client/src/components/pipeline/editorial/EditorialCheckCard.jsxindex 18c58c20e2..7b67a3bac2 100644--- a/client/src/components/pipeline/editorial/EditorialCheckCard.jsx+++ b/client/src/components/pipeline/editorial/EditorialCheckCard.jsx@@ -10,7 +10,7 @@* down through `check.config`.*/import { memo, useEffect, useState } from 'react';-import { ChevronDown, ChevronRight, Loader2, Sliders } from 'lucide-react';+import { ChevronDown, ChevronRight, Loader2, Pencil, Sliders, Trash2 } from 'lucide-react';import ToggleSwitch from '../../ToggleSwitch';const KIND_BADGE = {@@ -77,9 +77,11 @@ function ConfigField({ checkId, field, value, disabled, onCommit }) {);}-function EditorialCheckCard({ check, saving = false, onToggle, onConfigSave }) {+function EditorialCheckCard({ check, saving = false, onToggle, onConfigSave, onEdit, onDelete }) {const [expanded, setExpanded] = useState(false);+ const [confirmDelete, setConfirmDelete] = useState(false);const hasConfig = Array.isArray(check.configFields) && check.configFields.length > 0;+ const isCustom = !!check.isCustom;return (<div className="rounded-lg border border-port-border bg-port-card p-3 space-y-2">@@ -93,6 +95,11 @@ function EditorialCheckCard({ check, saving = false, onToggle, onConfigSave }) {<span className={`text-[10px] px-1.5 py-0.5 rounded ${SEVERITY_BADGE[check.severityDefault] || SEVERITY_BADGE.low}`}>{check.severityDefault}</span>+ {isCustom ? (+ <span className="text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded border border-emerald-500/30 bg-emerald-500/15 text-emerald-300">+ custom+ </span>+ ) : null}</div><p className="text-xs text-gray-400">{check.description}</p></div>@@ -135,6 +142,54 @@ function EditorialCheckCard({ check, saving = false, onToggle, onConfigSave }) {) : null}</div>) : null}++ {isCustom && (onEdit || onDelete) ? (+ <div className="flex items-center justify-end gap-2 border-t border-port-border/60 pt-2">+ {confirmDelete ? (+ <>+ <span className="mr-auto text-[11px] text-gray-400">Delete this check?</span>+ <button+ type="button"+ onClick={() => { setConfirmDelete(false); onDelete?.(check.id); }}+ disabled={saving}+ className="inline-flex items-center gap-1 rounded bg-port-error/20 px-2 py-1 text-[11px] text-rose-300 hover:bg-port-error/30 disabled:opacity-50"+ >+ <Trash2 size={12} /> Delete+ </button>+ <button+ type="button"+ onClick={() => setConfirmDelete(false)}+ className="rounded border border-port-border px-2 py-1 text-[11px] text-gray-300 hover:bg-port-border/40"+ >+ Cancel+ </button>+ </>+ ) : (+ <>+ {onEdit ? (+ <button+ type="button"+ onClick={() => onEdit(check.id)}+ disabled={saving}+ className="inline-flex items-center gap-1 text-[11px] text-gray-400 hover:text-gray-200 disabled:opacity-50"+ >+ <Pencil size={12} /> Edit+ </button>+ ) : null}+ {onDelete ? (+ <button+ type="button"+ onClick={() => setConfirmDelete(true)}+ disabled={saving}+ className="inline-flex items-center gap-1 text-[11px] text-rose-400 hover:text-rose-300 disabled:opacity-50"+ >+ <Trash2 size={12} /> Delete+ </button>+ ) : null}+ </>+ )}+ </div>+ ) : null}</div>);}diff --git a/client/src/components/pipeline/editorial/EditorialCustomCheckForm.jsx b/client/src/components/pipeline/editorial/EditorialCustomCheckForm.jsxnew file mode 100644index 0000000000..5ef3961c6d--- /dev/null+++ b/client/src/components/pipeline/editorial/EditorialCustomCheckForm.jsx@@ -0,0 +1,152 @@+/**+ * Author / edit a user-defined editorial check (#1346): name + prompt + scope ++ * category + severity, no code change. Presentational — persistence is lifted to+ * PipelineEditorialChecks (onSave returns a Promise; the form shows a spinner and+ * stays open until it resolves). The user only describes WHAT to look for; the+ * JSON output contract is enforced server-side, so there's no contract field.+ */+import { useState } from 'react';+import { Loader2, Save, X } from 'lucide-react';+import { CHECK_SCOPE_ORDER, scopeLabel } from '../../../lib/editorialChecks';++// Scopes mirror the server registry's CHECK_SCOPES (via the client scope-order+// catalog); severities have no client mirror so they live here.+const SCOPES = CHECK_SCOPE_ORDER;+const SEVERITIES = ['high', 'medium', 'low'];++const blankDraft = {+ label: '',+ description: '',+ prompt: '',+ scope: 'issue',+ category: 'custom',+ severityDefault: 'medium',+};++// Pull only the editable fields off an existing resolved check row so editing a+// custom check prefills without dragging along id/config/enabled.+const draftFromCheck = (check) => ({+ label: check?.label ?? '',+ description: check?.description ?? '',+ prompt: check?.prompt ?? '',+ scope: SCOPES.includes(check?.scope) ? check.scope : 'issue',+ category: check?.category || 'custom',+ severityDefault: SEVERITIES.includes(check?.severityDefault) ? check.severityDefault : 'medium',+});++export default function EditorialCustomCheckForm({ check = null, saving = false, onSave, onCancel }) {+ const isEdit = !!check;+ const [draft, setDraft] = useState(() => (isEdit ? draftFromCheck(check) : { ...blankDraft }));+ const set = (key, value) => setDraft((d) => ({ ...d, [key]: value }));++ const canSave = draft.label.trim().length > 0 && draft.prompt.trim().length > 0 && !saving;++ const submit = (e) => {+ e.preventDefault();+ if (!canSave) return;+ onSave({+ label: draft.label.trim(),+ description: draft.description.trim(),+ prompt: draft.prompt.trim(),+ scope: draft.scope,+ category: draft.category.trim() || 'custom',+ severityDefault: draft.severityDefault,+ });+ };++ const fieldClass = 'w-full rounded border border-port-border bg-port-bg px-2 py-1.5 text-sm text-gray-100 focus:border-port-accent focus:outline-none';++ return (+ <form onSubmit={submit} className="space-y-3 rounded-lg border border-port-accent/40 bg-port-card p-3">+ <h3 className="text-sm font-semibold text-gray-100">+ {isEdit ? 'Edit custom check' : 'New custom check'}+ </h3>++ <div className="flex flex-col gap-1">+ <label htmlFor="cc-label" className="text-xs text-gray-300">Name</label>+ <input+ id="cc-label"+ type="text"+ value={draft.label}+ maxLength={120}+ onChange={(e) => set('label', e.target.value)}+ placeholder="e.g. Anachronistic technology"+ className={fieldClass}+ />+ </div>++ <div className="flex flex-col gap-1">+ <label htmlFor="cc-description" className="text-xs text-gray-300">Description <span className="text-gray-500">(optional)</span></label>+ <input+ id="cc-description"+ type="text"+ value={draft.description}+ maxLength={500}+ onChange={(e) => set('description', e.target.value)}+ placeholder="A short summary shown in the catalog"+ className={fieldClass}+ />+ </div>++ <div className="flex flex-col gap-1">+ <label htmlFor="cc-prompt" className="text-xs text-gray-300">What to look for</label>+ <textarea+ id="cc-prompt"+ value={draft.prompt}+ rows={5}+ maxLength={8000}+ onChange={(e) => set('prompt', e.target.value)}+ placeholder="Describe what the LLM should flag in the manuscript. The JSON output format is added automatically."+ className={`${fieldClass} resize-y font-mono text-xs`}+ />+ <p className="text-[11px] text-gray-500">+ Just describe the problem to catch — PortOS appends the manuscript and the required findings JSON format.+ </p>+ </div>++ <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">+ <div className="flex flex-col gap-1">+ <label htmlFor="cc-scope" className="text-xs text-gray-300">Scope</label>+ <select id="cc-scope" value={draft.scope} onChange={(e) => set('scope', e.target.value)} className={fieldClass}>+ {SCOPES.map((s) => <option key={s} value={s}>{scopeLabel(s)}</option>)}+ </select>+ </div>+ <div className="flex flex-col gap-1">+ <label htmlFor="cc-category" className="text-xs text-gray-300">Category</label>+ <input+ id="cc-category"+ type="text"+ value={draft.category}+ maxLength={60}+ onChange={(e) => set('category', e.target.value)}+ className={fieldClass}+ />+ </div>+ <div className="flex flex-col gap-1">+ <label htmlFor="cc-severity" className="text-xs text-gray-300">Default severity</label>+ <select id="cc-severity" value={draft.severityDefault} onChange={(e) => set('severityDefault', e.target.value)} className={fieldClass}>+ {SEVERITIES.map((s) => <option key={s} value={s}>{s}</option>)}+ </select>+ </div>+ </div>++ <div className="flex items-center justify-end gap-2">+ <button+ type="button"+ onClick={onCancel}+ className="inline-flex items-center gap-1 rounded border border-port-border px-3 py-1.5 text-sm text-gray-300 hover:bg-port-border/40"+ >+ <X size={14} /> Cancel+ </button>+ <button+ type="submit"+ disabled={!canSave}+ 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"+ >+ {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}+ {isEdit ? 'Save changes' : 'Create check'}+ </button>+ </div>+ </form>+ );+}diff --git a/client/src/components/pipeline/editorial/EditorialCustomCheckForm.test.jsx b/client/src/components/pipeline/editorial/EditorialCustomCheckForm.test.jsxnew file mode 100644index 0000000000..838e0efd43--- /dev/null+++ b/client/src/components/pipeline/editorial/EditorialCustomCheckForm.test.jsx@@ -0,0 +1,47 @@+import { describe, it, expect, vi } from 'vitest';+import { render, screen, fireEvent } from '@testing-library/react';+import EditorialCustomCheckForm from './EditorialCustomCheckForm';++describe('EditorialCustomCheckForm (#1346)', () => {+ it('disables save until name + prompt are filled, then submits the trimmed values', () => {+ const onSave = vi.fn();+ render(<EditorialCustomCheckForm onSave={onSave} onCancel={() => {}} />);++ const submit = screen.getByRole('button', { name: /create check/i });+ expect(submit.disabled).toBe(true);++ fireEvent.change(screen.getByLabelText('Name'), { target: { value: ' Anachronisms ' } });+ fireEvent.change(screen.getByLabelText('What to look for'), { target: { value: ' Flag modern tech ' } });+ expect(submit.disabled).toBe(false);++ fireEvent.click(submit);+ expect(onSave).toHaveBeenCalledWith(expect.objectContaining({+ label: 'Anachronisms',+ prompt: 'Flag modern tech',+ scope: 'issue',+ category: 'custom',+ severityDefault: 'medium',+ }));+ });++ it('prefills from an existing check when editing', () => {+ render(+ <EditorialCustomCheckForm+ check={{ id: 'custom.1', label: 'Existing', prompt: 'do thing', scope: 'series', category: 'voice', severityDefault: 'high', isCustom: true }}+ onSave={() => {}}+ onCancel={() => {}}+ />,+ );+ expect(screen.getByText(/edit custom check/i)).toBeTruthy();+ expect(screen.getByLabelText('Name').value).toBe('Existing');+ expect(screen.getByLabelText('What to look for').value).toBe('do thing');+ expect(screen.getByLabelText('Default severity').value).toBe('high');+ });++ it('invokes onCancel without saving', () => {+ const onCancel = vi.fn();+ render(<EditorialCustomCheckForm onSave={() => {}} onCancel={onCancel} />);+ fireEvent.click(screen.getByRole('button', { name: /cancel/i }));+ expect(onCancel).toHaveBeenCalled();+ });+});diff --git a/client/src/pages/PipelineEditorialChecks.jsx b/client/src/pages/PipelineEditorialChecks.jsxindex e1ceed1b00..511be3ff6f 100644--- a/client/src/pages/PipelineEditorialChecks.jsx+++ b/client/src/pages/PipelineEditorialChecks.jsx@@ -13,9 +13,10 @@*/import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { Link, useSearchParams } from 'react-router-dom';-import { ArrowLeft, ListChecks, Loader2, Play, Square } from 'lucide-react';+import { ArrowLeft, ListChecks, Loader2, Play, Plus, Square } from 'lucide-react';import toast from '../components/ui/Toast';import EditorialCheckCard from '../components/pipeline/editorial/EditorialCheckCard';+import EditorialCustomCheckForm from '../components/pipeline/editorial/EditorialCustomCheckForm';import EditorialFindingsTriage from '../components/pipeline/editorial/EditorialFindingsTriage';import { groupChecksByScope } from '../lib/editorialChecks';import { usePipelineProgress } from '../hooks/usePipelineProgress';@@ -23,6 +24,9 @@ import {listPipelineSeries,getEditorialChecks,patchEditorialCheck,+ createEditorialCustomCheck,+ updateEditorialCustomCheck,+ deleteEditorialCustomCheck,startEditorialChecksRun,cancelEditorialChecksRun,getEditorialChecksRunStatus,@@ -163,6 +167,54 @@ export default function PipelineEditorialChecks() {.finally(() => setSavingIds((s) => { const n = new Set(s); n.delete(checkId); return n; }));}, []);+ // ---- Custom-check authoring (#1346). The form is URL-driven (?custom=new |+ // ?custom=<checkId>) so it's deep-linkable, not a stateful modal. ----+ const customParam = searchParams.get('custom') || '';+ const editingCheck = customParam && customParam !== 'new'+ ? checks.find((c) => c.id === customParam && c.isCustom) || null+ : null;+ // Form is open for 'new', or for a custom id that resolves to a check.+ const formOpen = customParam === 'new' || !!editingCheck;+ const [formSaving, setFormSaving] = useState(false);++ // useCallback so the memo'd custom cards (which take onEdit) only re-render on+ // an actual param change, not every parent run/selection state tick.+ const openCustomForm = useCallback((id) => {+ setSearchParams((prev) => { const next = new URLSearchParams(prev); next.set('custom', id); return next; }, { replace: true });+ }, [setSearchParams]);+ const closeCustomForm = useCallback(() => {+ setSearchParams((prev) => { const next = new URLSearchParams(prev); next.delete('custom'); return next; }, { replace: true });+ }, [setSearchParams]);++ const handleSaveCustom = (values) => {+ setFormSaving(true);+ const editingId = editingCheck?.id;+ const req = editingId+ ? updateEditorialCustomCheck(editingId, values, { silent: true })+ : createEditorialCustomCheck(values, { silent: true });+ req+ .then((row) => {+ if (!row) return;+ setChecks((rows) => (editingId+ ? rows.map((r) => (r.id === editingId ? row : r))+ : [...rows, row]));+ toast.success(editingId ? 'Custom check saved' : 'Custom check created');+ closeCustomForm();+ })+ .catch((err) => toast.error(err.message || 'Failed to save custom check'))+ .finally(() => setFormSaving(false));+ };++ const handleDeleteCustom = useCallback((checkId) => {+ setSavingIds((s) => new Set(s).add(checkId));+ // Drop from the targeted-run selection so a deleted id can't ride a run.+ setSelectedIds((s) => { if (!s.has(checkId)) return s; const n = new Set(s); n.delete(checkId); return n; });+ deleteEditorialCustomCheck(checkId, { silent: true })+ .then(() => { setChecks((rows) => rows.filter((r) => r.id !== checkId)); toast.success('Custom check deleted'); })+ .catch((err) => toast.error(err.message || 'Failed to delete custom check'))+ .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);@@ -277,7 +329,26 @@ export default function PipelineEditorialChecks() {<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>+ <div className="flex items-center justify-between gap-2">+ <h2 className="text-sm font-semibold uppercase tracking-wide text-gray-400">Catalog</h2>+ {!formOpen ? (+ <button+ type="button"+ onClick={() => openCustomForm('new')}+ className="inline-flex items-center gap-1 rounded border border-port-border px-2 py-1 text-xs text-gray-300 hover:bg-port-border/40"+ >+ <Plus size={13} /> New custom check+ </button>+ ) : null}+ </div>+ {formOpen ? (+ <EditorialCustomCheckForm+ check={editingCheck}+ saving={formSaving}+ onSave={handleSaveCustom}+ onCancel={closeCustomForm}+ />+ ) : null}{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) => (@@ -301,6 +372,8 @@ export default function PipelineEditorialChecks() {saving={savingIds.has(check.id)}onToggle={handleToggle}onConfigSave={handleConfigSave}+ onEdit={check.isCustom ? openCustomForm : undefined}+ onDelete={check.isCustom ? handleDeleteCustom : undefined}/></div></div>diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex 2ccb27b1bd..00519a5d13 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -634,6 +634,29 @@ export const patchEditorialCheck = (checkId, patch, options = {}) =>...options,});+// User-defined checks (#1346): author an LLM check (name + prompt + scope) with+// no code change. Create/update return the new check's resolved catalog row (the+// same shape getEditorialChecks rows carry, with `isCustom: true` + `prompt`).+export const createEditorialCustomCheck = (def, options = {}) =>+ request('/pipeline/editorial/custom-checks', {+ method: 'POST',+ body: JSON.stringify(def),+ ...options,+ });++export const updateEditorialCustomCheck = (checkId, patch, options = {}) =>+ request(`/pipeline/editorial/custom-checks/${encodeURIComponent(checkId)}`, {+ method: 'PATCH',+ body: JSON.stringify(patch),+ ...options,+ });++export const deleteEditorialCustomCheck = (checkId, options = {}) =>+ request(`/pipeline/editorial/custom-checks/${encodeURIComponent(checkId)}`, {+ method: 'DELETE',+ ...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).diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.mdindex 33ca583df0..980643011c 100644--- a/server/lib/editorial/README.md+++ b/server/lib/editorial/README.md@@ -10,19 +10,35 @@ the enabled checks, and seeds findings lives atThis directory is **pure** (no side-effecting imports — only `zod` and the pure`estimateTokens` budgeter). LLM-kind checks get their model caller through-`ctx.callStagedLLM`, and a manuscript-consuming LLM check plans the corpus into-provider-sized chunks through `ctx.planManuscriptChunks` — both injected by the-runner. Per-chunk findings are merged first-wins (capped at the check's-`maxFindings`) via `mergeChunkFindings`/`editorialFindingKey`, so a long series-is fully reviewed regardless of the provider's context window (#1340).+`ctx.callStagedLLM` (or `ctx.callInlineLLM` for user-defined checks), and a+manuscript-consuming LLM check plans the corpus into provider-sized chunks+through `ctx.planManuscriptChunks` — all injected by the runner. Per-chunk+findings are merged first-wins (capped at the check's `maxFindings`) via+`mergeChunkFindings`/`editorialFindingKey`, so a long series is fully reviewed+regardless of the provider's context window (#1340).## Discovery ruleBefore adding an editorial rule, check whether an existing registry entry covers-it. To add a new check, append an entry to `EDITORIAL_CHECKS` in+it. To add a new built-in check, append an entry to `EDITORIAL_CHECKS` in`checkRegistry.js` (the fail-fast guards enforce shape, enum, and unique-id).+## User-defined checks (#1346)++Users author their own LLM checks (name + prompt + scope) from the Editorial+Checks UI — no code change. A custom check's DEFINITION lives in settings+(`pipelineEditorialChecks.customChecks[]`); its enable/config override reuses the+SAME `checks[id]` slice the built-ins use. `buildCustomCheck(def)` synthesizes a+definition into the exact shape the registry/runner consume (an always-+manuscript-consuming LLM check, `id` prefixed `custom.`), so it flows through+`resolveCheckState` / `getEnabledChecks` / the runner identically to a built-in.+The fixed findings-JSON output contract is enforced by `buildCustomCheckPrompt`+(the user only describes WHAT to look for), and the model is called through the+runner-injected `ctx.callInlineLLM` (an inline-prompt sibling of+`ctx.callStagedLLM`, no shipped stage template). CRUD lives at+`POST/PATCH/DELETE /api/pipeline/editorial/custom-checks`.+| 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). |+| `checkRegistry.js` | `EDITORIAL_CHECKS` array + fail-fast guards + lookup/state helpers (`getCheck`, `getCheckById`, `getAllChecks`, `listChecks`, `resolveCheckState`, `getEnabledChecks`, `resolveCheckConfig`). User-defined-check helpers (`buildCustomCheck`, `buildCustomCheckPrompt`, `readCustomCheckDefs`, `isCustomCheckId`, `isValidCustomCheckDef`). 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.jsindex 7079b04a77..bb08555ffa 100644--- a/server/lib/editorial/checkRegistry.js+++ b/server/lib/editorial/checkRegistry.js@@ -29,7 +29,14 @@ import { estimateTokens } from '../contextBudget.js';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']);+export const CHECK_SEVERITIES = Object.freeze(['high', 'medium', 'low']);+const SEVERITIES = CHECK_SEVERITIES;++// Default per-run finding cap for user-defined checks (#1346) — mirrors the+// built-in LLM checks' `maxFindings` default so a long manuscript can't flood+// the review. Defined up here so the custom-check prompt builder and config+// schema (both below) share one source.+export const CUSTOM_CHECK_MAX_FINDINGS_DEFAULT = 12;// The serializable config-field types a check can declare for its UI form.// `configSchema` (a Zod schema) stays the validation authority on the server;@@ -270,6 +277,75 @@ function mapLlmFindings(raw, { severityDefault, category, max, withIssueNumber }})).filter((f) => f.problem);}+// ---------------------------------------------------------------------------+// User-defined (custom) LLM checks (#1346). A custom check has no shipped stage+// template — its prompt body is authored from the UI. The fixed JSON output+// contract is enforced HERE (not by the user), so an author only describes WHAT+// to look for; the response is parsed by the same `mapLlmFindings` the built-in+// stage prompts feed. Kept pure: the model caller (`ctx.callInlineLLM`) and the+// chunk planner (`ctx.planManuscriptChunks`) are injected by the runner.+// ---------------------------------------------------------------------------++// Free-form tag persisted on the run record so /runs can filter custom-check+// calls apart from the named-stage editorial checks.+export const CUSTOM_CHECK_RUN_SOURCE = 'pipeline-editorial-custom';++// Wrap a user's authored instructions in the fixed findings JSON contract. Pure+// and deterministic so it's unit-testable and so `runManuscriptLlmCheckInline`+// can render it once with an empty manuscript to measure per-call overhead.+export function buildCustomCheckPrompt({ instructions, manuscript, maxFindings = CUSTOM_CHECK_MAX_FINDINGS_DEFAULT }) {+ const cap = Number.isInteger(maxFindings) && maxFindings > 0 ? maxFindings : CUSTOM_CHECK_MAX_FINDINGS_DEFAULT;+ return [+ 'You are an editorial reviewer analyzing a draft manuscript for one specific issue.',+ '',+ '# What to look for',+ String(instructions || '').trim(),+ '',+ '# Manuscript',+ String(manuscript || ''),+ '',+ '# How to respond',+ `Return ONLY a JSON object of the form {"findings": [...]} with at most ${cap} findings.`,+ 'Each finding is an object with these fields:',+ '- "severity": one of "high", "medium", "low"',+ '- "location": a short human-readable pointer to where the problem is (e.g. a chapter or section name)',+ '- "problem": one sentence stating what is wrong (REQUIRED — omit the finding if you cannot name a concrete problem)',+ '- "suggestion": one sentence on how to fix it',+ '- "anchorQuote": a short verbatim quote from the manuscript at the problem location',+ '- "issueNumber": the issue/chapter number the problem is in, or null',+ 'If nothing matches, return {"findings": []}. Do not include any prose outside the JSON object.',+ ].join('\n');+}++// Inline-prompt sibling of `runManuscriptLlmCheck` for custom checks: same+// provider-sized chunking + first-wins merge, but the prompt is the authored+// instructions wrapped by `buildCustomCheckPrompt` instead of a named stage.+// `ctx.planManuscriptChunks(null, …)` resolves the active/overridden provider's+// window (a custom check has no stage to pin), and `ctx.callInlineLLM` runs the+// built prompt. Findings keep a model-supplied issue number (manuscript-scoped).+async function runManuscriptLlmCheckInline(ctx, { category, instructions }) {+ const max = ctx.config?.maxFindings ?? CUSTOM_CHECK_MAX_FINDINGS_DEFAULT;+ // Fixed per-call overhead = the contract wrapper + the instructions (only the+ // manuscript var changes per chunk). Measure it by rendering the prompt with an+ // empty manuscript so the chunk budget accounts for everything riding along.+ const overheadTokens = EDITORIAL_PROMPT_OVERHEAD_TOKENS+ + estimateTokens(buildCustomCheckPrompt({ instructions, manuscript: '', maxFindings: max }));+ const chunks = await ctx.planManuscriptChunks(null, { overheadTokens });+ const perChunk = [];+ for (const manuscript of chunks) {+ if (ctx.signal?.aborted) break;+ const prompt = buildCustomCheckPrompt({ instructions, manuscript, maxFindings: max });+ const { content } = await ctx.callInlineLLM(prompt, { returnsJson: true, source: CUSTOM_CHECK_RUN_SOURCE });+ perChunk.push(mapLlmFindings(content?.findings, {+ severityDefault: ctx.severityDefault,+ category,+ max,+ withIssueNumber: true,+ }));+ }+ return mergeChunkFindings(perChunk, max);+}+// ---------------------------------------------------------------------------// Deterministic helpers for the style-guide reading-level check (#1303). A// self-contained Flesch–Kincaid grade-level estimate so the registry stays pure@@ -928,7 +1004,10 @@ export const readChecksSlice = (settings) => {*/export function resolveCheckState(settings) {const stored = readChecksSlice(settings);- return EDITORIAL_CHECKS.map((check) => {+ // Built-ins + the user's synthesized custom checks (#1346) — a custom check+ // resolves identically; `isCustom` (and the authored `prompt`) mark it so the+ // UI can offer edit/delete and prefill the author form.+ return getAllChecks(settings).map((check) => {const row = stored[check.id] || {};const enabled = typeof row.enabled === 'boolean' ? row.enabled : check.defaultEnabled !== false;return {@@ -942,6 +1021,8 @@ export function resolveCheckState(settings) {enabled,config: resolveCheckConfig(check, row.config),configFields: Array.isArray(check.configFields) ? check.configFields : [],+ isCustom: !!check.isCustom,+ ...(check.isCustom ? { prompt: check.prompt } : {}),};});}@@ -962,7 +1043,100 @@ export function getEnabledCheckRows(settings, subsetIds = null) {* config) for every enabled check, narrowed to `subsetIds` when provided.*/export function getEnabledChecks(settings, subsetIds = null) {+ // Resolve against built-ins + custom checks (getCheck only knows built-ins).+ const byId = new Map(getAllChecks(settings).map((c) => [c.id, c]));return getEnabledCheckRows(settings, subsetIds)- .map((row) => ({ check: getCheck(row.id), config: row.config }))+ .map((row) => ({ check: byId.get(row.id), config: row.config })).filter((x) => x.check);}++// ---------------------------------------------------------------------------+// User-defined checks (#1346) — definition storage + synthesis.+//+// A custom check's DEFINITION lives in settings+// (`pipelineEditorialChecks.customChecks`), while its enable/config override+// reuses the SAME `checks[id]` slice the built-ins use — so the existing+// toggle/config PATCH path works unchanged. `buildCustomCheck` synthesizes a+// definition into the exact shape the registry/runner consume, so a custom check+// flows through resolveCheckState / getEnabledChecks / the runner like a built-in.+// ---------------------------------------------------------------------------++export const CUSTOM_CHECK_ID_PREFIX = 'custom.';+export const isCustomCheckId = (id) => typeof id === 'string' && id.startsWith(CUSTOM_CHECK_ID_PREFIX);++// One tunable (the per-run cap), mirroring the built-in LLM checks so the+// existing config form renders for custom checks with no special-casing.+const customCheckConfigSchema = z.object({+ maxFindings: z.number().int().min(1).max(50).default(CUSTOM_CHECK_MAX_FINDINGS_DEFAULT),+});+const CUSTOM_CHECK_CONFIG_FIELDS = Object.freeze([+ {+ 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.',+ },+]);++// True when a stored definition has the minimum viable shape. Defensive against+// a hand-edited settings.json or an older/newer peer — an invalid def is skipped+// (never throws), so one bad row can't break the whole catalog.+export function isValidCustomCheckDef(def) {+ return !!def+ && typeof def === 'object'+ && isCustomCheckId(def.id)+ && typeof def.label === 'string' && def.label.trim().length > 0+ && typeof def.prompt === 'string' && def.prompt.trim().length > 0+ && CHECK_SCOPES.includes(def.scope)+ && CHECK_SEVERITIES.includes(def.severityDefault);+}++// Synthesize a runnable check from a stored definition (or null when malformed).+// The result matches the built-in shape so the runner/resolver treat it the+// same; `isCustom` + `prompt` mark it for the UI. Custom checks are always+// manuscript-consuming LLM checks (the useful editorial case), gated on prose.+export function buildCustomCheck(def) {+ if (!isValidCustomCheckDef(def)) return null;+ const instructions = def.prompt;+ const category = typeof def.category === 'string' && def.category.trim() ? def.category.trim() : 'custom';+ return {+ id: def.id,+ label: def.label.trim(),+ description: typeof def.description === 'string' ? def.description.trim() : '',+ scope: def.scope,+ kind: 'llm',+ category,+ severityDefault: def.severityDefault,+ defaultEnabled: true,+ needsManuscript: true,+ isCustom: true,+ prompt: instructions,+ configSchema: customCheckConfigSchema,+ configFields: CUSTOM_CHECK_CONFIG_FIELDS,+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,+ run: (ctx) => runManuscriptLlmCheckInline(ctx, { category, instructions }),+ };+}++// The stored custom-check definitions, tolerant of a hand-edited / older-peer+// file (returns [] when absent or not an array).+export const readCustomCheckDefs = (settings) => {+ const defs = settings?.pipelineEditorialChecks?.customChecks;+ return Array.isArray(defs) ? defs : [];+};++// Synthesized custom checks for the current settings (invalid defs skipped).+export const buildCustomChecks = (settings) =>+ readCustomCheckDefs(settings).map(buildCustomCheck).filter(Boolean);++// All checks (built-in + custom) for the current settings.+export const getAllChecks = (settings) => [...EDITORIAL_CHECKS, ...buildCustomChecks(settings)];++// Settings-aware lookup spanning built-ins + custom checks. `getCheck` only+// knows built-ins, so the route + staleness path use this to resolve a custom id.+export function getCheckById(settings, id) {+ return CHECK_BY_ID.get(id) || buildCustomChecks(settings).find((c) => c.id === id) || null;+}diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.jsindex 578b74f3d9..463cf48f21 100644--- a/server/lib/editorial/checkRegistry.test.js+++ b/server/lib/editorial/checkRegistry.test.js@@ -10,11 +10,31 @@ import {resolveCheckConfig,resolveCheckState,getEnabledChecks,+ buildCustomCheck,+ buildCustomCheckPrompt,+ isValidCustomCheckDef,+ isCustomCheckId,+ getCheckById,+ getAllChecks,+ CUSTOM_CHECK_ID_PREFIX,+ CUSTOM_CHECK_MAX_FINDINGS_DEFAULT,} from './checkRegistry.js';const NAMING = 'naming.dissimilar-names';const INFODUMP = 'prose.info-dumping';+// A minimal valid stored custom-check definition.+const customDef = (over = {}) => ({+ id: `${CUSTOM_CHECK_ID_PREFIX}abc`,+ label: 'Anachronisms',+ prompt: 'Flag modern technology in a period setting.',+ scope: 'issue',+ category: 'continuity',+ severityDefault: 'medium',+ ...over,+});+const settingsWith = (defs) => ({ pipelineEditorialChecks: { customChecks: defs } });+describe('editorial check registry — shape invariants', () => {it('every entry has a valid shape', () => {for (const check of EDITORIAL_CHECKS) {@@ -665,3 +685,134 @@ describe('style.conformance — LLM check (#1303)', () => {expect(check.defaultEnabled).toBe(true);});});++// ---------------------------------------------------------------------------+// User-defined checks (#1346)+// ---------------------------------------------------------------------------++describe('custom checks (#1346)', () => {+ describe('isValidCustomCheckDef', () => {+ it('accepts a well-formed definition', () => {+ expect(isValidCustomCheckDef(customDef())).toBe(true);+ });+ it('rejects missing/blank required fields and bad enums', () => {+ expect(isValidCustomCheckDef(null)).toBe(false);+ expect(isValidCustomCheckDef(customDef({ id: 'naming.x' }))).toBe(false); // not a custom id+ expect(isValidCustomCheckDef(customDef({ label: ' ' }))).toBe(false);+ expect(isValidCustomCheckDef(customDef({ prompt: '' }))).toBe(false);+ expect(isValidCustomCheckDef(customDef({ scope: 'bogus' }))).toBe(false);+ expect(isValidCustomCheckDef(customDef({ severityDefault: 'urgent' }))).toBe(false);+ });+ });++ describe('isCustomCheckId', () => {+ it('matches the custom prefix only', () => {+ expect(isCustomCheckId('custom.abc')).toBe(true);+ expect(isCustomCheckId('prose.info-dumping')).toBe(false);+ expect(isCustomCheckId(null)).toBe(false);+ });+ });++ describe('buildCustomCheck', () => {+ it('synthesizes a runnable LLM check matching the built-in shape', () => {+ const check = buildCustomCheck(customDef());+ expect(check).toBeTruthy();+ expect(check.kind).toBe('llm');+ expect(check.isCustom).toBe(true);+ expect(check.needsManuscript).toBe(true);+ expect(check.defaultEnabled).toBe(true);+ expect(check.scope).toBe('issue');+ expect(check.category).toBe('continuity');+ expect(typeof check.run).toBe('function');+ expect(typeof check.gate).toBe('function');+ // Passes the registry's own structural guards.+ expect(() => assertValidChecks([check])).not.toThrow();+ });+ it('defaults category to "custom" and returns null for a bad def', () => {+ expect(buildCustomCheck(customDef({ category: ' ' })).category).toBe('custom');+ expect(buildCustomCheck(customDef({ id: 'x' }))).toBeNull();+ });+ it('gate skips when there is no manuscript', () => {+ const check = buildCustomCheck(customDef());+ expect(check.gate({ manuscript: '' })).toBe(false);+ expect(check.gate({ manuscript: 'Chapter 1...' })).toBe(true);+ });+ });++ describe('buildCustomCheckPrompt', () => {+ it('wraps instructions + manuscript in the findings JSON contract', () => {+ const prompt = buildCustomCheckPrompt({ instructions: 'Find anachronisms', manuscript: 'A knight checks his phone.', maxFindings: 7 });+ expect(prompt).toContain('Find anachronisms');+ expect(prompt).toContain('A knight checks his phone.');+ expect(prompt).toContain('"findings"');+ expect(prompt).toContain('at most 7 findings');+ expect(prompt).toContain('{"findings": []}');+ });+ it('falls back to the default cap on a bad maxFindings', () => {+ const prompt = buildCustomCheckPrompt({ instructions: 'x', manuscript: 'y', maxFindings: 0 });+ expect(prompt).toContain(`at most ${CUSTOM_CHECK_MAX_FINDINGS_DEFAULT} findings`);+ });+ });++ describe('integration with the resolver/runner helpers', () => {+ it('getAllChecks / getCheckById include valid custom checks and skip invalid ones', () => {+ const settings = settingsWith([customDef(), customDef({ id: 'custom.bad', scope: 'nope' })]);+ const ids = getAllChecks(settings).map((c) => c.id);+ expect(ids).toContain('custom.abc');+ expect(ids).not.toContain('custom.bad');+ expect(getCheckById(settings, 'custom.abc')?.label).toBe('Anachronisms');+ expect(getCheckById(settings, 'custom.bad')).toBeNull();+ expect(getCheckById(settings, NAMING)?.id).toBe(NAMING); // built-ins still resolve+ });++ it('resolveCheckState surfaces a custom check with isCustom + prompt + default-enabled', () => {+ const row = resolveCheckState(settingsWith([customDef()])).find((r) => r.id === 'custom.abc');+ expect(row).toBeTruthy();+ expect(row.isCustom).toBe(true);+ expect(row.prompt).toContain('modern technology');+ expect(row.enabled).toBe(true);+ expect(row.config.maxFindings).toBe(CUSTOM_CHECK_MAX_FINDINGS_DEFAULT);+ });++ it('the shared checks[id] override toggles a custom check off', () => {+ const settings = {+ pipelineEditorialChecks: {+ customChecks: [customDef()],+ checks: { 'custom.abc': { enabled: false } },+ },+ };+ const row = resolveCheckState(settings).find((r) => r.id === 'custom.abc');+ expect(row.enabled).toBe(false);+ expect(getEnabledChecks(settings).some((x) => x.check.id === 'custom.abc')).toBe(false);+ });++ it('getEnabledChecks resolves the synthesized custom check for execution', () => {+ const enabled = getEnabledChecks(settingsWith([customDef()]));+ const entry = enabled.find((x) => x.check.id === 'custom.abc');+ expect(entry).toBeTruthy();+ expect(entry.check.kind).toBe('llm');+ expect(entry.config.maxFindings).toBe(CUSTOM_CHECK_MAX_FINDINGS_DEFAULT);+ });++ it('a custom check run calls callInlineLLM per chunk and maps findings', async () => {+ const check = buildCustomCheck(customDef());+ let sentPrompt;+ const findings = await check.run({+ config: { maxFindings: 5 },+ severityDefault: 'medium',+ manuscript: 'Chapter 1. A knight checks his phone.',+ planManuscriptChunks: async () => ['Chapter 1. A knight checks his phone.'],+ callInlineLLM: async (prompt) => {+ sentPrompt = prompt;+ return { content: { findings: [{ severity: 'high', issueNumber: 1, problem: 'anachronistic phone', anchorQuote: 'his phone' }] } };+ },+ });+ expect(sentPrompt).toContain('modern technology');+ expect(sentPrompt).toContain('A knight checks his phone.');+ expect(findings).toHaveLength(1);+ expect(findings[0].category).toBe('continuity');+ expect(findings[0].severity).toBe('high');+ expect(findings[0].issueNumber).toBe(1);+ });+ });+});diff --git a/server/lib/stageRunner.js b/server/lib/stageRunner.jsindex 57f8bd1487..a088cbfcbb 100644--- a/server/lib/stageRunner.js+++ b/server/lib/stageRunner.js@@ -259,8 +259,38 @@ export function extractJson(text, { promptToStrip } = {}) {*/export async function runStagedLLM(stageName, variables, options = {}) {const stage = getStage(stageName);- const provider = await resolveProviderForStage(stage, options);const prompt = await buildPrompt(stageName, variables);+ return executeStagePrompt({ stage, label: stageName, prompt, options });+}++/**+ * Run an INLINE (caller-supplied) prompt end-to-end — no named stage template.+ * Same provider/model resolution, runner.js transcript persistence, runtime+ * fallback, and JSON extraction as `runStagedLLM`, but the prompt body is passed+ * directly. With no stage there is no stage-pinned provider/model/timeout, so it+ * resolves to `options.providerOverride` (or the active provider). Used by+ * user-defined editorial checks (#1346) whose prompt is authored from the UI.+ *+ * Same options as runStagedLLM (providerOverride / modelOverride /+ * timeoutOverride / returnsJson / source).+ */+export async function runInlineLLM(prompt, options = {}) {+ if (typeof prompt !== 'string' || !prompt.trim()) {+ throw new ServerError('runInlineLLM requires a non-empty prompt', { status: 400, code: 'INLINE_PROMPT_REQUIRED' });+ }+ return executeStagePrompt({ stage: null, label: options.source || 'inline-llm', prompt, options });+}++/**+ * Shared execution body for runStagedLLM / runInlineLLM. Takes an already-built+ * prompt + an optional resolved stage (null for inline), resolves the provider/+ * model/timeout, creates the run record, executes through the shared runner+ * (with runtime fallback reconciliation), and returns+ * `{ content, model, providerId, runId }`. `label` is the free-form name used in+ * the log line (the stage name, or the inline source tag).+ */+async function executeStagePrompt({ stage, label, prompt, options }) {+ const provider = await resolveProviderForStage(stage, options);const resolvedModel = resolveModel(provider, options.modelOverride || stage?.model);// resolveEffectiveModel gates the override per provider type and, for// CLI providers with a baked --model/-m flag in args, extracts the@@ -326,7 +356,7 @@ export async function runStagedLLM(stageName, variables, options = {}) {metadataPatch.providerName = effectiveProvider.name;}patchRunMetadata(runId, metadataPatch).catch(() => { /* best-effort */ });- console.log(`📝 stage: ${effectiveProvider.id} / ${effectiveModel || '(default)'} / ${stageName} → ${runId.slice(0, 8)}`);+ console.log(`📝 stage: ${effectiveProvider.id} / ${effectiveModel || '(default)'} / ${label} → ${runId.slice(0, 8)}`);// Stage runs pre-create the run record (so the runId can be logged BEFORE// the LLM call starts), then thread that id through the shared runner.@@ -350,7 +380,7 @@ export async function runStagedLLM(stageName, variables, options = {}) {finalRunId = runResult2.runId;finalProvider = runResult2.fallbackProvider;finalModel = runResult2.model ?? finalModel;- console.log(`⚡ stage fallback succeeded: ${finalProvider.id} / ${finalModel || '(default)'} / ${stageName} → ${finalRunId.slice(0, 8)}`);+ console.log(`⚡ stage fallback succeeded: ${finalProvider.id} / ${finalModel || '(default)'} / ${label} → ${finalRunId.slice(0, 8)}`);}// Codex CLI dumps the full transcript (banner + metadata + echoed prompt +// `codex\n<reply>` + token-stats footer). Carve out the assistant replydiff --git a/server/lib/stageRunner.test.js b/server/lib/stageRunner.test.jsindex 81678568c8..72718c6b0a 100644--- a/server/lib/stageRunner.test.js+++ b/server/lib/stageRunner.test.js@@ -21,7 +21,7 @@ vi.mock('../services/runner.js', () => ({const providers = await import('../services/providers.js');const prompts = await import('../services/promptService.js');const runner = await import('../services/runner.js');-const { runStagedLLM, resolveModel, extractJson } = await import('./stageRunner.js');+const { runStagedLLM, runInlineLLM, resolveModel, extractJson } = await import('./stageRunner.js');const apiProvider = (extra = {}) => ({id: 'mock-api', name: 'Mock', type: 'api', enabled: true, defaultModel: 'm-default', ...extra,@@ -192,6 +192,30 @@ describe('stageRunner — runStagedLLM provider resolution', () => {});});+describe('stageRunner — runInlineLLM (#1346)', () => {+ it('runs a caller-supplied prompt with no stage (active provider, no buildPrompt)', async () => {+ providers.getActiveProvider.mockResolvedValue(apiProvider());+ let executedPrompt;+ runner.executeApiRun.mockImplementation(async ({ prompt, onData, onComplete }) => {+ executedPrompt = prompt;+ onData('{"findings": []}');+ onComplete({ success: true });+ });+ const out = await runInlineLLM('my inline prompt body', { returnsJson: true, source: 'pipeline-editorial-custom' });+ expect(out.providerId).toBe('mock-api');+ expect(out.content).toEqual({ findings: [] });+ // The prompt is passed through verbatim — buildPrompt/getStage are not consulted.+ expect(executedPrompt).toBe('my inline prompt body');+ expect(prompts.buildPrompt).not.toHaveBeenCalled();+ expect(prompts.getStage).not.toHaveBeenCalled();+ });++ it('rejects an empty prompt', async () => {+ await expect(runInlineLLM(' ')).rejects.toMatchObject({ code: 'INLINE_PROMPT_REQUIRED' });+ await expect(runInlineLLM(null)).rejects.toMatchObject({ code: 'INLINE_PROMPT_REQUIRED' });+ });+});+describe('stageRunner — runStagedLLM dispatch', () => {it('routes CLI providers through executeCliRun', async () => {prompts.getStage.mockReturnValue(null);diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 82632478c3..49665b3e41 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -5,6 +5,7 @@ import { WORK_KINDS, WORK_STATUSES, ANALYSIS_KINDS } from './writersRoomPresets.import { ALL_STYLE_IDS, STYLE_ID } from './writersRoomStylePresets.js';import { BIBLE_LIMITS, RELATIONSHIP_LINK_TYPES, RELATIONSHIP_OPPOSITION_AXES, ATTACHMENT_ROLES } from './storyBible.js';import { MIN_TIMEOUT as STAGE_TIMEOUT_MIN_MS, MAX_TIMEOUT as STAGE_TIMEOUT_MAX_MS } from './aiToolkit/constants.js';+import { CHECK_SCOPES, CHECK_SEVERITIES } from './editorial/checkRegistry.js';// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total// pixels. Mirror the ceiling for every image-gen route. Local mflux can@@ -1017,10 +1018,45 @@ export const editorialChecksRunSchema = z.object({model: z.string().trim().max(200).optional(),}).strict();+// User-defined editorial check (#1346) — the authored input shape for+// POST .../editorial/custom-checks. The user only describes WHAT to look for;+// the JSON output contract is enforced server-side (buildCustomCheckPrompt), so+// no schema field captures it. `scope`/`severityDefault` reuse the registry's+// own enums so the wire gate can't drift from what `buildCustomCheck` accepts.+export const editorialCustomCheckCreateSchema = z.object({+ label: z.string().trim().min(1).max(120),+ description: z.string().trim().max(500).optional().default(''),+ prompt: z.string().trim().min(1).max(8_000),+ scope: z.enum([...CHECK_SCOPES]).optional().default('issue'),+ category: z.string().trim().max(60).optional().default('custom'),+ severityDefault: z.enum([...CHECK_SEVERITIES]).optional().default('medium'),+}).strict();++// Edit is the same shape, all-optional (the id is in the URL). `.partial()`+// drops the `.default()`s so an unspecified field is simply left unchanged.+export const editorialCustomCheckUpdateSchema = editorialCustomCheckCreateSchema.partial();++// The STORED definition shape (settings.pipelineEditorialChecks.customChecks[]):+// the authored fields + the generated id and timestamps. Validated as part of+// the settings slice below so a hand-edited / synced file is bounded.+export const editorialCustomCheckDefSchema = z.object({+ id: z.string().trim().min(1).max(120),+ label: z.string().trim().min(1).max(120),+ description: z.string().trim().max(500).optional().default(''),+ prompt: z.string().trim().min(1).max(8_000),+ scope: z.enum([...CHECK_SCOPES]),+ category: z.string().trim().max(60).optional().default('custom'),+ severityDefault: z.enum([...CHECK_SEVERITIES]),+ createdAt: z.string().optional(),+ updatedAt: z.string().optional(),+}).strict();+// settings.pipelineEditorialChecks slice (validated on PUT /api/settings when-// present). `checks` maps a checkId → its persisted enable/config.+// present). `checks` maps a checkId → its persisted enable/config; `customChecks`+// holds the user-defined check definitions (#1346).export const pipelineEditorialChecksSettingsSchema = z.object({checks: z.record(editorialCheckConfigSchema).optional(),+ customChecks: z.array(editorialCustomCheckDefSchema).optional(),}).strict();// Cursor-context payload for the CD-bridge suggest route — identical shape todiff --git a/server/routes/pipeline/editorial.js b/server/routes/pipeline/editorial.jsindex e50a41b713..d1362cb6a9 100644--- a/server/routes/pipeline/editorial.js+++ b/server/routes/pipeline/editorial.js@@ -3,11 +3,25 @@* per-issue and series-wide (batch with SSE progress).*/+import { randomUUID } from 'crypto';import { Router } from 'express';import { z } from 'zod';import { asyncHandler, ServerError } from '../../lib/errorHandler.js';-import { validateRequest, editorialCheckConfigSchema, editorialChecksRunSchema } from '../../lib/validation.js';-import { getCheck, resolveCheckState, readChecksSlice } from '../../lib/editorial/index.js';+import {+ validateRequest,+ editorialCheckConfigSchema,+ editorialChecksRunSchema,+ editorialCustomCheckCreateSchema,+ editorialCustomCheckUpdateSchema,+} from '../../lib/validation.js';+import {+ resolveCheckState,+ readChecksSlice,+ getCheckById,+ readCustomCheckDefs,+ isCustomCheckId,+ CUSTOM_CHECK_ID_PREFIX,+} 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';@@ -88,7 +102,10 @@ router.get('/editorial/checks', asyncHandler(async (req, res) => {// 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);+ // Resolve against built-ins + custom checks so a custom check's enable/config+ // override goes through the same path as a built-in's (#1346).+ const settings = await getSettings();+ const check = getCheckById(settings, 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) {@@ -110,13 +127,85 @@ router.patch('/editorial/checks/:id', asyncHandler(async (req, res) => {res.json(resolveCheckState(updated).find((r) => r.id === check.id));}));+// ---------------------------------------------------------------------------+// User-defined checks (#1346) — author LLM checks (name + prompt + scope) with+// no code change. The DEFINITION lives in settings.pipelineEditorialChecks.+// customChecks[]; enable/config still flow through PATCH /editorial/checks/:id.+// ---------------------------------------------------------------------------++const editorialChecksSlice = (current) =>+ (current.pipelineEditorialChecks && typeof current.pipelineEditorialChecks === 'object'+ ? current.pipelineEditorialChecks : {});++// Create a custom check. Returns its resolved catalog row (so the UI can append+// it without a refetch).+router.post('/editorial/custom-checks', asyncHandler(async (req, res) => {+ const body = validateRequest(editorialCustomCheckCreateSchema, req.body ?? {});+ const id = `${CUSTOM_CHECK_ID_PREFIX}${randomUUID()}`;+ const now = new Date().toISOString();+ const def = { id, ...body, createdAt: now, updatedAt: now };+ const updated = await updateSettingsWith((current) => {+ const slice = editorialChecksSlice(current);+ const defs = Array.isArray(slice.customChecks) ? slice.customChecks : [];+ return { ...current, pipelineEditorialChecks: { ...slice, customChecks: [...defs, def] } };+ });+ res.status(201).json(resolveCheckState(updated).find((r) => r.id === id));+}));++// Edit a custom check's definition (label / prompt / scope / category / severity).+router.patch('/editorial/custom-checks/:id', asyncHandler(async (req, res) => {+ const id = req.params.id;+ if (!isCustomCheckId(id)) throw new ServerError('Not a custom check id', { status: 400 });+ const body = validateRequest(editorialCustomCheckUpdateSchema, req.body ?? {});+ const settings = await getSettings();+ if (!readCustomCheckDefs(settings).some((d) => d?.id === id)) {+ throw new ServerError(`Unknown custom check: ${id}`, { status: 404 });+ }+ const updated = await updateSettingsWith((current) => {+ const slice = editorialChecksSlice(current);+ const defs = Array.isArray(slice.customChecks) ? slice.customChecks : [];+ // Preserve id + createdAt; apply only the supplied fields; stamp updatedAt.+ const next = defs.map((d) => (d?.id === id+ ? { ...d, ...body, id: d.id, createdAt: d.createdAt, updatedAt: new Date().toISOString() }+ : d));+ return { ...current, pipelineEditorialChecks: { ...slice, customChecks: next } };+ });+ res.json(resolveCheckState(updated).find((r) => r.id === id));+}));++// Delete a custom check — drops both its definition and its enable/config override.+router.delete('/editorial/custom-checks/:id', asyncHandler(async (req, res) => {+ const id = req.params.id;+ if (!isCustomCheckId(id)) throw new ServerError('Not a custom check id', { status: 400 });+ const settings = await getSettings();+ if (!readCustomCheckDefs(settings).some((d) => d?.id === id)) {+ throw new ServerError(`Unknown custom check: ${id}`, { status: 404 });+ }+ await updateSettingsWith((current) => {+ const slice = editorialChecksSlice(current);+ const defs = Array.isArray(slice.customChecks) ? slice.customChecks : [];+ const checks = readChecksSlice(current);+ const { [id]: _removed, ...remainingChecks } = checks;+ return {+ ...current,+ pipelineEditorialChecks: {+ ...slice,+ customChecks: defs.filter((d) => d?.id !== id),+ checks: remainingChecks,+ },+ };+ });+ res.json({ deleted: true, 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 ?? {});// Reject unknown check ids up front — otherwise a typo'd subset is silently// filtered to a zero-check run that reports success (PATCH 404s unknown ids too).if (body.checkIds?.length) {- const unknown = body.checkIds.filter((id) => !getCheck(id));+ const settings = await getSettings();+ const unknown = body.checkIds.filter((id) => !getCheckById(settings, id));if (unknown.length) {throw new ServerError(`Unknown editorial check(s): ${unknown.join(', ')}`, { status: 400 });}diff --git a/server/routes/pipeline/editorial.test.js b/server/routes/pipeline/editorial.test.jsindex 12cec15170..c22f007de6 100644--- a/server/routes/pipeline/editorial.test.js+++ b/server/routes/pipeline/editorial.test.js@@ -112,4 +112,81 @@ describe('POST /api/pipeline/series/:id/editorial/checks/run', () => {expect(res.status).toBe(400);expect(startEditorialChecksRun).not.toHaveBeenCalled();});++ it('accepts a created custom check id in a targeted run', async () => {+ const created = await request(app)+ .post('/api/pipeline/editorial/custom-checks')+ .send({ label: 'Runnable', prompt: 'Find X' });+ const res = await request(app)+ .post('/api/pipeline/series/s1/editorial/checks/run')+ .send({ checkIds: [created.body.id] });+ expect(res.status).toBe(200);+ expect(startEditorialChecksRun).toHaveBeenCalled();+ });+});++describe('custom checks CRUD (#1346)', () => {+ const create = (body) => request(app).post('/api/pipeline/editorial/custom-checks').send(body);++ it('creates a custom check and returns its resolved row', async () => {+ const res = await create({ label: 'Anachronisms', prompt: 'Flag modern tech in a period setting.' });+ expect(res.status).toBe(201);+ expect(res.body.id.startsWith('custom.')).toBe(true);+ expect(res.body.isCustom).toBe(true);+ expect(res.body.kind).toBe('llm');+ expect(res.body.enabled).toBe(true);+ expect(res.body.prompt).toContain('modern tech');+ expect(settingsStore.pipelineEditorialChecks.customChecks).toHaveLength(1);+ const list = await request(app).get('/api/pipeline/editorial/checks');+ expect(list.body.checks.some((c) => c.id === res.body.id)).toBe(true);+ });++ it('400s a create with no prompt or label', async () => {+ expect((await create({ label: 'No prompt' })).status).toBe(400);+ expect((await create({ prompt: 'No label' })).status).toBe(400);+ });++ it('reuses the shared toggle path to enable/disable a custom check', async () => {+ const { body } = await create({ label: 'Toggle me', prompt: 'do thing' });+ const res = await request(app)+ .patch(`/api/pipeline/editorial/checks/${encodeURIComponent(body.id)}`)+ .send({ enabled: false });+ expect(res.status).toBe(200);+ expect(res.body.enabled).toBe(false);+ expect(settingsStore.pipelineEditorialChecks.checks[body.id].enabled).toBe(false);+ });++ it('edits a custom check definition, preserving id/createdAt', async () => {+ const { body } = await create({ label: 'Old name', prompt: 'old prompt' });+ const createdAt = settingsStore.pipelineEditorialChecks.customChecks[0].createdAt;+ const res = await request(app)+ .patch(`/api/pipeline/editorial/custom-checks/${encodeURIComponent(body.id)}`)+ .send({ label: 'New name', severityDefault: 'high' });+ expect(res.status).toBe(200);+ expect(res.body.label).toBe('New name');+ expect(res.body.severityDefault).toBe('high');+ const def = settingsStore.pipelineEditorialChecks.customChecks[0];+ expect(def.id).toBe(body.id);+ expect(def.createdAt).toBe(createdAt);+ expect(def.prompt).toBe('old prompt'); // untouched fields preserved+ });++ it('404s editing an unknown custom id and 400s a non-custom id', async () => {+ expect((await request(app).patch('/api/pipeline/editorial/custom-checks/custom.nope').send({ label: 'x' })).status).toBe(404);+ expect((await request(app).patch('/api/pipeline/editorial/custom-checks/prose.info-dumping').send({ label: 'x' })).status).toBe(400);+ });++ it('deletes a custom check and its enable/config override', async () => {+ const { body } = await create({ label: 'Delete me', prompt: 'p' });+ await request(app).patch(`/api/pipeline/editorial/checks/${encodeURIComponent(body.id)}`).send({ enabled: false });+ const res = await request(app).delete(`/api/pipeline/editorial/custom-checks/${encodeURIComponent(body.id)}`);+ expect(res.status).toBe(200);+ expect(res.body.deleted).toBe(true);+ expect(settingsStore.pipelineEditorialChecks.customChecks).toHaveLength(0);+ expect(settingsStore.pipelineEditorialChecks.checks[body.id]).toBeUndefined();+ });++ it('404s deleting an unknown custom id', async () => {+ expect((await request(app).delete('/api/pipeline/editorial/custom-checks/custom.nope')).status).toBe(404);+ });});diff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.jsindex cc825f63d6..0b4ddb3de9 100644--- a/server/services/pipeline/editorial/checkRunner.js+++ b/server/services/pipeline/editorial/checkRunner.js@@ -17,9 +17,9 @@import { randomUUID, createHash } from 'crypto';import { createSseRunner } from '../../../lib/sseUtils.js';-import { runStagedLLM, resolveStageContext } from '../../../lib/stageRunner.js';+import { runStagedLLM, runInlineLLM, resolveStageContext } from '../../../lib/stageRunner.js';import { planManuscriptPass } from '../../../lib/contextBudget.js';-import { getEnabledChecks, getEnabledCheckRows, getCheck } from '../../../lib/editorial/index.js';+import { getEnabledChecks, getEnabledCheckRows, getCheckById } from '../../../lib/editorial/index.js';import { getSettings } from '../../settings.js';import { getSeries } from '../series.js';import { listIssues } from '../issues.js';@@ -127,6 +127,11 @@ export async function runEditorialChecks(seriesId, options = {}) {// provider/model overrides so an LLM check honors the autopilot's choice.callStagedLLM: (stage, vars, opts = {}) =>runStagedLLM(stage, vars, { providerOverride, modelOverride, ...opts }),+ // Injected inline-prompt caller for user-defined checks (#1346) whose prompt+ // body is authored from the UI (no shipped stage template). Same provider/+ // model overrides as callStagedLLM so a custom check honors the run's choice.+ callInlineLLM: (prompt, opts = {}) =>+ runInlineLLM(prompt, { providerOverride, modelOverride, ...opts }),// Injected manuscript chunker — plans the stitched manuscript into chunks// sized to `stage`'s resolved provider context window (reusing the same// budgeter as the completeness pass), so a long series is fully reviewed@@ -227,11 +232,15 @@ export async function buildEditorialCheckPlan(seriesId, { checkIds = null, setti*/export async function getReviewWithStaleness(seriesId) {const review = await getReview(seriesId);+ // Resolve checks against built-ins + the user's custom checks (#1346) so a+ // custom-check finding still gets staleness annotation. Read settings once.+ const settings = await getSettings();+ const checkFor = (id) => getCheckById(settings, id);// Only recompute hashes when there's at least one hash-stamped finding from a// still-registered check — a pure completeness review pays no extra I/O.- const evaluable = review.comments.filter((c) => c.checkId && c.sourceContentHash && getCheck(c.checkId));+ const evaluable = review.comments.filter((c) => c.checkId && c.sourceContentHash && checkFor(c.checkId));if (!evaluable.length) return review;- const needsManuscript = evaluable.some((c) => getCheck(c.checkId).needsManuscript);+ const needsManuscript = evaluable.some((c) => checkFor(c.checkId).needsManuscript);const series = await getSeries(seriesId);const [sections, canon] = await Promise.all([needsManuscript ? collectManuscriptSections(seriesId) : Promise.resolve([]),@@ -241,7 +250,7 @@ export async function getReviewWithStaleness(seriesId) {return {...review,comments: review.comments.map((c) => {- const check = c.checkId && c.sourceContentHash ? getCheck(c.checkId) : null;+ const check = c.checkId && c.sourceContentHash ? checkFor(c.checkId) : null;if (!check) return c;const current = hashForCheck(sourceHashes, !!check.needsManuscript);return { ...c, stale: c.sourceContentHash !== current };