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: editorial health score + revision-trend tracking (#1316)
Adam Eivyf24e4869adb2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 1c8b07772a..6cbdcaa45b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **[issue-1316] Editorial health score + revision-trend tracking — *manage* the draft, not just receive findings.** A new **Editorial Health** panel (Create → Editorial Checks, alongside the findings triage) turns the point-in-time manuscript-review findings into a metric you can steer by. A transparent, deterministic **health score** (0–100, per series with a per-issue drill-down) is computed from the OPEN findings weighted by severity — `100 − Σ weight(severity)` with published weights (high 12 / medium 5 / low 1), so it's never a black box; accepted (fixed) and dismissed (waived) findings cost nothing. A **revision-trend ledger** snapshots the open-finding counts (by severity + category) on each editorial-checks / completeness run — the run is the revision boundary — so the panel renders a **score sparkline** across revisions, the most-recent-revision **delta**, and per-category **regressions** (a category that got *worse* after an edit pass). A configurable **readiness gate** ("no open high findings" by default, or the stricter "no high or medium", or "none") is the convergence signal the UI shows as **Ready / Not ready** *and* that the **autopilot editorial loop** now reads as a final gate (`editorialHealthGate`): after both editorial passes seed their findings, autopilot pauses with the residual blockers if the manuscript isn't clean — catching a blocker the registry checks surface *after* the completeness loop converged. The trend ledger is install-local telemetry (`data/pipeline-editorial-health/{seriesId}.json`, not synced); the score/readiness are derived live from the synced review. Scoring is pure + unit-tested. (`server/services/pipeline/editorialScore.js`, `server/routes/pipeline/editorial.js`, `server/services/pipeline/{editorial/checkRunner,manuscriptCompletenessRunner,seriesAutopilot}.js`, `client/src/components/pipeline/editorial/EditorialHealthPanel.jsx`, `client/src/lib/editorialHealth.js`, Part of #1283, #1316)+- **[issue-1315] Storyboard shots now record camera framing + screen direction, and a new editorial check catches film-grammar continuity errors before render.** Each storyboard shot gains two film-grammar fields — **shot type** (extreme-wide / wide / medium / close / extreme-close / over-the-shoulder / two-shot / POV) and **screen direction** (the side the subject faces or moves: left / right / neutral) — captured by the scene extractor (the teleplay→scenes prompt now asks the model to tag them) and carried on the shot record. A new deterministic **Storyboard shot continuity** check (Create → Editorial Checks) reads those fields and flags two classic film-grammar mistakes *before* you spend render time on a clip: a **180-degree-rule axis reversal** — a shot that continues from an earlier one but flips the subject to the opposite side of the screen, so they appear to jump sides across the cut — and **shot-type monotony**, a scene whose shots all share one framing and read as flat, slideshow coverage with no establishing wide or punch-in. Findings render as `Continuity` notes anchored to the offending issue + scene, and (being deterministic) need no LLM. Both fields are backward-compatible and default to "not captured," so older storyboards simply aren't flagged until re-extracted; the extraction-prompt change migrates for existing installs (114). Eyeline-match and appearance/prop continuity (which need a vision/LLM pass) and a hard pre-render render-gate are tracked as follow-ups. (`server/lib/shotGrammar.js`, `server/lib/sceneExtractor.js`, `server/lib/editorial/shotContinuity.js`, `server/lib/editorial/checkRegistry.js`, `server/services/pipeline/editorial/checkRunner.js`, `scripts/migrations/114-extract-scenes-shot-grammar.js`, #1315)- **Digital Twin federation now syncs your *whole* identity — taste profile, documents, and autobiography — not just the four core files.** The `digitalTwin` sync category only ever transferred `identity` / `chronotype` / `longevity` / `feedback`, so a peer could read **"Digital Twin: synced"** while your taste questionnaire, soul documents, and autobiography stories never crossed between machines (they were never wired into the snapshot at all). The snapshot now covers everything under `data/digital-twin/`: the **taste profile** (responses union per section by `questionId`, LWW — answers given on either machine survive), **meta.json** (documents/test-histories/personas union by id, enrichment deep-unioned, settings fill-missing), the **`.md` documents** themselves (shipped by filename, written **add-only** so a local doc is never overwritten — with a path-traversal guard on peer-supplied names), and the **autobiography** (stories union by id with LWW, prompt schedule stays machine-local). The merge is additive and key-presence-guarded, so an older peer that still sends only the four legacy keys can't blank out the new data, and no schemaVersions gate is needed (digitalTwin stays unversioned). The "Digital Twin" sync-category description in the Instances UI now reflects the full coverage. (`server/services/digital-twin-sync.js`, `server/services/dataSync.js`, `client/src/pages/Instances.jsx`)diff --git a/client/src/components/pipeline/editorial/EditorialHealthPanel.jsx b/client/src/components/pipeline/editorial/EditorialHealthPanel.jsxnew file mode 100644index 0000000000..ab1e1bef34--- /dev/null+++ b/client/src/components/pipeline/editorial/EditorialHealthPanel.jsx@@ -0,0 +1,190 @@+/**+ * Editorial health panel (#1316) for the Editorial Checks page — turns the+ * point-in-time findings into something the author can MANAGE the draft with:+ *+ * - the transparent severity-weighted HEALTH SCORE (per series, with a per-issue+ * drill-down), and the READINESS signal under the configured gate;+ * - the REVISION TREND — a score sparkline across the recorded runs plus the+ * most-recent-revision delta, and the per-category REGRESSIONS (a category+ * that got worse after an edit pass).+ *+ * Read-only over the same manuscript-review findings the triage view shows: the+ * server (`getEditorialHealth`) computes the score + trend; this renders it. The+ * readiness gate is the one editable control (it drives the autopilot's+ * convergence gate too). Refetches when `refreshKey` changes (e.g. after a run+ * completes), so the score reflects the freshest review.+ */+import { useCallback, useEffect, useState } from 'react';+import { Activity, Loader2, TrendingUp, TrendingDown } from 'lucide-react';+import toast from '../../ui/Toast';+import { getEditorialHealth, setEditorialReadinessGate } from '../../../services/api';+import {+ scoreBand,+ deltaDisplay,+ sparklineGeometry,+ orderedCategories,+ SEVERITY_ORDER,+ SEVERITY_LABELS,+ READINESS_GATE_LABELS,+ READINESS_GATE_ORDER,+} from '../../../lib/editorialHealth';++const SEVERITY_DOT = { high: 'bg-rose-400', medium: 'bg-amber-400', low: 'bg-gray-400' };++function SeverityBreakdown({ openBySeverity }) {+ const any = SEVERITY_ORDER.some((s) => (openBySeverity?.[s] || 0) > 0);+ if (!any) return <span className="text-[11px] text-port-success">No open findings</span>;+ return (+ <span className="flex items-center gap-3">+ {SEVERITY_ORDER.map((sev) => (+ <span key={sev} className="flex items-center gap-1 text-[11px] text-gray-400">+ <span className={`h-2 w-2 rounded-full ${SEVERITY_DOT[sev]}`} />+ {openBySeverity?.[sev] || 0} {SEVERITY_LABELS[sev].toLowerCase()}+ </span>+ ))}+ </span>+ );+}++function Sparkline({ points }) {+ const { points: poly, coords } = sparklineGeometry(points, { width: 140, height: 32, pad: 3 });+ if (!poly) return <span className="text-[11px] text-gray-600">Run editorial checks to start the trend</span>;+ const last = coords[coords.length - 1];+ return (+ <svg width={140} height={32} className="overflow-visible" role="img" aria-label="Editorial health score trend">+ <polyline points={poly} fill="none" stroke="currentColor" strokeWidth="1.5" className="text-port-accent" />+ <circle cx={last.x} cy={last.y} r="2.5" className="fill-port-accent" />+ </svg>+ );+}++export default function EditorialHealthPanel({ seriesId, refreshKey = 0 }) {+ const [health, setHealth] = useState(null);+ const [loading, setLoading] = useState(false);+ const [savingGate, setSavingGate] = useState(false);++ const load = useCallback((id) => {+ if (!id) { setHealth(null); return; }+ setLoading(true);+ // getEditorialHealth has no silent option here — request() toasts on failure;+ // just clear + swallow so the panel degrades to its empty state.+ getEditorialHealth(id)+ .then((h) => setHealth(h && typeof h === 'object' ? h : null))+ .catch(() => setHealth(null))+ .finally(() => setLoading(false));+ }, []);++ useEffect(() => { load(seriesId); }, [seriesId, refreshKey, load]);++ const onGateChange = (gate) => {+ setSavingGate(true);+ // Optimistic — reflect the picked gate, re-derive readiness on the refetch.+ setHealth((h) => (h ? { ...h, gate } : h));+ setEditorialReadinessGate(gate, { silent: true })+ .then(() => load(seriesId))+ .catch((err) => toast.error(err.message || 'Failed to update readiness gate'))+ .finally(() => setSavingGate(false));+ };++ if (!seriesId) return null;+ if (loading && !health) {+ return (+ <p className="flex items-center gap-2 text-sm text-gray-400">+ <Loader2 size={16} className="animate-spin" /> Loading editorial health…+ </p>+ );+ }+ if (!health) return null;++ const band = scoreBand(health.score);+ const delta = deltaDisplay(health.trend?.delta);+ const regressions = Array.isArray(health.trend?.regressions) ? health.trend.regressions : [];+ const categories = orderedCategories(health.openByCategory);+ const hasTrend = (health.trend?.points || []).length > 0;++ return (+ <section className="space-y-3 rounded-lg border border-port-border bg-port-card p-3">+ <div className="flex items-center justify-between gap-2">+ <h2 className="flex items-center gap-1.5 text-sm font-semibold uppercase tracking-wide text-gray-400">+ <Activity size={15} className="text-port-accent" /> Editorial Health+ </h2>+ {health.ready ? (+ <span className="rounded-full bg-port-success/15 px-2 py-0.5 text-[10px] font-medium text-port-success">Ready</span>+ ) : (+ <span className="rounded-full bg-port-warning/15 px-2 py-0.5 text-[10px] font-medium text-port-warning">Not ready</span>+ )}+ </div>++ {/* Score + breakdown */}+ <div className="flex flex-wrap items-end justify-between gap-3">+ <div>+ <div className="flex items-baseline gap-2">+ <span className={`text-3xl font-bold ${band.tone}`}>{health.score}</span>+ <span className="text-xs text-gray-500">/ 100 · {band.label}</span>+ {hasTrend ? (+ <span className={`flex items-center gap-0.5 text-xs ${delta.tone}`} title="Change since the previous revision">+ {delta.text}+ </span>+ ) : null}+ </div>+ <div className="mt-1.5 h-1.5 w-40 overflow-hidden rounded-full bg-port-border">+ <div className={`h-full ${band.bar}`} style={{ width: `${Math.max(0, Math.min(100, health.score))}%` }} />+ </div>+ <div className="mt-1.5"><SeverityBreakdown openBySeverity={health.openBySeverity} /></div>+ </div>+ <div className="text-right">+ <span className="block text-[10px] uppercase tracking-wide text-gray-600">Score trend</span>+ <span className="text-port-accent"><Sparkline points={health.trend?.points} /></span>+ </div>+ </div>++ {/* Readiness gate control — also drives the autopilot convergence gate. */}+ <div className="flex flex-wrap items-center gap-2 border-t border-port-border/60 pt-2.5">+ <label htmlFor="eh-gate" className="text-[11px] text-gray-500">Ready when:</label>+ <select+ id="eh-gate"+ value={READINESS_GATE_ORDER.includes(health.gate) ? health.gate : 'noOpenHigh'}+ onChange={(e) => onGateChange(e.target.value)}+ disabled={savingGate}+ className="rounded border border-port-border bg-port-bg px-2 py-1 text-[11px] text-gray-200 focus:border-port-accent focus:outline-none disabled:opacity-50"+ >+ {READINESS_GATE_ORDER.map((g) => (+ <option key={g} value={g}>{READINESS_GATE_LABELS[g]}</option>+ ))}+ </select>+ {savingGate ? <Loader2 size={12} className="animate-spin text-gray-500" /> : null}+ </div>++ {/* Per-category breakdown + regressions */}+ {categories.length ? (+ <div className="border-t border-port-border/60 pt-2.5">+ <span className="block text-[10px] uppercase tracking-wide text-gray-600">Open by category</span>+ <ul className="mt-1 flex flex-wrap gap-x-3 gap-y-1">+ {categories.map(({ category, count }) => {+ const regressed = regressions.find((r) => r.category === category);+ return (+ <li key={category} className="flex items-center gap-1 text-[11px] text-gray-400">+ <span className="text-gray-300">{category}</span>+ <span className="text-gray-500">{count}</span>+ {regressed ? (+ <span className="flex items-center gap-0.5 text-port-error" title={`Regressed: ${regressed.from} → ${regressed.to} since the previous revision`}>+ <TrendingUp size={11} />+ {regressed.from}→{regressed.to}+ </span>+ ) : null}+ </li>+ );+ })}+ </ul>+ </div>+ ) : null}++ {/* A clean run that improved on the prior revision gets a positive note. */}+ {!regressions.length && hasTrend && (health.trend?.delta || 0) > 0 ? (+ <p className="flex items-center gap-1 text-[11px] text-port-success">+ <TrendingDown size={11} className="rotate-180" /> No category regressed since the previous revision.+ </p>+ ) : null}+ </section>+ );+}diff --git a/client/src/components/pipeline/editorial/EditorialHealthPanel.test.jsx b/client/src/components/pipeline/editorial/EditorialHealthPanel.test.jsxnew file mode 100644index 0000000000..185e98e111--- /dev/null+++ b/client/src/components/pipeline/editorial/EditorialHealthPanel.test.jsx@@ -0,0 +1,85 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, waitFor, fireEvent } from '@testing-library/react';+import EditorialHealthPanel from './EditorialHealthPanel';++const getEditorialHealth = vi.fn();+const setEditorialReadinessGate = vi.fn();+vi.mock('../../../services/api', () => ({+ getEditorialHealth: (...a) => getEditorialHealth(...a),+ setEditorialReadinessGate: (...a) => setEditorialReadinessGate(...a),+}));+vi.mock('../../ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));++const health = (over = {}) => ({+ seriesId: 'ser-1',+ score: 83,+ ready: false,+ open: 3,+ openBySeverity: { high: 1, medium: 1, low: 1 },+ openByCategory: { continuity: 2, pacing: 1 },+ gate: 'noOpenHigh',+ weights: { high: 12, medium: 5, low: 1 },+ perIssue: [],+ trend: {+ points: [{ score: 70, open: 6 }, { score: 83, open: 3 }],+ regressions: [],+ delta: 13,+ },+ ...over,+});++beforeEach(() => {+ getEditorialHealth.mockReset();+ setEditorialReadinessGate.mockReset();+});++describe('EditorialHealthPanel', () => {+ it('renders nothing without a series', () => {+ const { container } = render(<EditorialHealthPanel seriesId="" />);+ expect(container.firstChild).toBeNull();+ expect(getEditorialHealth).not.toHaveBeenCalled();+ });++ it('shows the score, readiness, severity breakdown and trend delta', async () => {+ getEditorialHealth.mockResolvedValue(health());+ render(<EditorialHealthPanel seriesId="ser-1" />);+ expect(await screen.findByText('83')).toBeTruthy();+ expect(screen.getByText('Not ready')).toBeTruthy();+ expect(screen.getByText('+13')).toBeTruthy();+ expect(screen.getByText(/1 high/)).toBeTruthy();+ });++ it('flags a category that regressed', async () => {+ getEditorialHealth.mockResolvedValue(health({+ trend: { points: [{ score: 90 }, { score: 70 }], regressions: [{ category: 'continuity', from: 1, to: 2 }], delta: -20 },+ }));+ render(<EditorialHealthPanel seriesId="ser-1" />);+ expect(await screen.findByText('1→2')).toBeTruthy();+ });++ it('marks ready when the gate is satisfied', async () => {+ getEditorialHealth.mockResolvedValue(health({ ready: true, score: 100, openBySeverity: { high: 0, medium: 0, low: 0 }, open: 0 }));+ render(<EditorialHealthPanel seriesId="ser-1" />);+ expect(await screen.findByText('Ready')).toBeTruthy();+ expect(screen.getByText('No open findings')).toBeTruthy();+ });++ it('persists a readiness-gate change and refetches', async () => {+ getEditorialHealth.mockResolvedValue(health());+ setEditorialReadinessGate.mockResolvedValue({ readinessGate: 'noOpenHighOrMedium' });+ render(<EditorialHealthPanel seriesId="ser-1" />);+ await screen.findByText('83');+ fireEvent.change(screen.getByLabelText('Ready when:'), { target: { value: 'noOpenHighOrMedium' } });+ await waitFor(() => expect(setEditorialReadinessGate).toHaveBeenCalledWith('noOpenHighOrMedium', { silent: true }));+ // Refetch fired after the save (initial mount + post-save = 2 reads).+ await waitFor(() => expect(getEditorialHealth).toHaveBeenCalledTimes(2));+ });++ it('refetches when refreshKey changes', async () => {+ getEditorialHealth.mockResolvedValue(health());+ const { rerender } = render(<EditorialHealthPanel seriesId="ser-1" refreshKey={0} />);+ await screen.findByText('83');+ rerender(<EditorialHealthPanel seriesId="ser-1" refreshKey={1} />);+ await waitFor(() => expect(getEditorialHealth).toHaveBeenCalledTimes(2));+ });+});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex ff955b9ea9..df4978f23d 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -99,6 +99,7 @@ grep -i "what you want to do" client/src/lib/README.md| `pitchDetect.js` | Dependency-free vocal pitch-detection core for the song system (tuner / color-match / sing-to-score). `detectFrequency(frame, { sampleRate })` → `{ hz, clarity }` (McLeod NSDF; clarity gate rejects silence/noise); `frequencyToNote(hz, { a4 })` → `{ letter, accidental, octave, step, cents }` (cents ∈ [-50,+50], sharp positive; `step` reuses `scoreNotation`'s `diatonicStep` so detected notes align with the renderer); `noteToFrequency(note, { a4 })` inverse (color-match targets); `createPitchTracker(analyser, { onUpdate })` → `{ stop }` rAF/interval loop with median+EMA smoothing to kill octave jumps; `tuningQuality(cents)` → `{ level, label }` buckets a cents deviation into `in-tune`/`close`/`off`/`none` (thresholds `IN_TUNE_CENTS`/`CLOSE_CENTS`) for the tuner color readout. || `universeBuilderExpand.js` | `mergeExpandIntoDraft(draft, result)` — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with `kind` precedence, canon dedupe by name/slugline/alias). Also exports `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` for callers that need the building blocks (per-category Generate, save-time refetch+merge). || `editorialChecks.js` | Pure helpers for the Editorial Checks page (`/pipeline/editorial-checks`, #1285): `groupChecksByScope(checks)` buckets catalog rows into ordered Noun/Scene/Issue/Series sections; `groupFindingsByCheck(comments, rowsById)` groups check-sourced review comments per check with open/total + severity counts; `openFindingsTotal(groups)` sums open findings; `findingManuscriptLink(seriesId, comment)` builds the `?comment=` deep-link into the manuscript editor; plus `scopeLabel` and the `CHECK_SCOPE_ORDER`/`CHECK_SCOPE_LABELS` tables. No React/window — the page and its tests share them. |+| `editorialHealth.js` | Pure presentation helpers for the editorial health panel (`/pipeline/editorial-checks`, #1316): `scoreBand(score)` bands a 0–100 health score into a label + Tailwind tone; `deltaDisplay(delta)` formats the revision-to-revision score change (arrow + tone); `sparklineGeometry(points, box)` projects the trend's score points into SVG polyline coords; `orderedCategories(openByCategory)` sorts the per-category open-finding breakdown; plus the `SEVERITY_ORDER`/`SEVERITY_LABELS` and `READINESS_GATE_LABELS`/`READINESS_GATE_ORDER` tables. No React/window — the panel and its tests share them. || `metronome.js` | Sample-accurate Web Audio metronome — the shared timing grid for the song system and first consumer of the song `tempo` field. `createMetronome({ bpm, beatsPerBar, countInBars, onBeat, onCountInComplete })` lookahead-schedules accented click tones on the shared `AudioContext` clock (same pattern as `songPlayback.js`), emits `{ beat, bar, accent, countIn, whenAudioTime }` per beat (the beat-clock callback color-match/sing-to-score subscribe to), and tears down all timers on `stop()`. Plus `clampBpm` (20–320), `secondsPerBeat`, `timeSignatureFromScore`, `beatDescriptor`. || `pianoKeyboard.js` | Piano-keyboard geometry for the song system's Synthesia-style piano-roll visualizer (`<PianoRoll>`). Pure math, no canvas/React. `keyboardRange(midis, { minSemitones })` → `{ lowMidi, highMidi }` padded out to whole C–B octaves (min 2) so the keyboard always starts on a C / ends on a B and never collapses for a one-note part; `buildKeyboardLayout({ lowMidi, highMidi, width })` → `{ keys:[{midi,isBlack,x,w}], whiteWidth, blackWidth }` (white keys tiled edge-to-edge, black keys overlaid centered on the boundary, narrower); plus `isBlackKey(midi)`, `midiNoteName(midi)` (sharps spelling), and the `BLACK_KEY_RATIO`/`BLACK_KEY_HEIGHT_RATIO` constants. Pairs with `scorePlayback`'s per-note `midi` field. || `scoreNotation.js` | Parser for the PortOS lead-sheet notation — a dependency-free text format for melody + chords + lyrics that the `<ScoreSheet>` SVG renderer draws (no abcjs / VexFlow / OSMD). `parseScore(text)` → `{ clef, key, keySig, time, tempo, measures, errors }`; plus `parsePitch`, `diatonicStep`, `durationBeats`, `keySignature`, `DURATIONS`, and `scoreHasMusic(text)`. Forgiving: bad tokens collect into `errors` and are skipped, never thrown. Pure — the renderer only does geometry. |diff --git a/client/src/lib/editorialHealth.js b/client/src/lib/editorialHealth.jsnew file mode 100644index 0000000000..27396a0c3d--- /dev/null+++ b/client/src/lib/editorialHealth.js@@ -0,0 +1,65 @@+// Pure presentation helpers for the editorial health panel (#1316) — score+// banding, trend sparkline geometry, and severity/category ordering. No React,+// no window: the panel component and its unit tests both consume these.++export const SEVERITY_ORDER = Object.freeze(['high', 'medium', 'low']);+export const SEVERITY_LABELS = Object.freeze({ high: 'High', medium: 'Medium', low: 'Low' });++// Readiness-gate display labels (mirrors the server READINESS_GATES enum).+export const READINESS_GATE_LABELS = Object.freeze({+ noOpenHigh: 'No open high findings',+ noOpenHighOrMedium: 'No open high or medium findings',+ none: 'No gate (always ready)',+});+export const READINESS_GATE_ORDER = Object.freeze(['noOpenHigh', 'noOpenHighOrMedium', 'none']);++// Band a 0..100 health score into a label + Tailwind token class. The cutoffs+// are presentation-only (the score itself is the authority): a draft with no+// open high findings lands ≥ ~88 under the default weights, so the bands read+// as "clean / minor nits / needs work / rough".+export function scoreBand(score) {+ const s = Number.isFinite(score) ? score : 0;+ if (s >= 90) return { label: 'Clean', tone: 'text-port-success', bar: 'bg-port-success' };+ if (s >= 70) return { label: 'Minor', tone: 'text-port-success', bar: 'bg-port-success' };+ if (s >= 40) return { label: 'Needs work', tone: 'text-port-warning', bar: 'bg-port-warning' };+ return { label: 'Rough', tone: 'text-port-error', bar: 'bg-port-error' };+}++// A delta's display: sign, arrow, and tone. Positive = improving (score went up+// between the two most recent revisions). Zero is neutral.+export function deltaDisplay(delta) {+ const d = Number.isFinite(delta) ? delta : 0;+ if (d > 0) return { text: `+${d}`, arrow: '▲', tone: 'text-port-success' };+ if (d < 0) return { text: `${d}`, arrow: '▼', tone: 'text-port-error' };+ return { text: '0', arrow: '→', tone: 'text-gray-400' };+}++/**+ * Project a trend's score points into SVG polyline coordinates within a+ * `width × height` box. Returns `{ points: "x,y x,y …", coords: [{x,y,score}] }`.+ * Scores are mapped 0..100 → bottom..top. A single point sits at the right edge;+ * an empty series yields empty geometry (the caller renders a placeholder).+ */+export function sparklineGeometry(points = [], { width = 120, height = 28, pad = 2 } = {}) {+ const list = Array.isArray(points) ? points.filter((p) => Number.isFinite(p?.score)) : [];+ if (!list.length) return { points: '', coords: [] };+ const innerW = Math.max(1, width - pad * 2);+ const innerH = Math.max(1, height - pad * 2);+ const span = Math.max(1, list.length - 1);+ const coords = list.map((p, i) => {+ const x = pad + (list.length === 1 ? innerW : (i / span) * innerW);+ // Score 0 → bottom (height-pad), 100 → top (pad).+ const y = pad + (1 - Math.max(0, Math.min(100, p.score)) / 100) * innerH;+ return { x: Math.round(x * 10) / 10, y: Math.round(y * 10) / 10, score: p.score };+ });+ return { points: coords.map((c) => `${c.x},${c.y}`).join(' '), coords };+}++// Order an openByCategory map into `[{ category, count }]` sorted by count desc+// then name, dropping zero/empty buckets. Used for the per-category breakdown.+export function orderedCategories(openByCategory = {}) {+ return Object.entries(openByCategory || {})+ .filter(([, count]) => Number.isFinite(count) && count > 0)+ .map(([category, count]) => ({ category, count }))+ .sort((a, b) => b.count - a.count || a.category.localeCompare(b.category));+}diff --git a/client/src/lib/editorialHealth.test.js b/client/src/lib/editorialHealth.test.jsnew file mode 100644index 0000000000..8bafa9b711--- /dev/null+++ b/client/src/lib/editorialHealth.test.js@@ -0,0 +1,73 @@+import { describe, it, expect } from 'vitest';+import {+ scoreBand,+ deltaDisplay,+ sparklineGeometry,+ orderedCategories,+} from './editorialHealth.js';++describe('scoreBand', () => {+ it('bands scores into label + tone', () => {+ expect(scoreBand(100).label).toBe('Clean');+ expect(scoreBand(75).label).toBe('Minor');+ expect(scoreBand(50).label).toBe('Needs work');+ expect(scoreBand(10).label).toBe('Rough');+ });++ it('tolerates a non-finite score (treats as 0 → Rough)', () => {+ expect(scoreBand(undefined).label).toBe('Rough');+ });+});++describe('deltaDisplay', () => {+ it('marks an improving delta positive', () => {+ const d = deltaDisplay(10);+ expect(d.text).toBe('+10');+ expect(d.arrow).toBe('▲');+ });++ it('marks a regressing delta negative', () => {+ const d = deltaDisplay(-8);+ expect(d.text).toBe('-8');+ expect(d.arrow).toBe('▼');+ });++ it('is neutral at zero', () => {+ expect(deltaDisplay(0).arrow).toBe('→');+ });+});++describe('sparklineGeometry', () => {+ it('maps a higher score to a higher point (smaller y)', () => {+ const { coords } = sparklineGeometry([{ score: 20 }, { score: 90 }], { width: 100, height: 30, pad: 0 });+ expect(coords).toHaveLength(2);+ expect(coords[1].y).toBeLessThan(coords[0].y); // 90 plotted above 20+ expect(coords[0].x).toBe(0);+ expect(coords[1].x).toBe(100);+ });++ it('returns empty geometry for no points', () => {+ expect(sparklineGeometry([]).points).toBe('');+ expect(sparklineGeometry(undefined).coords).toEqual([]);+ });++ it('drops non-finite scores', () => {+ const { coords } = sparklineGeometry([{ score: 50 }, { score: null }]);+ expect(coords).toHaveLength(1);+ });+});++describe('orderedCategories', () => {+ it('sorts by count desc then name, dropping zero buckets', () => {+ expect(orderedCategories({ pacing: 1, continuity: 3, naming: 0, style: 1 })).toEqual([+ { category: 'continuity', count: 3 },+ { category: 'pacing', count: 1 },+ { category: 'style', count: 1 },+ ]);+ });++ it('returns empty for an empty/absent map', () => {+ expect(orderedCategories()).toEqual([]);+ expect(orderedCategories({})).toEqual([]);+ });+});diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 4394c6f55f..446c94a3bf 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -65,6 +65,7 @@ export * from './voiceLabel.js';export * from './cityPlaybackFrame.js';export * from './colorMatch.js';export * from './editorialChecks.js';+export * from './editorialHealth.js';export * from './metronome.js';export * from './pianoKeyboard.js';export * from './pitchDetect.js';diff --git a/client/src/pages/PipelineEditorialChecks.jsx b/client/src/pages/PipelineEditorialChecks.jsxindex 8e632069e5..86949f3f11 100644--- a/client/src/pages/PipelineEditorialChecks.jsx+++ b/client/src/pages/PipelineEditorialChecks.jsx@@ -18,6 +18,7 @@ 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 EditorialHealthPanel from '../components/pipeline/editorial/EditorialHealthPanel';import { groupChecksByScope } from '../lib/editorialChecks';import { usePipelineProgress } from '../hooks/usePipelineProgress';import {@@ -45,6 +46,10 @@ export default function PipelineEditorialChecks() {const seriesId = searchParams.get('series') || '';const [comments, setComments] = useState([]);const [loadingFindings, setLoadingFindings] = useState(false);+ // Bumped whenever the findings are (re)loaded so the health panel refetches+ // its score/trend in lockstep — a run that seeds new findings also moves the+ // health score + records a trend snapshot server-side.+ const [healthRefresh, setHealthRefresh] = useState(0);const [runActive, setRunActive] = useState(false);const [runStarting, setRunStarting] = useState(false);@@ -90,7 +95,12 @@ export default function PipelineEditorialChecks() {getPipelineManuscriptReview(id).then((review) => { if (activeSeriesRef.current === id) setComments(Array.isArray(review?.comments) ? review.comments : []); }).catch(() => { if (activeSeriesRef.current === id) setComments([]); })- .finally(() => { if (activeSeriesRef.current === id) setLoadingFindings(false); });+ .finally(() => {+ if (activeSeriesRef.current === id) {+ setLoadingFindings(false);+ setHealthRefresh((n) => n + 1); // re-pull the health score/trend in lockstep+ }+ });}, []);useEffect(() => {@@ -392,10 +402,15 @@ export default function PipelineEditorialChecks() {<h2 className="text-sm font-semibold uppercase tracking-wide text-gray-400">Findings</h2>{!seriesId ? (<p className="rounded-lg border border-dashed border-port-border p-4 text-center text-xs text-gray-500">Select a series to view its findings.</p>- ) : loadingFindings ? (- <p className="flex items-center gap-2 text-sm text-gray-400"><Loader2 size={16} className="animate-spin" /> Loading findings…</p>) : (- <EditorialFindingsTriage seriesId={seriesId} comments={comments} checksById={checksById} />+ <>+ <EditorialHealthPanel seriesId={seriesId} refreshKey={healthRefresh} />+ {loadingFindings ? (+ <p className="flex items-center gap-2 text-sm text-gray-400"><Loader2 size={16} className="animate-spin" /> Loading findings…</p>+ ) : (+ <EditorialFindingsTriage seriesId={seriesId} comments={comments} checksById={checksById} />+ )}+ </>)}</section></div>diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex 42a1bdaebb..efb97175d3 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -698,6 +698,24 @@ export const cancelEditorialChecksRun = (seriesId, options = {}) =>export const editorialChecksRunSseUrl = (seriesId) =>`/api/pipeline/series/${encodeURIComponent(seriesId)}/editorial/checks/run/progress`;+// ---- Editorial health score + revision trend (#1316) ----+// The transparent severity-weighted health score (per series + per issue), the+// readiness signal, and the revision trend + per-category regressions:+// { seriesId, score, ready, open, openBySeverity, openByCategory, gate, weights,+// perIssue: [...], trend: { points, regressions, latest, previous, delta } }.+export const getEditorialHealth = (seriesId, options = {}) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/editorial/health`, options);++// Set the editorial-health readiness gate ('noOpenHigh' | 'noOpenHighOrMedium' |+// 'none') the autopilot loop + UI read as "manuscript clean". Returns the+// persisted { readinessGate }.+export const setEditorialReadinessGate = (readinessGate, options = {}) =>+ request('/pipeline/editorial/readiness-gate', {+ method: 'PATCH',+ body: JSON.stringify({ readinessGate }),+ ...options,+ });+// ---- Reverse Outline (scene segmentation + plotline tagging) ----// The stored outline: { plotlines, scenes, stale, status }. `status:'none'`// when never generated, `'no-content'` shell while nothing is drafted yet.diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.jsindex 481a75da2c..1c4a3c2e95 100644--- a/server/lib/editorial/checkRegistry.js+++ b/server/lib/editorial/checkRegistry.js@@ -4066,6 +4066,15 @@ export const readChecksSlice = (settings) => {return slice && typeof slice === 'object' && !Array.isArray(slice) ? slice : {};};+// The editorial-health readiness gate (#1316) the autopilot loop + UI read as+// "manuscript clean". Returns the raw stored value (or null) — the caller+// resolves an unknown/absent value to the default via `resolveReadinessGate` in+// editorialScore.js (kept there so the gate vocabulary lives with the scorer).+export const readReadinessGate = (settings) => {+ const gate = settings?.pipelineEditorialChecks?.readinessGate;+ return typeof gate === 'string' && gate ? gate : null;+};+/*** Merge the static registry with persisted per-check state from settings.* Returns one row per registered check:diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 3498ebcb4c..1aca88f376 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1076,9 +1076,14 @@ export const editorialCustomCheckUpdateSchema = z.object(editorialCustomCheckSha// peer compatible — a def carrying a future field (or a newer scope value) must// not 400 an unrelated settings save. `buildCustomCheck`/`isValidCustomCheckDef`// decide at read time which stored defs are actually runnable.+// `readinessGate` (#1316) is the editorial health convergence gate the autopilot+// loop + UI read as "manuscript clean": 'noOpenHigh' (default), the stricter+// 'noOpenHighOrMedium', or 'none' (disable). Optional + additive, so older peers+// and a never-configured install fall through to the service default.export const pipelineEditorialChecksSettingsSchema = z.object({checks: z.record(editorialCheckConfigSchema).optional(),customChecks: z.array(z.object({}).passthrough()).optional(),+ readinessGate: z.enum(['noOpenHigh', 'noOpenHighOrMedium', 'none']).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 dea84ba1f8..a276d638e4 100644--- a/server/routes/pipeline/editorial.js+++ b/server/routes/pipeline/editorial.js@@ -17,6 +17,7 @@ import {import {resolveCheckState,readChecksSlice,+ readReadinessGate,getCheckById,readCustomCheckDefs,isCustomCheckId,@@ -27,6 +28,7 @@ import * as issuesSvc from '../../services/pipeline/issues.js';import * as editorialAnalysis from '../../services/pipeline/editorialAnalysis.js';import * as editorialRunner from '../../services/pipeline/editorialAnalysisRunner.js';import * as checkRunner from '../../services/pipeline/editorial/checkRunner.js';+import { getSeriesHealth, READINESS_GATES, DEFAULT_READINESS_GATE } from '../../services/pipeline/editorialScore.js';import { getSettings, updateSettingsWith } from '../../services/settings.js';import { mapServiceError } from './shared.js';@@ -98,6 +100,34 @@ router.get('/editorial/checks', asyncHandler(async (req, res) => {res.json({ checks: resolveCheckState(settings) });}));+// ---------------------------------------------------------------------------+// Editorial health score + revision-trend tracking (#1316).+// ---------------------------------------------------------------------------++// Editorial health for a series: the transparent severity-weighted score (per+// series + per issue), the readiness signal, and the revision trend ++// regressions. Reads the same manuscript-review findings the triage view shows.+router.get('/series/:id/editorial/health', asyncHandler(async (req, res) => {+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });+ const settings = await getSettings();+ const gate = readReadinessGate(settings) || DEFAULT_READINESS_GATE;+ res.json(await getSeriesHealth(req.params.id, { gate }));+}));++// Set the editorial-health readiness gate (the convergence signal the autopilot+// loop + UI read as "manuscript clean"). Persists into the same+// `pipelineEditorialChecks` settings slice as the per-check enable/config state.+const readinessGateSchema = z.object({ readinessGate: z.enum([...READINESS_GATES]) }).strict();+router.patch('/editorial/readiness-gate', asyncHandler(async (req, res) => {+ const body = validateRequest(readinessGateSchema, req.body ?? {});+ const updated = await updateSettingsWith((current) => {+ const slice = current.pipelineEditorialChecks && typeof current.pipelineEditorialChecks === 'object'+ ? current.pipelineEditorialChecks : {};+ return { ...current, pipelineEditorialChecks: { ...slice, readinessGate: body.readinessGate } };+ });+ res.json({ readinessGate: readReadinessGate(updated) || DEFAULT_READINESS_GATE });+}));+// Enable/disable a check or update its config. Config is validated against the// check's own Zod schema before persisting (the wire shape is gated by// editorialCheckConfigSchema first).diff --git a/server/routes/pipeline/editorial.test.js b/server/routes/pipeline/editorial.test.jsindex 882ea8a4d7..fb8cb70754 100644--- a/server/routes/pipeline/editorial.test.js+++ b/server/routes/pipeline/editorial.test.js@@ -36,6 +36,14 @@ vi.mock('../../services/pipeline/editorial/checkRunner.js', () => ({cancelEditorialChecks: vi.fn(() => true),}));+// Health service (#1316) — stub the read so the route test exercises the route+// wiring (series-resolve + settings-gate resolution) without the file store.+const getSeriesHealth = vi.fn(async (seriesId, opts) => ({ seriesId, score: 100, ready: true, gate: opts?.gate }));+vi.mock('../../services/pipeline/editorialScore.js', async (importOriginal) => ({+ ...(await importOriginal()),+ getSeriesHealth: (...a) => getSeriesHealth(...a),+}));+const editorialRoutes = (await import('./editorial.js')).default;const app = express();@@ -46,6 +54,7 @@ app.use(errorMiddleware);beforeEach(() => {settingsStore = {};startEditorialChecksRun.mockClear();+ getSeriesHealth.mockClear();});describe('GET /api/pipeline/editorial/checks', () => {@@ -206,3 +215,45 @@ describe('custom checks CRUD (#1346)', () => {expect((await request(app).delete('/api/pipeline/editorial/custom-checks/custom.nope')).status).toBe(404);});});++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');+ expect(res.status).toBe(200);+ expect(res.body.seriesId).toBe('s1');+ expect(res.body.score).toBe(100);+ // No gate configured → service called with the default.+ expect(getSeriesHealth).toHaveBeenCalledWith('s1', { gate: 'noOpenHigh' });+ });++ it('GET .../editorial/health resolves the configured gate from settings', async () => {+ await request(app).patch('/api/pipeline/editorial/readiness-gate').send({ readinessGate: 'noOpenHighOrMedium' });+ await request(app).get('/api/pipeline/series/s1/editorial/health');+ expect(getSeriesHealth).toHaveBeenLastCalledWith('s1', { gate: 'noOpenHighOrMedium' });+ });++ it('GET .../editorial/health 404s a missing series', async () => {+ const res = await request(app).get('/api/pipeline/series/missing/editorial/health');+ expect(res.status).toBe(404);+ expect(getSeriesHealth).not.toHaveBeenCalled();+ });++ it('PATCH .../editorial/readiness-gate persists into the editorial-checks slice', async () => {+ const res = await request(app).patch('/api/pipeline/editorial/readiness-gate').send({ readinessGate: 'none' });+ expect(res.status).toBe(200);+ expect(res.body.readinessGate).toBe('none');+ expect(settingsStore.pipelineEditorialChecks.readinessGate).toBe('none');+ });++ it('PATCH .../editorial/readiness-gate 400s an unknown gate value', async () => {+ const res = await request(app).patch('/api/pipeline/editorial/readiness-gate').send({ readinessGate: 'whenever' });+ expect(res.status).toBe(400);+ });++ it('PATCH .../editorial/readiness-gate does not clobber existing check overrides', async () => {+ await request(app).patch('/api/pipeline/editorial/checks/prose.info-dumping').send({ enabled: false });+ await request(app).patch('/api/pipeline/editorial/readiness-gate').send({ readinessGate: 'noOpenHigh' });+ expect(settingsStore.pipelineEditorialChecks.checks['prose.info-dumping'].enabled).toBe(false);+ expect(settingsStore.pipelineEditorialChecks.readinessGate).toBe('noOpenHigh');+ });+});diff --git a/server/routes/pipeline/manuscript.js b/server/routes/pipeline/manuscript.jsindex bd0718ec80..82387e96c2 100644--- a/server/routes/pipeline/manuscript.js+++ b/server/routes/pipeline/manuscript.js@@ -18,6 +18,9 @@ import * as manuscriptReview from '../../services/pipeline/manuscriptReview.js';import * as manuscriptFix from '../../services/pipeline/manuscriptFix.js';import * as completenessRunner from '../../services/pipeline/manuscriptCompletenessRunner.js';import { getReviewWithStaleness } from '../../services/pipeline/editorial/checkRunner.js';+import { recordTrendSnapshot } from '../../services/pipeline/editorialScore.js';+import { readReadinessGate } from '../../lib/editorial/index.js';+import { getSettings } from '../../services/settings.js';import { mapServiceError, providerOverrideShape } from './shared.js';const router = Router();@@ -91,6 +94,11 @@ router.post('/series/:id/manuscript/completeness', asyncHandler(async (req, res)// existing ArcHeader caller — the editor reads the merged `review`.const review = await manuscriptReview.seedReviewFromFindings(req.params.id, result.issues, { runId: result.runId, mode: body.mode }).catch((err) => { throw mapServiceError(err); });+ // Revision-trend snapshot (#1316): this completeness pass is a revision+ // boundary. Best-effort — never fail the request on a ledger-write error.+ const gate = readReadinessGate(await getSettings().catch(() => null)) || undefined;+ await recordTrendSnapshot(req.params.id, { runId: result.runId, gate, comments: review.comments })+ .catch((err) => { console.error(`⚠️ editorial trend snapshot failed — series=${String(req.params.id).slice(0, 12)} ${err.message}`); });res.json({ ...result, review });}));diff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.jsindex cf278eb42d..9b3a112163 100644--- a/server/services/pipeline/editorial/checkRunner.js+++ b/server/services/pipeline/editorial/checkRunner.js@@ -28,6 +28,8 @@ import { collectManuscriptSections, sectionsCorpus, manuscriptSectionHeader } frimport { getReverseOutline } from '../reverseOutline.js';import { getSeriesEditorial } from '../editorialAnalysis.js';import { seedReviewFromFindings, getReview } from '../manuscriptReview.js';+import { recordTrendSnapshot } from '../editorialScore.js';+import { readReadinessGate } from '../../../lib/editorial/index.js';import { canonicalStringify } from '../../../lib/objects.js';// Source-content fingerprinting for finding staleness (#1345, #1387). Each finding@@ -417,6 +419,13 @@ export async function runEditorialChecks(seriesId, options = {}) {// review with partial findings collected before the abort.if (findings.length && !canceled) {await seedReviewFromFindings(seriesId, findings, { runId, mode: 'merge' });+ // Record a revision-trend snapshot (#1316): this run is a revision boundary,+ // so snapshot the post-seed open-finding counts for the health-trend ledger.+ // Best-effort — a ledger write must never fail the check run (it's telemetry).+ const gate = readReadinessGate(settings) || undefined;+ await recordTrendSnapshot(seriesId, { runId, gate }).catch((err) => {+ console.error(`⚠️ editorial trend snapshot failed — series=${String(seriesId).slice(0, 12)} ${err.message}`);+ });}return { runId, findings, perCheck, canceled };}diff --git a/server/services/pipeline/editorialScore.js b/server/services/pipeline/editorialScore.jsnew file mode 100644index 0000000000..e5ec2456a3--- /dev/null+++ b/server/services/pipeline/editorialScore.js@@ -0,0 +1,335 @@+/**+ * Pipeline — Editorial health score + revision-trend tracking (#1316).+ *+ * Turns the point-in-time manuscript-review findings (manuscriptReview.js) into+ * something the author can *manage* the draft with:+ *+ * - a transparent, deterministic HEALTH SCORE (per-issue + per-series) computed+ * from the OPEN findings weighted by severity — no black box, the formula is+ * `100 − Σ weight(severity)` clamped to 0..100 (weights below);+ * - a "READY" signal — a configurable convergence gate (default: no open `high`+ * findings) the autopilot editorial loop and the UI read as "manuscript clean";+ * - a per-run REVISION-TREND ledger — each editorial-checks / completeness run is+ * a revision boundary; we snapshot the open-finding counts by severity ++ * category so the UI can render "continuity 8→5→2" trends and flag categories+ * that REGRESSED after an edit pass.+ *+ * Scoring is PURE (unit-testable in isolation); the trend ledger persists at+ * `data/pipeline-editorial-health/{seriesId}.json` (atomic write, per-series+ * tail) mirroring the editorialAnalysis snapshot pattern. Errors bubble (no+ * try/catch) — callers own their boundary.+ */++import { join } from 'path';+import { PATHS, atomicWrite, readJSONFile } from '../../lib/fileUtils.js';+import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';+import { getReview } from './manuscriptReview.js';++// Storage-layout version for the trend ledger. Bump + migrate if the snapshot+// shape changes in a way older peers can't read. (Trend snapshots are local+// telemetry — they do NOT ride peer sync, so this is install-local.)+const SCHEMA_VERSION = 1;++const SEVERITIES = Object.freeze(['high', 'medium', 'low']);++// Transparent severity penalty weights. A draft starts at 100 and loses points+// per OPEN finding: a `high` finding costs as much as a dozen `low` nits. These+// are the published formula — surfaced in the API + UI so the score is never a+// black box. Accepted (fixed) and dismissed (waived) findings cost nothing.+export const SEVERITY_WEIGHTS = Object.freeze({ high: 12, medium: 5, low: 1 });++// Readiness gates — the convergence signal the autopilot + UI read as "clean".+// `noOpenHigh` (default) is the manuscript-not-clean threshold; the stricter+// gate also blocks on mediums; `none` disables the gate (always ready).+export const READINESS_GATES = Object.freeze(['noOpenHigh', 'noOpenHighOrMedium', 'none']);+export const DEFAULT_READINESS_GATE = 'noOpenHigh';++// Cap on the persisted revision-trend ledger. Each run appends one snapshot; the+// oldest roll off so the file can't grow unbounded over a long series' life.+const MAX_TREND_SNAPSHOTS = 100;++const nowIso = () => new Date().toISOString();++// Defense-in-depth: refuse path-traversal-shaped ids before interpolating into+// the on-disk ledger path. Series ids are `ser-<uuid>` — restrict to a safe+// charset (mirrors editorialAnalysis.assertValidIssueId).+function assertValidSeriesId(id) {+ if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(id)) {+ throw new Error(`Invalid series id: ${id}`);+ }+}++const healthDir = () => join(PATHS.data, 'pipeline-editorial-health');+const ledgerPath = (seriesId) => join(healthDir(), `${seriesId}.json`);++// ---------------------------------------------------------------------------+// Pure scoring.+// ---------------------------------------------------------------------------++const normalizeSeverity = (s) => (SEVERITIES.includes(s) ? s : 'low');+const emptySeverityCounts = () => ({ high: 0, medium: 0, low: 0 });++// Resolve the readiness gate to one of READINESS_GATES, falling back to the+// default for an absent/unknown value — so a hand-edited settings blob can't+// silently disable the gate with a typo (it falls through to noOpenHigh).+export function resolveReadinessGate(gate) {+ return READINESS_GATES.includes(gate) ? gate : DEFAULT_READINESS_GATE;+}++// Is a set of open-severity counts "ready" under the given gate?+export function isReadyUnderGate(openBySeverity, gate) {+ const g = resolveReadinessGate(gate);+ const counts = openBySeverity || emptySeverityCounts();+ if (g === 'none') return true;+ if (g === 'noOpenHighOrMedium') return (counts.high || 0) === 0 && (counts.medium || 0) === 0;+ return (counts.high || 0) === 0; // noOpenHigh+}++// The weighted health score for a list of OPEN findings: 100 minus the summed+// severity penalty, clamped to 0..100. Pure + deterministic.+export function scoreFromOpen(openBySeverity) {+ const counts = openBySeverity || emptySeverityCounts();+ const penalty = SEVERITIES.reduce((sum, sev) => sum + (counts[sev] || 0) * SEVERITY_WEIGHTS[sev], 0);+ return Math.max(0, Math.min(100, 100 - penalty));+}++// Tally one finding into an accumulator. OPEN findings drive the score ++// breakdowns; accepted/dismissed are counted only for context (resolved totals).+function tally(acc, comment) {+ acc.total += 1;+ const status = comment?.status;+ if (status === 'accepted') { acc.accepted += 1; return; }+ if (status === 'dismissed') { acc.dismissed += 1; return; }+ // Treat any non-accepted/dismissed status (incl. legacy/absent) as open — the+ // store defaults unknown statuses to 'open', so this can't under-count blockers.+ const sev = normalizeSeverity(comment?.severity);+ acc.open += 1;+ acc.openBySeverity[sev] += 1;+ const category = (typeof comment?.category === 'string' && comment.category) ? comment.category : 'other';+ acc.openByCategory[category] = (acc.openByCategory[category] || 0) + 1;+ const checkId = (typeof comment?.checkId === 'string' && comment.checkId) ? comment.checkId : 'completeness';+ acc.openByCheck[checkId] = (acc.openByCheck[checkId] || 0) + 1;+}++const newAcc = () => ({+ total: 0,+ open: 0,+ accepted: 0,+ dismissed: 0,+ openBySeverity: emptySeverityCounts(),+ openByCategory: {},+ openByCheck: {},+});++// Finalize an accumulator into a scored metric block (adds score + ready).+function finalize(acc, gate) {+ return {+ score: scoreFromOpen(acc.openBySeverity),+ ready: isReadyUnderGate(acc.openBySeverity, gate),+ total: acc.total,+ open: acc.open,+ accepted: acc.accepted,+ dismissed: acc.dismissed,+ openBySeverity: acc.openBySeverity,+ openByCategory: acc.openByCategory,+ openByCheck: acc.openByCheck,+ };+}++/**+ * Compute the editorial health score from a review's comments — a per-series+ * roll-up plus a per-issue breakdown (keyed by issueNumber). Pure: pass in the+ * comments + the resolved readiness gate.+ *+ * @param {Array} comments — manuscriptReview comment records+ * @param {string} [gate] — readiness gate (default DEFAULT_READINESS_GATE)+ * @returns {{ score, ready, ...series-rollup, gate, weights, perIssue: [] }}+ */+export function computeHealth(comments, gate = DEFAULT_READINESS_GATE) {+ const resolvedGate = resolveReadinessGate(gate);+ const list = Array.isArray(comments) ? comments : [];+ const seriesAcc = newAcc();+ const byIssue = new Map();+ for (const c of list) {+ if (!c || typeof c !== 'object') continue;+ tally(seriesAcc, c);+ // Per-issue breakdown — findings with no issueNumber bucket under `null`+ // (series-scoped findings like naming collisions).+ const key = Number.isInteger(c.issueNumber) ? c.issueNumber : null;+ if (!byIssue.has(key)) byIssue.set(key, newAcc());+ tally(byIssue.get(key), c);+ }+ const perIssue = [...byIssue.entries()]+ .map(([issueNumber, acc]) => ({ issueNumber, ...finalize(acc, resolvedGate) }))+ // Stable order: real issue numbers ascending, the null (series-scoped) bucket last.+ .sort((a, b) => (a.issueNumber ?? Infinity) - (b.issueNumber ?? Infinity));+ return {+ ...finalize(seriesAcc, resolvedGate),+ gate: resolvedGate,+ weights: SEVERITY_WEIGHTS,+ perIssue,+ };+}++// ---------------------------------------------------------------------------+// Revision-trend ledger (persisted per series).+// ---------------------------------------------------------------------------++// Per-series write tail (the ledger file is distinct per series, so each only+// serializes against itself). Mirrors manuscriptReview's queue pattern.+const ledgerQueues = new Map();+function queueLedgerWrite(seriesId, fn) {+ const key = typeof seriesId === 'string' && seriesId ? seriesId : '__unknown__';+ let q = ledgerQueues.get(key);+ if (!q) { q = createFileWriteQueue(); ledgerQueues.set(key, q); }+ return q(fn);+}++const emptyLedger = (seriesId) => ({ schemaVersion: SCHEMA_VERSION, seriesId, snapshots: [] });++function sanitizeSnapshot(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const at = typeof raw.at === 'string' ? raw.at : null;+ if (!at) return null;+ const sevRaw = raw.openBySeverity && typeof raw.openBySeverity === 'object' ? raw.openBySeverity : {};+ const openBySeverity = {+ high: Number.isFinite(sevRaw.high) ? sevRaw.high : 0,+ medium: Number.isFinite(sevRaw.medium) ? sevRaw.medium : 0,+ low: Number.isFinite(sevRaw.low) ? sevRaw.low : 0,+ };+ const byCat = raw.openByCategory && typeof raw.openByCategory === 'object' ? raw.openByCategory : {};+ const openByCategory = {};+ for (const [k, v] of Object.entries(byCat)) if (Number.isFinite(v)) openByCategory[k] = v;+ return {+ runId: typeof raw.runId === 'string' ? raw.runId : null,+ at,+ score: Number.isFinite(raw.score) ? raw.score : scoreFromOpen(openBySeverity),+ ready: raw.ready === true,+ open: Number.isFinite(raw.open) ? raw.open : (openBySeverity.high + openBySeverity.medium + openBySeverity.low),+ openBySeverity,+ openByCategory,+ };+}++function sanitizeLedger(raw, seriesId) {+ if (!raw || typeof raw !== 'object' || !Array.isArray(raw.snapshots)) return emptyLedger(seriesId);+ return {+ schemaVersion: SCHEMA_VERSION,+ seriesId,+ snapshots: raw.snapshots.map(sanitizeSnapshot).filter(Boolean),+ };+}++async function readLedger(seriesId) {+ const raw = await readJSONFile(ledgerPath(seriesId), null);+ return raw == null ? emptyLedger(seriesId) : sanitizeLedger(raw, seriesId);+}++/**+ * Read the persisted revision-trend ledger for a series (never null — an empty+ * ledger when none has been recorded yet).+ */+export async function getTrendLedger(seriesId) {+ assertValidSeriesId(seriesId);+ return readLedger(seriesId);+}++/**+ * Record a revision-trend snapshot for a series from its CURRENT review state.+ * Called after each editorial-checks / completeness run (the run is the+ * revision boundary). Reads the freshest review, derives the open-finding+ * counts, and appends a snapshot — de-duped by `runId` so a re-entrant seed for+ * the same run replaces rather than doubles the point. The ledger is capped at+ * MAX_TREND_SNAPSHOTS (oldest roll off).+ *+ * @param {string} seriesId+ * @param {object} [opts]+ * - runId: the run that produced this revision (snapshot identity)+ * - gate: readiness gate to stamp the snapshot's `ready` flag+ * - comments: pre-loaded review comments (skips the getReview round-trip)+ * @returns {Promise<object>} the appended snapshot+ */+export async function recordTrendSnapshot(seriesId, { runId = null, gate = DEFAULT_READINESS_GATE, comments } = {}) {+ assertValidSeriesId(seriesId);+ const list = Array.isArray(comments) ? comments : (await getReview(seriesId)).comments;+ const health = computeHealth(list, gate);+ const snapshot = {+ runId: typeof runId === 'string' ? runId : null,+ at: nowIso(),+ score: health.score,+ ready: health.ready,+ open: health.open,+ openBySeverity: health.openBySeverity,+ openByCategory: health.openByCategory,+ };+ return queueLedgerWrite(seriesId, async () => {+ const ledger = await readLedger(seriesId);+ // De-dupe by runId: a re-entrant seed for the SAME run replaces its point+ // (so two write paths in one run — e.g. completeness then checks — don't+ // each leave a snapshot for the same runId). A null runId always appends.+ const kept = snapshot.runId+ ? ledger.snapshots.filter((s) => s.runId !== snapshot.runId)+ : ledger.snapshots;+ const next = {+ schemaVersion: SCHEMA_VERSION,+ seriesId,+ snapshots: [...kept, snapshot].slice(-MAX_TREND_SNAPSHOTS),+ };+ await atomicWrite(ledgerPath(seriesId), next);+ return snapshot;+ });+}++// ---------------------------------------------------------------------------+// Trend / regression projection (pure).+// ---------------------------------------------------------------------------++/**+ * Project a ledger's snapshots into a trend view: the score/open time-series+ * plus per-category REGRESSIONS (a category whose open-finding count rose+ * between the two most recent snapshots — i.e. it got WORSE after an edit pass).+ * Pure so the route + UI + tests share one definition.+ *+ * @param {Array} snapshots — the ledger's snapshots (chronological, oldest first)+ * @returns {{ points: [], regressions: [], latest, previous, delta }}+ */+export function computeTrend(snapshots) {+ const list = Array.isArray(snapshots) ? snapshots.map(sanitizeSnapshot).filter(Boolean) : [];+ const points = list.map((s) => ({+ runId: s.runId,+ at: s.at,+ score: s.score,+ open: s.open,+ openBySeverity: s.openBySeverity,+ }));+ const latest = list[list.length - 1] || null;+ const previous = list.length >= 2 ? list[list.length - 2] : null;+ // Score delta between the two most recent revisions (positive = improving).+ const delta = latest && previous ? latest.score - previous.score : 0;+ // Per-category regressions: a category whose open count is higher in `latest`+ // than in `previous`. Categories absent from `previous` count as 0 prior.+ const regressions = [];+ if (latest && previous) {+ for (const [category, to] of Object.entries(latest.openByCategory || {})) {+ const from = previous.openByCategory?.[category] || 0;+ if (to > from) regressions.push({ category, from, to });+ }+ regressions.sort((a, b) => (b.to - b.from) - (a.to - a.from));+ }+ return { points, regressions, latest, previous, delta };+}++/**+ * The full health payload for a series: the current score/breakdown, the+ * readiness signal, and the revision trend + regressions. The single read the+ * route + UI consume.+ */+export async function getSeriesHealth(seriesId, { gate = DEFAULT_READINESS_GATE } = {}) {+ assertValidSeriesId(seriesId);+ const [review, ledger] = await Promise.all([getReview(seriesId), readLedger(seriesId)]);+ const health = computeHealth(review.comments, gate);+ const trend = computeTrend(ledger.snapshots);+ return { seriesId, ...health, trend, generatedAt: nowIso() };+}++export const __testing = { sanitizeSnapshot, sanitizeLedger, MAX_TREND_SNAPSHOTS };diff --git a/server/services/pipeline/editorialScore.test.js b/server/services/pipeline/editorialScore.test.jsnew file mode 100644index 0000000000..95de3a0400--- /dev/null+++ b/server/services/pipeline/editorialScore.test.js@@ -0,0 +1,175 @@+import { describe, it, expect } from 'vitest';+import {+ SEVERITY_WEIGHTS,+ DEFAULT_READINESS_GATE,+ scoreFromOpen,+ isReadyUnderGate,+ resolveReadinessGate,+ computeHealth,+ computeTrend,+ __testing,+} from './editorialScore.js';++const open = (severity, extra = {}) => ({ status: 'open', severity, ...extra });++describe('scoreFromOpen', () => {+ it('a clean draft scores 100', () => {+ expect(scoreFromOpen({ high: 0, medium: 0, low: 0 })).toBe(100);+ });++ it('subtracts the published severity weights', () => {+ expect(scoreFromOpen({ high: 1, medium: 0, low: 0 })).toBe(100 - SEVERITY_WEIGHTS.high);+ expect(scoreFromOpen({ high: 0, medium: 1, low: 0 })).toBe(100 - SEVERITY_WEIGHTS.medium);+ expect(scoreFromOpen({ high: 0, medium: 0, low: 1 })).toBe(100 - SEVERITY_WEIGHTS.low);+ });++ it('clamps to 0 (never negative) when findings pile up', () => {+ expect(scoreFromOpen({ high: 100, medium: 0, low: 0 })).toBe(0);+ });++ it('tolerates an absent/partial counts object', () => {+ expect(scoreFromOpen(undefined)).toBe(100);+ expect(scoreFromOpen({ high: 2 })).toBe(100 - 2 * SEVERITY_WEIGHTS.high);+ });+});++describe('readiness gate', () => {+ it('resolves unknown/absent gate to the default', () => {+ expect(resolveReadinessGate('bogus')).toBe(DEFAULT_READINESS_GATE);+ expect(resolveReadinessGate(undefined)).toBe(DEFAULT_READINESS_GATE);+ expect(resolveReadinessGate('none')).toBe('none');+ });++ it('noOpenHigh: ready iff no open high findings', () => {+ expect(isReadyUnderGate({ high: 0, medium: 5, low: 9 }, 'noOpenHigh')).toBe(true);+ expect(isReadyUnderGate({ high: 1, medium: 0, low: 0 }, 'noOpenHigh')).toBe(false);+ });++ it('noOpenHighOrMedium: blocks on mediums too', () => {+ expect(isReadyUnderGate({ high: 0, medium: 1, low: 0 }, 'noOpenHighOrMedium')).toBe(false);+ expect(isReadyUnderGate({ high: 0, medium: 0, low: 9 }, 'noOpenHighOrMedium')).toBe(true);+ });++ it('none: always ready', () => {+ expect(isReadyUnderGate({ high: 9, medium: 9, low: 9 }, 'none')).toBe(true);+ });+});++describe('computeHealth', () => {+ it('rolls up open findings, ignoring accepted/dismissed in the score', () => {+ const comments = [+ open('high', { issueNumber: 1, category: 'continuity' }),+ open('medium', { issueNumber: 1, category: 'pacing' }),+ { status: 'accepted', severity: 'high', issueNumber: 1, category: 'continuity' },+ { status: 'dismissed', severity: 'high', issueNumber: 2, category: 'naming' },+ open('low', { issueNumber: 2, category: 'style' }),+ ];+ const health = computeHealth(comments, 'noOpenHigh');+ expect(health.total).toBe(5);+ expect(health.open).toBe(3);+ expect(health.accepted).toBe(1);+ expect(health.dismissed).toBe(1);+ expect(health.openBySeverity).toEqual({ high: 1, medium: 1, low: 1 });+ expect(health.score).toBe(100 - SEVERITY_WEIGHTS.high - SEVERITY_WEIGHTS.medium - SEVERITY_WEIGHTS.low);+ expect(health.ready).toBe(false); // one open high+ });++ it('breaks findings down per issue, with series-scoped (null issueNumber) last', () => {+ const comments = [+ open('high', { issueNumber: 2, category: 'continuity' }),+ open('low', { issueNumber: 1, category: 'style' }),+ open('medium', { category: 'naming' }), // series-scoped, no issueNumber+ ];+ const health = computeHealth(comments);+ expect(health.perIssue.map((p) => p.issueNumber)).toEqual([1, 2, null]);+ const issue2 = health.perIssue.find((p) => p.issueNumber === 2);+ expect(issue2.openBySeverity.high).toBe(1);+ expect(issue2.ready).toBe(false);+ const seriesScoped = health.perIssue.find((p) => p.issueNumber === null);+ expect(seriesScoped.openByCategory.naming).toBe(1);+ });++ it('treats a finding with no/unknown status as open (does not under-count blockers)', () => {+ const comments = [{ severity: 'high', issueNumber: 1 }]; // no status field+ const health = computeHealth(comments);+ expect(health.open).toBe(1);+ expect(health.ready).toBe(false);+ });++ it('buckets a missing checkId under "completeness" and missing category under "other"', () => {+ const comments = [open('low', { issueNumber: 1 })];+ const health = computeHealth(comments);+ expect(health.openByCheck.completeness).toBe(1);+ expect(health.openByCategory.other).toBe(1);+ });++ it('a clean (all-resolved) review is ready and scores 100', () => {+ const comments = [+ { status: 'accepted', severity: 'high', issueNumber: 1 },+ { status: 'dismissed', severity: 'medium', issueNumber: 1 },+ ];+ const health = computeHealth(comments);+ expect(health.score).toBe(100);+ expect(health.open).toBe(0);+ expect(health.ready).toBe(true);+ });+});++describe('computeTrend', () => {+ const snap = (at, score, open, openByCategory = {}) => ({+ runId: `run-${at}`, at, score, ready: open === 0, open,+ openBySeverity: { high: 0, medium: 0, low: open }, openByCategory,+ });++ it('projects a score/open time-series in order', () => {+ const trend = computeTrend([+ snap('2026-06-01T00:00:00Z', 80, 5),+ snap('2026-06-02T00:00:00Z', 90, 2),+ ]);+ expect(trend.points.map((p) => p.score)).toEqual([80, 90]);+ expect(trend.delta).toBe(10); // improving+ expect(trend.latest.open).toBe(2);+ expect(trend.previous.open).toBe(5);+ });++ it('flags a category that regressed (got worse) between the two latest snapshots', () => {+ const trend = computeTrend([+ snap('2026-06-01T00:00:00Z', 90, 3, { continuity: 1, pacing: 2 }),+ snap('2026-06-02T00:00:00Z', 70, 5, { continuity: 4, pacing: 1 }),+ ]);+ expect(trend.regressions).toEqual([{ category: 'continuity', from: 1, to: 4 }]);+ expect(trend.delta).toBe(-20); // regressing+ });++ it('treats a category absent in the prior snapshot as 0 prior (new regressions count)', () => {+ const trend = computeTrend([+ snap('2026-06-01T00:00:00Z', 95, 1, { style: 1 }),+ snap('2026-06-02T00:00:00Z', 88, 2, { style: 1, naming: 1 }),+ ]);+ expect(trend.regressions).toEqual([{ category: 'naming', from: 0, to: 1 }]);+ });++ it('returns empty trend for an empty/absent ledger', () => {+ const trend = computeTrend([]);+ expect(trend.points).toEqual([]);+ expect(trend.regressions).toEqual([]);+ expect(trend.delta).toBe(0);+ expect(trend.latest).toBeNull();+ });+});++describe('ledger sanitization', () => {+ it('drops malformed snapshots and coerces severity counts', () => {+ const ledger = __testing.sanitizeLedger({+ snapshots: [+ null,+ { at: '2026-06-01T00:00:00Z', score: 90, openBySeverity: { high: 'x', medium: 2 }, openByCategory: { a: 1, b: 'nope' } },+ { score: 50 }, // no `at` → dropped+ ],+ }, 'ser-abc');+ expect(ledger.snapshots).toHaveLength(1);+ expect(ledger.snapshots[0].openBySeverity).toEqual({ high: 0, medium: 2, low: 0 });+ expect(ledger.snapshots[0].openByCategory).toEqual({ a: 1 });+ expect(ledger.seriesId).toBe('ser-abc');+ });+});diff --git a/server/services/pipeline/manuscriptCompletenessRunner.js b/server/services/pipeline/manuscriptCompletenessRunner.jsindex 570c74612a..cc95e9b93b 100644--- a/server/services/pipeline/manuscriptCompletenessRunner.js+++ b/server/services/pipeline/manuscriptCompletenessRunner.js@@ -20,6 +20,9 @@import { createSseRunner } from '../../lib/sseUtils.js';import { analyzeManuscriptCompleteness } from './arcPlanner.js';import { seedReviewFromFindings } from './manuscriptReview.js';+import { recordTrendSnapshot } from './editorialScore.js';+import { readReadinessGate } from '../../lib/editorial/index.js';+import { getSettings } from '../settings.js';const runner = createSseRunner({ logLabel: 'completeness review' });@@ -72,6 +75,12 @@ export function startCompletenessReview(seriesId, options = {}) {mode: options.mode,});const openCount = review.comments.filter((c) => c.status === 'open').length;+ // Revision-trend snapshot (#1316): this completeness run is a revision+ // boundary. Best-effort telemetry — never fail the run on a ledger write.+ const gate = readReadinessGate(await getSettings().catch(() => null)) || undefined;+ await recordTrendSnapshot(seriesId, { runId: result.runId, gate, comments: review.comments }).catch((err) => {+ console.error(`⚠️ editorial trend snapshot failed — series=${String(seriesId).slice(0, 12)} ${err.message}`);+ });broadcast({type: 'complete',runId,diff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.jsindex f27f2fd35c..0dc0b42851 100644--- a/server/services/pipeline/seriesAutopilot.js+++ b/server/services/pipeline/seriesAutopilot.js@@ -91,7 +91,9 @@ import * as volumeBeatsRunner from './volumeBeatsRunner.js';import * as autoRunner from './autoRunner.js';import { seedReviewFromFindings, getReview } from './manuscriptReview.js';import { runEditorialChecks, buildEditorialCheckPlan } from './editorial/checkRunner.js';+import { computeHealth } from './editorialScore.js';import { getSettings } from '../settings.js';+import { readReadinessGate } from '../../lib/editorial/index.js';import { generateManuscriptFix, acceptManuscriptFix } from './manuscriptFix.js';import { verifyComicScript } from './scriptVerify.js';import { checkSeriesCanonReadiness } from './canonReadiness.js';@@ -281,6 +283,16 @@ export function resolveNextStep(series, issues, runState = {}, options = {}) {return { kind: 'editorialChecks', reason: 'editorial checks not yet run this run' };}+ // STEP 5.3 — editorial health convergence gate (#1316). After BOTH editorial+ // passes have seeded their findings, read the aggregate "ready" signal (no open+ // findings above the configured readiness gate). The completeness loop only+ // gates on its OWN high findings; the registry checks (5.2) can surface fresh+ // blockers after it converged, so this final gate reconciles the whole review+ // before visuals. Pauses with the residual blockers when not clean.+ if (!runState.editorialHealthReady) {+ return { kind: 'editorialHealthGate', reason: 'editorial health not yet confirmed clean this run' };+ }+// STEP 5.5 — canon descriptive integrity. Before ANY visual production, every// canon noun that appears where it'd be drawn must be described (an artist// can't render a name). Runs once per run; the gate blocks (pauses) on@@ -557,6 +569,9 @@ async function runEditorial(sId, record) {if (maxRounds === 0) {record.runState.editorialReviewed = true;record.runState.editorialChecksReviewed = true;+ // Skipping the editorial gate also skips its health convergence check (#1316)+ // — the resolver must advance past editorialHealthGate too.+ record.runState.editorialHealthReady = true;return {};}for (let round = 1; round <= maxRounds; round += 1) {@@ -643,6 +658,36 @@ async function runEditorialChecksPass(sId, record) {return {};}+// STEP 5.3 — editorial health convergence gate (#1316). A cheap, no-LLM gate:+// read the persisted review, compute the aggregate health under the configured+// readiness gate, and either mark the run clean (proceed to visuals) or PAUSE+// with the open blockers for human triage. This is the consolidated "ready"+// signal — distinct from the completeness loop's own per-round high-only gate —+// so a blocker the registry checks (5.2) surfaced after completeness converged+// still stops the run. No auto-fix here: the completeness loop already attempted+// fixes; remaining blockers need a human (or a re-run after edits).+async function runEditorialHealthGate(sId, record) {+ if (record.cancelRequested) return { canceled: true };+ const settings = await getSettings().catch(() => null);+ const gate = readReadinessGate(settings) || undefined;+ const review = await getReview(sId).catch(() => ({ comments: [] }));+ const health = computeHealth(review.comments || [], gate);+ broadcast(sId, {+ type: 'verify:round', scope: 'editorialHealth', round: 1,+ findings: health.open, blocking: health.ready ? 0 : health.open, score: health.score,+ });+ if (health.ready) {+ record.runState.editorialHealthReady = true;+ return {};+ }+ // Not clean — surface the open blockers (the gate-relevant severities) as the+ // residual the pause records, so the human sees exactly what's left.+ const blockers = (review.comments || []).filter(+ (c) => c.status === 'open' && (gate === 'noOpenHighOrMedium' ? ARC_BLOCKING.has(c.severity) : EDITORIAL_BLOCKING.has(c.severity)),+ );+ return { pause: true, reason: `editorial health not clean (score ${health.score}, ${health.open} open finding(s))`, residual: blockers };+}+// Turn a render-enqueue result into the { slotKey, slot } pair the render// routes persist (proof → proofImage, final → finalImage).const slotFromRenderResult = (result) => {@@ -872,6 +917,8 @@ async function dispatchStep(sId, step, record) {return runEditorial(sId, record);case 'editorialChecks':return runEditorialChecksPass(sId, record);+ case 'editorialHealthGate':+ return runEditorialHealthGate(sId, record);case 'canonVerify':return runCanonVerify(sId, record);case 'visualDraft':@@ -908,6 +955,7 @@ function buildDryRunPlan(series, issues, options) {if (isComicTarget(series)) plan.push({ kind: 'scriptVerify', count: ordered.length });plan.push({ kind: 'editorialReview', count: 1, note: `up to ${MAX_EDITORIAL_ROUNDS} rounds` });plan.push({ kind: 'editorialChecks', count: 1, note: 'enabled editorial checks (#1284)' });+ plan.push({ kind: 'editorialHealthGate', count: 1, note: 'editorial health readiness gate (#1316)' });if (VISUAL_DRAFT_ENABLED && wantsVisual(options) && isComicTarget(series)) {plan.push({ kind: 'canonVerify', count: 1, note: 'descriptive integrity of drawn nouns' });const visualNeeded = ordered.filter((i) => !visualReady(i)).length;@@ -960,6 +1008,7 @@ export async function startSeriesAutopilot(sId, options = {}) {arcVerified: false,editorialReviewed: false,editorialChecksReviewed: false,+ editorialHealthReady: false,canonVerified: false,episodesAttempted: new Set(),beatsAttempted: new Set(),@@ -1017,8 +1066,11 @@ export async function startSeriesAutopilot(sId, options = {}) {// self-gates: runEditorialChecksPass only pauses/bills the budget when an// enabled LLM check will actually run (returning a pause result this loop// still handles), so a deterministic-only or all-disabled checks step can- // complete a text-ready series even with the budget exhausted.- if (step.kind !== 'editorialChecks') {+ // complete a text-ready series even with the budget exhausted. The+ // editorialHealthGate (#1316) is likewise exempt — it's a pure read ++ // score with no LLM cost, so a budget-exhausted run can still produce its+ // readiness verdict (and pause on the findings, not the budget).+ if (step.kind !== 'editorialChecks' && step.kind !== 'editorialHealthGate') {const budget = await getDomainBudgetStatus('cos');if (!budget.withinBudget) {await persistMarker(sId, { status: 'paused', runId, currentStep: step.kind, lastError: `daily cos ${budget.exceeded} budget reached` });diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.jsindex d47c87b7c5..e01eeacf2f 100644--- a/server/services/pipeline/seriesAutopilot.test.js+++ b/server/services/pipeline/seriesAutopilot.test.js@@ -237,13 +237,23 @@ describe('resolveNextStep (pure)', () => {expect(step.kind).toBe('editorialChecks');});- it('is done once editorial review has run (no visuals requested)', () => {+ it('runs the editorial health gate after both editorial passes (#1316)', () => {const step = resolveNextStep(comic,[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],{ arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true },{ includeVisual: false },);+ expect(step.kind).toBe('editorialHealthGate');+ });++ it('is done once the editorial health gate is clean (no visuals requested)', () => {+ const step = resolveNextStep(+ comic,+ [issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],+ { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true, editorialHealthReady: true },+ { includeVisual: false },+ );expect(step.kind).toBe('done');});@@ -251,7 +261,7 @@ describe('resolveNextStep (pure)', () => {const step = resolveNextStep(comic,[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],- { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true },+ { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true, editorialHealthReady: true },{ includeVisual: true, target: 'text' },);expect(step.kind).toBe('done');@@ -261,7 +271,7 @@ describe('resolveNextStep (pure)', () => {const step = resolveNextStep(comic,[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],- { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true },+ { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true, editorialHealthReady: true },{ includeVisual: true },);expect(step.kind).toBe('canonVerify');@@ -271,7 +281,7 @@ describe('resolveNextStep (pure)', () => {const step = resolveNextStep(comic,[issue({ stages: { idea: ready(), comicScript: ready(VALID_SCRIPT) } })],- { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true, canonVerified: true },+ { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true, editorialHealthReady: true, canonVerified: true },{ includeVisual: true },);expect(step).toMatchObject({ kind: 'visualDraft', issueId: 'iss1' });@@ -290,7 +300,7 @@ describe('resolveNextStep (pure)', () => {const step = resolveNextStep(comic,[issue({ stages: renderedStages })],- { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true, canonVerified: true },+ { arcVerified: true, scriptChecked: new Set(['iss1']), editorialReviewed: true, editorialChecksReviewed: true, editorialHealthReady: true, canonVerified: true },{ includeVisual: true },);expect(step.kind).toBe('done');@@ -487,6 +497,24 @@ describe('autopilot conductor', () => {expect(checkRunnerSpies.runEditorialChecks).not.toHaveBeenCalled();});+ it('pauses at the editorial health gate when a blocking finding remains open (#1316)', async () => {+ const manuscriptReview = await import('./manuscriptReview.js');+ // Completeness + checks converge clean, but the post-pass review still holds+ // an open high finding (e.g. surfaced by the registry checks) — the health+ // gate must catch it and pause before visuals.+ manuscriptReview.getReview.mockResolvedValue({+ comments: [{ id: 'c1', status: 'open', severity: 'high', category: 'continuity', issueNumber: 1, problem: 'timeline contradiction' }],+ });+ const { seriesId } = await seedComplete();+ await autopilot.startSeriesAutopilot(seriesId, { includeVisual: false });+ await waitFor(runFinished(seriesId));+ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;+ expect(last?.type).toBe('paused');+ expect(last?.scope).toBe('editorialHealthGate');+ expect(last?.residualFindings?.[0]?.problem).toBe('timeline contradiction');+ manuscriptReview.getReview.mockResolvedValue({ comments: [] }); // restore+ });+it('a second start while active resolves to alreadyRunning', async () => {// Hold the run open by making the verify loop wait on a never-converging// finding plus a slow child so the first run is still active.