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: preview a draft editorial custom check against a series before saving (#1607)
[._.]/ Adam Eivy482a005ad591
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 139d556411..aac61bbec4 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -59,6 +59,8 @@- **[issue-1606] The editorial health panel's category and check breakdowns are now clickable — tap one to filter the findings list to it.** The "Open by category" and "Open by check" rows (and their regression flags) showed you *where* the problems were but weren't navigable: spotting a regressed category meant manually re-scanning the list for its findings. Each row whose findings you can triage is now a button that deep-links the triage filter to that category or check and scrolls the findings list into view; clicking the active row again clears the filter, and the row shows a highlighted state while it's the active filter. (Rows that only count findings the triage doesn't list — e.g. the "completeness" bucket — stay as plain text rather than linking to an empty list.) Because the filter writes the same URL query the toolbar uses, the resulting view stays deep-linkable. This also adds a proper **Category** filter to the triage toolbar — distinct from the existing scope filter, which is now correctly labeled **Scope** (its Noun/Scene/Issue/Series values were mislabeled "Category"). (`client/src/components/pipeline/editorial/EditorialHealthPanel.jsx`, `client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx`, `client/src/lib/editorialChecks.js`)+- **[issue-1607] Preview a custom check against a series before saving it.** Custom checks are authored as free-text prompts, and the only way to know whether one was noisy or mis-scoped used to be to save it, run the whole series, see the findings, then edit and re-run — a slow loop that left a half-baked check (and its seeded findings) in the catalog. The custom-check form now has a **Preview on this series** button: pick a series, fill in the name + prompt, and PortOS runs the *draft* against the live manuscript and shows sample findings inline — **without persisting the check, seeding the review, or recording a health-trend snapshot**. The dry-run uses the exact same provider-sized manuscript chunking and source resolution a real run would (so the sample reflects production behavior), respects the per-run findings cap, and surfaces the gate-skip case ("this series has no manuscript yet") and the clean case ("flagged nothing") distinctly. The button is disabled with a hint until a series is selected. Internally, the runner's shared context construction was extracted into a reusable `buildEditorialContext` helper so the preview and a real run can never drift apart. (`server/services/pipeline/editorial/checkRunner.js`, `server/routes/pipeline/editorial.js`, `server/lib/validation.js`, `client/src/services/apiPipeline.js`, `client/src/components/pipeline/editorial/EditorialCustomCheckForm.jsx`, `client/src/pages/PipelineEditorialChecks.jsx`)+- **[issue-1596] Override any editorial check's severity to match a series' house style — without touching code.** Every check ships a fixed default severity (e.g. `prose.adverb-density` defaults to `low`), but a literary-fiction series may want adverb density flagged `high` while an action series wants it `low`. Each check in the catalog now has a **Severity** selector: leave it on **Default** to use the registry value, or pin it to `high` / `medium` / `low`. A pin is **authoritative** — every finding that check raises is stamped with the chosen level, consistently across deterministic *and* LLM checks (a pin overrides both a check's escalation-from-default and an LLM's own per-finding severity, so "pin this check to low" actually means low everywhere). On the next run the pin also re-grades the check's *existing* open findings — even ones a sampled LLM pass doesn't re-surface — so the editorial-health score and any severity-based autopilot gating reflect the pinned level immediately rather than lagging on stale severities. Leaving a check on **Default** preserves its native per-finding nuance untouched. The override is backward-compatible and additive (absent → the check's `severityDefault`), and the catalog badge shows the effective level with a `*` marker when it's been overridden. (`server/lib/editorial/checkRegistry.js`, `server/routes/pipeline/editorial.js`, `server/services/pipeline/editorial/checkRunner.js`, `server/lib/validation.js`, `client/src/components/pipeline/editorial/EditorialCheckCard.jsx`, `client/src/pages/PipelineEditorialChecks.jsx`)- **[issue-1604] The findings triage now shows each check's kind and documented purpose, so you can tell a hard rule from an LLM judgement while triaging.** A finding listed its check's label and problem text but never the check's documented description — and custom checks were especially opaque, since you had to recall your own prompt to know what the check even looks for. Each check group header now carries a **rule / LLM** kind badge (the same badge the catalog card uses, now a shared `CheckKindBadge` component) plus an **info toggle** that expands the check's registry description inline — pulled from the catalog manifest the page already fetched, so it works even when the check is disabled. The toggle is only offered when the check actually ships a description; the kind badge always shows. Knowing whether a finding came from a deterministic heuristic or a model judgement makes false-positive triage faster. (`client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx`, `client/src/components/pipeline/editorial/CheckKindBadge.jsx`, `client/src/components/pipeline/editorial/EditorialCheckCard.jsx`, `client/src/lib/editorialChecks.js`)diff --git a/client/src/components/pipeline/editorial/EditorialCheckCard.jsx b/client/src/components/pipeline/editorial/EditorialCheckCard.jsxindex 3020827367..2ea5b044f8 100644--- a/client/src/components/pipeline/editorial/EditorialCheckCard.jsx+++ b/client/src/components/pipeline/editorial/EditorialCheckCard.jsx@@ -24,12 +24,8 @@ import { memo, useEffect, useState } from 'react';import { ChevronDown, ChevronRight, Loader2, Pencil, Sliders, Trash2 } from 'lucide-react';import ToggleSwitch from '../../ToggleSwitch';import CheckKindBadge from './CheckKindBadge';+import { SEVERITY_BADGE_CLASSES } from '../../../lib/editorialChecks';-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',-};const SEVERITY_LEVELS = ['high', 'medium', 'low'];function ConfigField({ checkId, field, value, disabled, onCommit, resetNonce = 0 }) {@@ -116,7 +112,7 @@ function EditorialCheckCard({<span className="text-sm font-medium text-gray-100">{check.label}</span><CheckKindBadge kind={check.kind} /><span- className={`text-[10px] px-1.5 py-0.5 rounded ${SEVERITY_BADGE[effectiveSeverity] || SEVERITY_BADGE.low}`}+ className={`text-[10px] px-1.5 py-0.5 rounded ${SEVERITY_BADGE_CLASSES[effectiveSeverity] || SEVERITY_BADGE_CLASSES.low}`}title={check.severityOverride ? `Overridden — default is ${check.severityDefault}` : 'Default severity'}>{effectiveSeverity}{check.severityOverride ? '*' : ''}diff --git a/client/src/components/pipeline/editorial/EditorialCustomCheckForm.jsx b/client/src/components/pipeline/editorial/EditorialCustomCheckForm.jsxindex 5ef3961c6d..d054ad327d 100644--- a/client/src/components/pipeline/editorial/EditorialCustomCheckForm.jsx+++ b/client/src/components/pipeline/editorial/EditorialCustomCheckForm.jsx@@ -4,10 +4,16 @@* 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.+ *+ * Dry-run preview (#1607): when the parent supplies `onPreview` (an async fn that+ * runs the DRAFT against the selected series WITHOUT saving) and `canPreview`+ * (a series is selected), a "Preview on this series" button runs the draft and+ * renders sample findings inline — so the author can judge noise/scope before+ * committing the check to the catalog.*/-import { useState } from 'react';-import { Loader2, Save, X } from 'lucide-react';-import { CHECK_SCOPE_ORDER, scopeLabel } from '../../../lib/editorialChecks';+import { useEffect, useRef, useState } from 'react';+import { FlaskConical, Loader2, Save, X } from 'lucide-react';+import { CHECK_SCOPE_ORDER, scopeLabel, SEVERITY_BADGE_CLASSES } 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.@@ -34,24 +40,73 @@ const draftFromCheck = (check) => ({severityDefault: SEVERITIES.includes(check?.severityDefault) ? check.severityDefault : 'medium',});-export default function EditorialCustomCheckForm({ check = null, saving = false, onSave, onCancel }) {+export default function EditorialCustomCheckForm({ check = null, saving = false, onSave, onCancel, onPreview = null, canPreview = false, previewTarget = null }) {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;+ // Preview (#1607) — transient dry-run state, local to the form (it never+ // persists). A preview describes ONE exact draft+series; it goes stale the+ // moment either changes, so we clear it on any edit and invalidate any+ // in-flight request via a generation ref (a slow response for the old draft/+ // series must not overwrite the UI after the user moved on).+ const [preview, setPreview] = useState(null);+ const [previewing, setPreviewing] = useState(false);+ const [previewError, setPreviewError] = useState('');+ const previewReqRef = useRef(0);+ const mountedRef = useRef(true);+ useEffect(() => () => { mountedRef.current = false; }, []);++ // Invalidate + clear any preview when the draft or the target series changes.+ const invalidatePreview = () => {+ previewReqRef.current += 1;+ setPreview(null);+ setPreviewError('');+ setPreviewing(false);+ };+ // A draft edit invalidates a prior/in-flight preview (it described a different draft).+ const set = (key, value) => {+ setDraft((d) => ({ ...d, [key]: value }));+ invalidatePreview();+ };+ // The form stays mounted across a series switch (only new↔edit remounts via the+ // key), so reset the preview when the target series changes too.+ useEffect(() => { invalidatePreview(); }, [previewTarget]); // eslint-disable-line react-hooks/exhaustive-deps++ const hasRequiredFields = draft.label.trim().length > 0 && draft.prompt.trim().length > 0;+ const canSave = hasRequiredFields && !saving;++ // Shared payload so submit and preview send the IDENTICAL draft shape — a+ // preview that diverged from what gets saved would mislead the author.+ const buildPayload = () => ({+ label: draft.label.trim(),+ description: draft.description.trim(),+ prompt: draft.prompt.trim(),+ scope: draft.scope,+ category: draft.category.trim() || 'custom',+ severityDefault: draft.severityDefault,+ });++ const canPreviewNow = !!onPreview && canPreview && hasRequiredFields && !previewing && !saving;++ const runPreview = () => {+ if (!canPreviewNow) return;+ const reqId = (previewReqRef.current += 1);+ // Gate every state write on staleness (this request still current) AND mount+ // — a draft edit / series switch / unmount during the request drops its result.+ const isCurrent = () => mountedRef.current && reqId === previewReqRef.current;+ setPreviewing(true);+ setPreviewError('');+ setPreview(null);+ Promise.resolve(onPreview(buildPayload()))+ .then((res) => { if (isCurrent()) setPreview(res || { findings: [] }); })+ .catch((err) => { if (isCurrent()) setPreviewError(err?.message || 'Preview failed'); })+ .finally(() => { if (isCurrent()) setPreviewing(false); });+ };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,- });+ onSave(buildPayload());};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';@@ -130,7 +185,19 @@ export default function EditorialCustomCheckForm({ check = null, saving = false,</div></div>- <div className="flex items-center justify-end gap-2">+ <div className="flex flex-wrap items-center justify-end gap-2">+ {onPreview ? (+ <button+ type="button"+ onClick={runPreview}+ disabled={!canPreviewNow}+ title={canPreview ? 'Run this draft against the selected series without saving' : 'Select a series above to preview'}+ className="mr-auto inline-flex items-center gap-1.5 rounded border border-port-border px-3 py-1.5 text-sm text-gray-300 hover:bg-port-border/40 disabled:cursor-not-allowed disabled:opacity-50"+ >+ {previewing ? <Loader2 size={14} className="animate-spin" /> : <FlaskConical size={14} />}+ Preview on this series+ </button>+ ) : null}<buttontype="button"onClick={onCancel}@@ -147,6 +214,55 @@ export default function EditorialCustomCheckForm({ check = null, saving = false,{isEdit ? 'Save changes' : 'Create check'}</button></div>++ {/* Preview hint: only when previewing is offered but no series is selected. */}+ {onPreview && !canPreview ? (+ <p className="text-[11px] text-gray-500">Select a series above to preview this check before saving.</p>+ ) : null}++ {/* Dry-run results (#1607) — sample findings only; nothing is persisted. */}+ {previewError ? (+ <p className="rounded border border-port-error/40 bg-port-error/10 p-2 text-xs text-port-error" role="alert">{previewError}</p>+ ) : null}+ {preview ? <PreviewResults preview={preview} /> : null}</form>);}++// Renders the transient dry-run outcome: the gate-skip / empty / invalid notices,+// or the sample findings list. Pure presentational — the findings are never+// seeded into the review (#1607).+function PreviewResults({ preview }) {+ if (preview.invalid) {+ return <p className="rounded border border-port-border bg-port-bg p-2 text-xs text-gray-400">Fill in a name and prompt to preview this check.</p>;+ }+ if (preview.skipped) {+ return <p className="rounded border border-port-border bg-port-bg p-2 text-xs text-gray-400">Nothing to preview yet — this series has no manuscript content.</p>;+ }+ const findings = Array.isArray(preview.findings) ? preview.findings : [];+ if (findings.length === 0) {+ return <p className="rounded border border-port-success/40 bg-port-success/10 p-2 text-xs text-port-success">No sample findings — this check flagged nothing on the current manuscript.</p>;+ }+ return (+ <div className="space-y-2 rounded-lg border border-port-border bg-port-bg p-2">+ <p className="text-[11px] font-medium uppercase tracking-wider text-gray-500">+ Sample findings ({findings.length}) — preview only, not saved+ </p>+ <ul className="space-y-2">+ {findings.map((f, i) => (+ <li key={i} className="rounded border border-port-border/70 bg-port-card p-2 text-xs">+ <div className="flex items-center gap-2">+ <span className={`rounded px-1.5 py-0.5 text-[10px] font-semibold uppercase ${SEVERITY_BADGE_CLASSES[f.severity] || SEVERITY_BADGE_CLASSES.medium}`}>+ {f.severity || 'medium'}+ </span>+ {f.location ? <span className="truncate text-gray-400">{f.location}</span> : null}+ </div>+ {f.problem ? <p className="mt-1 text-gray-200">{f.problem}</p> : null}+ {f.suggestion ? <p className="mt-1 text-gray-400"><span className="text-gray-500">Fix:</span> {f.suggestion}</p> : null}+ {f.anchorQuote ? <p className="mt-1 border-l-2 border-port-border pl-2 italic text-gray-500">“{f.anchorQuote}”</p> : null}+ </li>+ ))}+ </ul>+ </div>+ );+}diff --git a/client/src/components/pipeline/editorial/EditorialCustomCheckForm.test.jsx b/client/src/components/pipeline/editorial/EditorialCustomCheckForm.test.jsxindex 838e0efd43..2f2510c662 100644--- a/client/src/components/pipeline/editorial/EditorialCustomCheckForm.test.jsx+++ b/client/src/components/pipeline/editorial/EditorialCustomCheckForm.test.jsx@@ -1,7 +1,12 @@import { describe, it, expect, vi } from 'vitest';-import { render, screen, fireEvent } from '@testing-library/react';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';import EditorialCustomCheckForm from './EditorialCustomCheckForm';+const fillRequired = () => {+ fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Anachronisms' } });+ fireEvent.change(screen.getByLabelText('What to look for'), { target: { value: 'Flag modern tech' } });+};+describe('EditorialCustomCheckForm (#1346)', () => {it('disables save until name + prompt are filled, then submits the trimmed values', () => {const onSave = vi.fn();@@ -44,4 +49,85 @@ describe('EditorialCustomCheckForm (#1346)', () => {fireEvent.click(screen.getByRole('button', { name: /cancel/i }));expect(onCancel).toHaveBeenCalled();});++ // Dry-run preview (#1607).+ it('hides the preview button entirely when onPreview is not provided', () => {+ render(<EditorialCustomCheckForm onSave={() => {}} onCancel={() => {}} />);+ expect(screen.queryByRole('button', { name: /preview on this series/i })).toBeNull();+ });++ it('shows a hint and disables preview when no series is selected', () => {+ render(<EditorialCustomCheckForm onSave={() => {}} onCancel={() => {}} onPreview={vi.fn()} canPreview={false} />);+ fillRequired();+ expect(screen.getByRole('button', { name: /preview on this series/i }).disabled).toBe(true);+ expect(screen.getByText(/select a series above to preview/i)).toBeTruthy();+ });++ it('runs the draft and renders sample findings when a series is selected', async () => {+ const onPreview = vi.fn().mockResolvedValue({+ findings: [{ severity: 'high', location: 'Chapter 1', problem: 'Anachronistic phone', suggestion: 'Remove it', anchorQuote: 'rang' }],+ skipped: false,+ invalid: false,+ });+ render(<EditorialCustomCheckForm onSave={() => {}} onCancel={() => {}} onPreview={onPreview} canPreview />);+ fillRequired();+ const btn = screen.getByRole('button', { name: /preview on this series/i });+ expect(btn.disabled).toBe(false);+ fireEvent.click(btn);+ expect(onPreview).toHaveBeenCalledWith(expect.objectContaining({ label: 'Anachronisms', prompt: 'Flag modern tech' }));+ await waitFor(() => expect(screen.getByText(/anachronistic phone/i)).toBeTruthy());+ expect(screen.getByText(/sample findings/i)).toBeTruthy();+ });++ it('renders the empty-result message when the draft finds nothing', async () => {+ const onPreview = vi.fn().mockResolvedValue({ findings: [], skipped: false, invalid: false });+ render(<EditorialCustomCheckForm onSave={() => {}} onCancel={() => {}} onPreview={onPreview} canPreview />);+ fillRequired();+ fireEvent.click(screen.getByRole('button', { name: /preview on this series/i }));+ await waitFor(() => expect(screen.getByText(/no sample findings/i)).toBeTruthy());+ });++ it('surfaces a preview error inline', async () => {+ const onPreview = vi.fn().mockRejectedValue(new Error('provider down'));+ render(<EditorialCustomCheckForm onSave={() => {}} onCancel={() => {}} onPreview={onPreview} canPreview />);+ fillRequired();+ fireEvent.click(screen.getByRole('button', { name: /preview on this series/i }));+ await waitFor(() => expect(screen.getByRole('alert').textContent).toMatch(/provider down/i));+ });++ it('clears a stale preview result when the draft is edited', async () => {+ const onPreview = vi.fn().mockResolvedValue({ findings: [{ severity: 'high', problem: 'Anachronistic phone' }], skipped: false, invalid: false });+ render(<EditorialCustomCheckForm onSave={() => {}} onCancel={() => {}} onPreview={onPreview} canPreview />);+ fillRequired();+ fireEvent.click(screen.getByRole('button', { name: /preview on this series/i }));+ await waitFor(() => expect(screen.getByText(/anachronistic phone/i)).toBeTruthy());+ // Editing the prompt invalidates the now-stale result.+ fireEvent.change(screen.getByLabelText('What to look for'), { target: { value: 'Flag something else' } });+ expect(screen.queryByText(/anachronistic phone/i)).toBeNull();+ });++ it('ignores an in-flight preview that resolves after the draft changed', async () => {+ let resolve;+ const onPreview = vi.fn(() => new Promise((r) => { resolve = r; }));+ render(<EditorialCustomCheckForm onSave={() => {}} onCancel={() => {}} onPreview={onPreview} canPreview />);+ fillRequired();+ fireEvent.click(screen.getByRole('button', { name: /preview on this series/i }));+ // User edits the draft while the preview is still in flight, then it resolves.+ fireEvent.change(screen.getByLabelText('What to look for'), { target: { value: 'Different prompt' } });+ resolve({ findings: [{ severity: 'high', problem: 'Stale finding' }], skipped: false, invalid: false });+ await waitFor(() => expect(onPreview).toHaveBeenCalled());+ expect(screen.queryByText(/stale finding/i)).toBeNull();+ });++ it('clears the preview when the target series changes', async () => {+ const onPreview = vi.fn().mockResolvedValue({ findings: [{ severity: 'low', problem: 'Series A finding' }], skipped: false, invalid: false });+ const { rerender } = render(+ <EditorialCustomCheckForm onSave={() => {}} onCancel={() => {}} onPreview={onPreview} canPreview previewTarget="series-a" />,+ );+ fillRequired();+ fireEvent.click(screen.getByRole('button', { name: /preview on this series/i }));+ await waitFor(() => expect(screen.getByText(/series a finding/i)).toBeTruthy());+ rerender(<EditorialCustomCheckForm onSave={() => {}} onCancel={() => {}} onPreview={onPreview} canPreview previewTarget="series-b" />);+ expect(screen.queryByText(/series a finding/i)).toBeNull();+ });});diff --git a/client/src/lib/editorialChecks.js b/client/src/lib/editorialChecks.jsindex 0f5b742c2c..66addcb53a 100644--- a/client/src/lib/editorialChecks.js+++ b/client/src/lib/editorialChecks.js@@ -48,6 +48,16 @@ export const FINDINGS_TRIAGE_ANCHOR_ID = 'editorial-findings-triage';const SEVERITY_ORDER = Object.freeze(['high', 'medium', 'low']);+// Tailwind badge classes for a finding/check severity (rose/amber/gray) — the+// shared editorial severity palette, used by the catalog card's severity badge+// and the custom-check preview's sample findings so the styling stays consistent+// across the editorial UI. Callers supply their own fallback level.+export const SEVERITY_BADGE_CLASSES = Object.freeze({+ high: 'bg-rose-500/15 text-rose-300',+ medium: 'bg-amber-500/15 text-amber-300',+ low: 'bg-gray-500/15 text-gray-300',+});+/*** Group catalog rows into ordered scope sections for the catalog view.* Returns `[{ scope, label, checks }]` in CHECK_SCOPE_ORDER, with any unknowndiff --git a/client/src/pages/PipelineEditorialChecks.jsx b/client/src/pages/PipelineEditorialChecks.jsxindex 2337032b9d..b0b057062e 100644--- a/client/src/pages/PipelineEditorialChecks.jsx+++ b/client/src/pages/PipelineEditorialChecks.jsx@@ -31,6 +31,7 @@ import {createEditorialCustomCheck,updateEditorialCustomCheck,deleteEditorialCustomCheck,+ previewEditorialCustomCheck,startEditorialChecksRun,cancelEditorialChecksRun,getEditorialChecksRunStatus,@@ -366,6 +367,21 @@ export default function PipelineEditorialChecks() {.finally(() => setFormSaving(false));};+ // Dry-run a draft against the selected series WITHOUT saving (#1607). Returns+ // the preview result (or throws, so the form's own error UI fires). Gated on a+ // selected series by the form via `canPreview`. `{ silent: true }` — the form+ // renders the error inline rather than toasting. Forwards the same AI-pass+ // provider/model override a real run uses (empty = default), so the preview's+ // context sizing + model behavior match the run the user would commit to.+ const handlePreviewCustom = useCallback(+ (values) => previewEditorialCustomCheck(seriesId, {+ ...values,+ ...(selectedProviderId ? { providerId: selectedProviderId } : {}),+ ...(selectedModel ? { model: selectedModel } : {}),+ }, { silent: true }),+ [seriesId, selectedProviderId, selectedModel],+ );+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.@@ -541,6 +557,9 @@ export default function PipelineEditorialChecks() {saving={formSaving}onSave={handleSaveCustom}onCancel={closeCustomForm}+ onPreview={handlePreviewCustom}+ canPreview={!!seriesId}+ previewTarget={seriesId}/>) : null}{checks.length === 0 ? (diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex bd6f458881..6f2c9e8e4d 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -689,6 +689,18 @@ export const deleteEditorialCustomCheck = (checkId, options = {}) =>...options,});+// Dry-run a DRAFT custom check (#1607) against a series WITHOUT saving it: runs+// the unsaved definition transiently and returns { findings, skipped, invalid }+// (sample findings only — never seeded into the review). `def` carries the same+// authored fields as create, plus an optional maxFindings cap. Pass+// { silent: true } when the caller owns its own error UI.+export const previewEditorialCustomCheck = (seriesId, def, options = {}) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/editorial/custom-checks/preview`, {+ method: 'POST',+ body: JSON.stringify(def),+ ...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/validation.js b/server/lib/validation.jsindex 2bf4fe078d..931c5b2f35 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1072,6 +1072,21 @@ export const editorialCustomCheckCreateSchema = z.object({// field is left unchanged rather than reset.export const editorialCustomCheckUpdateSchema = z.object(editorialCustomCheckShape).partial().strict();+// Dry-run preview (#1607): run an UNSAVED draft check against a series and return+// sample findings without persisting. Same authored fields as create (so the+// draft synthesizes into a runnable check), plus an optional per-run cap and the+// provider/model overrides the run route accepts.+export const editorialCustomCheckPreviewSchema = z.object({+ ...editorialCustomCheckShape,+ description: editorialCustomCheckShape.description.optional().default(''),+ scope: editorialCustomCheckShape.scope.optional().default('issue'),+ category: editorialCustomCheckShape.category.optional().default('custom'),+ severityDefault: editorialCustomCheckShape.severityDefault.optional().default('medium'),+ maxFindings: z.number().int().min(1).max(50).optional(),+ providerId: z.string().trim().max(80).optional(),+ model: z.string().trim().max(200).optional(),+}).strict();+// settings.pipelineEditorialChecks slice (validated on PUT /api/settings when// present). `checks` maps a checkId → its persisted enable/config; `customChecks`// holds the user-defined check definitions (#1346).diff --git a/server/routes/pipeline/editorial.js b/server/routes/pipeline/editorial.jsindex 0ed31ca27f..201cbee548 100644--- a/server/routes/pipeline/editorial.js+++ b/server/routes/pipeline/editorial.js@@ -13,6 +13,7 @@ import {editorialChecksRunSchema,editorialCustomCheckCreateSchema,editorialCustomCheckUpdateSchema,+ editorialCustomCheckPreviewSchema,} from '../../lib/validation.js';import {resolveCheckState,@@ -236,6 +237,22 @@ router.delete('/editorial/custom-checks/:id', asyncHandler(async (req, res) => {res.json({ deleted: true, id });}));+// Preview a DRAFT custom check transiently against a series (#1607). Synthesizes+// the UNSAVED definition, runs it against the live manuscript, and returns sample+// findings WITHOUT persisting the check or seeding the review — so the author can+// see whether a check is noisy/mis-scoped before committing it to the catalog.+router.post('/series/:id/editorial/custom-checks/preview', asyncHandler(async (req, res) => {+ const body = validateRequest(editorialCustomCheckPreviewSchema, req.body ?? {});+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });+ const { providerId, model, maxFindings, ...def } = body;+ const result = await checkRunner.previewCustomCheck(req.params.id, def, {+ providerOverride: providerId,+ modelOverride: model,+ maxFindings,+ });+ res.json(result);+}));+// 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 ?? {});diff --git a/server/routes/pipeline/editorial.test.js b/server/routes/pipeline/editorial.test.jsindex ff6cc98b61..0a40adb099 100644--- a/server/routes/pipeline/editorial.test.js+++ b/server/routes/pipeline/editorial.test.js@@ -29,8 +29,10 @@ vi.mock('../../services/pipeline/issues.js', async (importOriginal) => ({}));const startEditorialChecksRun = vi.fn(() => ({ runId: 'run-1', alreadyRunning: false }));+const previewCustomCheck = vi.fn(async () => ({ findings: [{ severity: 'medium', problem: 'x' }], skipped: false, invalid: false }));vi.mock('../../services/pipeline/editorial/checkRunner.js', () => ({startEditorialChecksRun: (...a) => startEditorialChecksRun(...a),+ previewCustomCheck: (...a) => previewCustomCheck(...a),attachClient: vi.fn(() => false),isEditorialChecksActive: vi.fn(() => false),cancelEditorialChecks: vi.fn(() => true),@@ -54,6 +56,7 @@ app.use(errorMiddleware);beforeEach(() => {settingsStore = {};startEditorialChecksRun.mockClear();+ previewCustomCheck.mockClear();getSeriesHealth.mockClear();});@@ -244,6 +247,40 @@ describe('custom checks CRUD (#1346)', () => {});});+describe('POST /api/pipeline/series/:id/editorial/custom-checks/preview (#1607)', () => {+ const draft = { label: 'Anachronisms', prompt: 'Flag modern tech.' };++ it('returns sample findings for a valid draft and forwards overrides to the runner', async () => {+ const res = await request(app)+ .post('/api/pipeline/series/s1/editorial/custom-checks/preview')+ .send({ ...draft, providerId: 'ollama', model: 'm', maxFindings: 5 });+ expect(res.status).toBe(200);+ expect(res.body.findings).toHaveLength(1);+ // The provider/model/maxFindings split off the def and forward as runner opts.+ const [seriesId, def, opts] = previewCustomCheck.mock.calls[0];+ expect(seriesId).toBe('s1');+ expect(def).toMatchObject({ label: 'Anachronisms', prompt: 'Flag modern tech.' });+ expect(def.providerId).toBeUndefined();+ expect(opts).toMatchObject({ providerOverride: 'ollama', modelOverride: 'm', maxFindings: 5 });+ });++ it('404s an unknown series before running the check', async () => {+ const res = await request(app)+ .post('/api/pipeline/series/missing/editorial/custom-checks/preview')+ .send(draft);+ expect(res.status).toBe(404);+ expect(previewCustomCheck).not.toHaveBeenCalled();+ });++ it('400s a draft missing the required prompt', async () => {+ const res = await request(app)+ .post('/api/pipeline/series/s1/editorial/custom-checks/preview')+ .send({ label: 'No prompt' });+ expect(res.status).toBe(400);+ expect(previewCustomCheck).not.toHaveBeenCalled();+ });+});+describe('editorial health (#1316)', () => {it('GET .../editorial/health returns the health payload with the default gate', async () => {const res = await request(app).get('/api/pipeline/series/s1/editorial/health');diff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.jsindex aa2da7ea60..f67b43794a 100644--- a/server/services/pipeline/editorial/checkRunner.js+++ b/server/services/pipeline/editorial/checkRunner.js@@ -19,7 +19,7 @@ import { randomUUID, createHash } from 'crypto';import { createSseRunner } from '../../../lib/sseUtils.js';import { runStagedLLM, runInlineLLM, runStageScopedInlineLLM, resolveStageContext } from '../../../lib/stageRunner.js';import { planManuscriptPass, fitContextToManuscriptFloor, estimateTokens, MANUSCRIPT_FLOOR_TOKENS } from '../../../lib/contextBudget.js';-import { getEnabledChecks, getEnabledCheckRows, getAllChecks, applySeriesCheckConfig, EDITORIAL_SOURCES, comicLetteringIssues, proseStageIssues } from '../../../lib/editorial/index.js';+import { getEnabledChecks, getEnabledCheckRows, getAllChecks, applySeriesCheckConfig, buildCustomCheck, CUSTOM_CHECK_ID_PREFIX, EDITORIAL_SOURCES, comicLetteringIssues, proseStageIssues } from '../../../lib/editorial/index.js';import { getSettings } from '../../settings.js';import { getSeries } from '../series.js';import { listIssuesForSeries } from '../issues.js';@@ -325,39 +325,24 @@ function fingerprintForCheck(check, resolved) {const EDITORIAL_OUTPUT_RESERVE_TOKENS = 2_000;/**- * Run the enabled editorial checks for a series and seed their findings into the- * manuscript review.+ * Build the shared `ctx` every editorial check reads (series, stitched+ * manuscript, canon, reverse outline, arcs, comic/storyboard projections, the+ * injected LLM callers + provider-sized manuscript chunker). Extracted from+ * runEditorialChecks so the dry-run preview path (#1607) reuses the IDENTICAL+ * context construction — same per-source I/O gating and provider-sized chunking+ * a real run would use — without persisting anything.+ *+ * Only pays the I/O an enabled check actually consumes: the `needs*` gates read+ * each check's declared `sources`, so a run of a canon-only check skips the+ * manuscript-collection / reverse-outline / issue fetches entirely.** @param {string} seriesId- * @param {object} [options]- * - checkIds: string[] — run only this subset (default: all enabled)- * - settings: object — pre-loaded settings (default: read fresh)- * - providerOverride / modelOverride — hard provider/model, forwarded to LLM checks- * - providerDefault / modelDefault — soft run-level default provider/model- * (Series Autopilot), forwarded to LLM checks (lose to a per-stage pin)- * - signal: AbortSignal — checked between checks for cancellation- * - onProgress: (event) => void — { type: 'check:start'|'check:complete', ... }- * @returns {Promise<{ runId, findings, perCheck, canceled }>}+ * @param {Array<{check: object}>} enabled — the enabled (or previewed) checks+ * @param {object} [opts] — providerOverride/Default, modelOverride/Default, signal+ * @returns {Promise<{ series, baseCtx, resolvedSources }>}*/-export async function runEditorialChecks(seriesId, options = {}) {- const { checkIds = null, providerOverride, providerDefault, modelOverride, modelDefault, signal, onProgress } = options;- const settings = options.settings || await getSettings();- const enabled = getEnabledChecks(settings, checkIds);-- const runId = randomUUID();- if (enabled.length === 0) {- return { runId, findings: [], perCheck: [], canceled: false };- }-- // Build the shared context once — every check reads from this. Only pay the- // manuscript section-collection I/O when an enabled check actually consumes- // the stitched corpus (deterministic checks like naming use only the canon).+export async function buildEditorialContext(seriesId, enabled, { providerOverride, providerDefault, modelOverride, modelDefault, signal } = {}) {const series = await getSeries(seriesId);- // Overlay this series' per-check config overrides (#1591) onto the global- // resolved config. The `needs*` gates below read only `check` (config-- // independent), so they keep using `enabled`; only the run loop consumes the- // merged config via `enabledResolved`.- const enabledResolved = applySeriesCheckConfig(enabled, series?.editorialCheckConfig);const needsManuscript = enabled.some(({ check }) => check.needsManuscript);// Reverse-outline fetch is gated on the declared source (#1296) so a run with no// scene-segmentation check pays no extra I/O — mirrors the needsManuscript gate.@@ -543,6 +528,42 @@ export async function runEditorialChecks(seriesId, options = {}) {return chunks;},};+ return { series, baseCtx, resolvedSources };+}++/**+ * Run the enabled editorial checks for a series and seed their findings into the+ * manuscript review.+ *+ * @param {string} seriesId+ * @param {object} [options]+ * - checkIds: string[] — run only this subset (default: all enabled)+ * - settings: object — pre-loaded settings (default: read fresh)+ * - providerOverride / modelOverride — hard provider/model, forwarded to LLM checks+ * - providerDefault / modelDefault — soft run-level default provider/model+ * (Series Autopilot), forwarded to LLM checks (lose to a per-stage pin)+ * - signal: AbortSignal — checked between checks for cancellation+ * - onProgress: (event) => void — { type: 'check:start'|'check:complete', ... }+ * @returns {Promise<{ runId, findings, perCheck, canceled }>}+ */+export async function runEditorialChecks(seriesId, options = {}) {+ const { checkIds = null, providerOverride, providerDefault, modelOverride, modelDefault, signal, onProgress } = options;+ const settings = options.settings || await getSettings();+ const enabled = getEnabledChecks(settings, checkIds);++ const runId = randomUUID();+ if (enabled.length === 0) {+ return { runId, findings: [], perCheck: [], canceled: false };+ }++ // Build the shared context once — every check reads from this (extracted to+ // buildEditorialContext so the dry-run preview path reuses the exact same+ // provider-sized chunking + source resolution as a real run, #1607).+ const { series, baseCtx, resolvedSources } = await buildEditorialContext(seriesId, enabled, { providerOverride, providerDefault, modelOverride, modelDefault, signal });+ // Overlay this series' per-check config overrides (#1591) onto the global+ // resolved config. The `needs*` gates inside the builder read only `check`+ // (config-independent); only the run loop consumes the merged config here.+ const enabledResolved = applySeriesCheckConfig(enabled, series?.editorialCheckConfig);const findings = [];const perCheck = [];@@ -676,6 +697,49 @@ export async function runEditorialChecks(seriesId, options = {}) {return { runId, findings, perCheck, canceled };}+/**+ * Transient preview of a DRAFT custom check (#1607). Synthesizes the unsaved+ * definition into a runnable check, runs it against the live manuscript via the+ * SAME context builder a real run uses, and returns its sample findings —+ * WITHOUT persisting the definition, seeding the manuscript review, or recording+ * a trend snapshot. Lets the author judge a check's noise/scope before committing+ * it to the catalog.+ *+ * The findings are deliberately NOT stamped with `checkId` / `sourceContentHash`+ * (those mark a finding for the review store's seed + staleness machinery, which+ * a preview must never touch). Severity is normalized to the check's native+ * default the same way the run loop does, so the preview's levels match a run.+ *+ * @param {string} seriesId+ * @param {object} def — the draft definition (label, prompt, scope, category, severityDefault)+ * @param {object} [opts] — providerOverride / modelOverride / maxFindings+ * @returns {Promise<{ findings: object[], skipped: boolean, invalid: boolean }>}+ * - invalid: the draft failed the minimum-viable shape (missing label/prompt/scope/severity)+ * - skipped: the check's gate declined (e.g. the series has no manuscript yet)+ */+export async function previewCustomCheck(seriesId, def, { providerOverride, modelOverride, maxFindings } = {}) {+ // Stamp a transient custom id so buildCustomCheck accepts the draft — its+ // validator requires the `custom.` prefix; the id is never persisted or seeded.+ const check = buildCustomCheck({ ...def, id: `${CUSTOM_CHECK_ID_PREFIX}preview` });+ if (!check) return { findings: [], skipped: false, invalid: true };++ const { baseCtx } = await buildEditorialContext(seriesId, [{ check }], { providerOverride, modelOverride });+ // Validate the (optional) per-run cap through the check's own config schema so+ // an out-of-range value falls back to the default rather than flooding.+ const config = check.configSchema.parse(Number.isInteger(maxFindings) ? { maxFindings } : {});+ const ctx = { ...baseCtx, config, severityDefault: check.severityDefault };++ if (typeof check.gate === 'function' && !check.gate(ctx)) {+ return { findings: [], skipped: true, invalid: false };+ }+ const raw = (await check.run(ctx)) || [];+ const findings = raw.map((f) => ({+ ...f,+ severity: ['high', 'medium', 'low'].includes(f.severity) ? f.severity : check.severityDefault,+ }));+ return { findings, skipped: false, invalid: false };+}+/*** Dry-run preview: which checks would run for the current settings (+ optional* subset), without executing them. Used by the run route's plan response and bydiff --git a/server/services/pipeline/editorial/checkRunner.test.js b/server/services/pipeline/editorial/checkRunner.test.jsindex 7d89ea3b38..c181f6a799 100644--- a/server/services/pipeline/editorial/checkRunner.test.js+++ b/server/services/pipeline/editorial/checkRunner.test.js@@ -76,7 +76,7 @@ vi.mock('../reverseOutline.js', () => ({ getReverseOutline: vi.fn(async () => oulet editorialState = { characters: [] };vi.mock('../editorialAnalysis.js', () => ({ getSeriesEditorial: vi.fn(async () => editorialState) }));-const { runEditorialChecks, buildEditorialCheckPlan, getReviewWithStaleness, enabledChecksConsumeReverseOutline, summarizeCheckErrors } = await import('./checkRunner.js');+const { runEditorialChecks, buildEditorialCheckPlan, getReviewWithStaleness, enabledChecksConsumeReverseOutline, summarizeCheckErrors, previewCustomCheck } = await import('./checkRunner.js');const { runStagedLLM, resolveStageContext } = await import('../../../lib/stageRunner.js');const { collectManuscriptSections } = await import('../arcPlanner.js');const { getSeriesCanon } = await import('../seriesCanon.js');@@ -474,6 +474,70 @@ describe('runEditorialChecks', () => {});});+describe('previewCustomCheck (#1607)', () => {+ const draft = {+ label: 'Anachronisms',+ description: '',+ prompt: 'Flag any modern technology that does not fit the setting.',+ scope: 'issue',+ category: 'custom',+ severityDefault: 'medium',+ };++ it('runs the draft and returns sample findings WITHOUT seeding the review', async () => {+ const result = await previewCustomCheck('s1', draft);+ expect(result.invalid).toBe(false);+ expect(result.skipped).toBe(false);+ expect(result.findings.length).toBe(1);+ // The mocked inline LLM returns a 'medium' finding; preview surfaces it as-is.+ expect(result.findings[0].problem).toMatch(/anachronism/i);+ expect(result.findings[0].severity).toBe('medium');+ // Preview is transient: the review store is never seeded, and findings carry+ // no checkId / sourceContentHash (those mark a finding for the seed machinery).+ expect(seedReviewFromFindings).not.toHaveBeenCalled();+ expect(result.findings[0].checkId).toBeUndefined();+ expect(result.findings[0].sourceContentHash).toBeUndefined();+ });++ it('normalizes an out-of-enum LLM severity to the draft default', async () => {+ const { runInlineLLM } = await import('../../../lib/stageRunner.js');+ runInlineLLM.mockResolvedValueOnce({+ runId: 'inline-run',+ content: { findings: [{ severity: 'catastrophic', issueNumber: 1, location: 'p1', problem: 'x', suggestion: 'y', anchorQuote: 'z' }] },+ });+ const result = await previewCustomCheck('s1', { ...draft, severityDefault: 'high' });+ expect(result.findings[0].severity).toBe('high');+ });++ it('reports invalid for a draft missing the required prompt', async () => {+ const result = await previewCustomCheck('s1', { ...draft, prompt: '' });+ expect(result.invalid).toBe(true);+ expect(result.findings).toEqual([]);+ expect(seedReviewFromFindings).not.toHaveBeenCalled();+ });++ it('reports skipped when the series has no manuscript (gate declines)', async () => {+ collectManuscriptSections.mockResolvedValueOnce([]);+ const result = await previewCustomCheck('s1', draft);+ expect(result.skipped).toBe(true);+ expect(result.findings).toEqual([]);+ });++ it('honors a maxFindings cap', async () => {+ const { runInlineLLM } = await import('../../../lib/stageRunner.js');+ runInlineLLM.mockResolvedValueOnce({+ runId: 'inline-run',+ content: { findings: [+ { severity: 'low', issueNumber: 1, location: 'a', problem: 'p1', suggestion: 's', anchorQuote: 'q1' },+ { severity: 'low', issueNumber: 1, location: 'b', problem: 'p2', suggestion: 's', anchorQuote: 'q2' },+ { severity: 'low', issueNumber: 1, location: 'c', problem: 'p3', suggestion: 's', anchorQuote: 'q3' },+ ] },+ });+ const result = await previewCustomCheck('s1', draft, { maxFindings: 2 });+ expect(result.findings.length).toBe(2);+ });+});+describe('summarizeCheckErrors (#1573)', () => {it('extracts the count + checkIds of errored perCheck entries', () => {const perCheck = [