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
perf: overlap the foundation judge and canon readiness with the editorial checks in series review (#4108)
[._.]/ Adam Eivyb85d4c2e2bd8
diff --git a/.changelog/next/changed-issue-4108.md b/.changelog/next/changed-issue-4108.mdnew file mode 100644index 0000000000..1ac15daa0f--- /dev/null+++ b/.changelog/next/changed-issue-4108.md@@ -0,0 +1 @@+- Series review runs the foundation judge and canon readiness concurrently with the editorial-checks pass instead of before/after it, cutting roughly the full foundation-judge round-trip off each run; the live progress panel now summarizes the interleaved frame stream instead of labelling only the newest framediff --git a/client/src/components/pipeline/SeriesReviewPanel.jsx b/client/src/components/pipeline/SeriesReviewPanel.jsxindex b9f1fd84ea..06e9b7065a 100644--- a/client/src/components/pipeline/SeriesReviewPanel.jsx+++ b/client/src/components/pipeline/SeriesReviewPanel.jsx@@ -7,6 +7,7 @@ import {import toast from '../ui/Toast';import { usePipelineProgress } from '../../hooks/usePipelineProgress';import { severityRank } from '../../lib/editorialChecks';+import { reviewFrameLabel, summarizeReviewProgress } from '../../lib/seriesReviewProgress';import {startPipelineSeriesReview,getPipelineSeriesReview,@@ -25,30 +26,6 @@ const RUN_ENDED = new Set(['complete', 'canceled', 'error']);// The fix run's terminal frames: `rejected` = the cos gate/budget refused it.const FIX_RUN_ENDED = new Set(['complete', 'canceled', 'error', 'rejected']);-// One-line label for a review SSE frame (mirrors AutopilotPanel's frameLabel,-// scoped to this flow's steps).-const REVIEW_STEP_LABELS = {- foundation: 'Judging foundation',- feedback: 'Routing your feedback',- editorialChecks: 'Running editorial checks',- canon: 'Checking canon descriptions',- health: 'Scoring editorial health',-};-function reviewFrameLabel(f) {- if (!f) return null;- switch (f.type) {- case 'start': return 'Starting review…';- case 'step:start': return `${REVIEW_STEP_LABELS[f.kind] || f.kind}…`;- case 'step:complete': return `${REVIEW_STEP_LABELS[f.kind] || f.kind} done`;- case 'check:start': return `Editorial check: ${f.label || f.checkId}…`;- case 'check:complete': return `Editorial check: ${f.label || f.checkId} — ${f.count ?? 0} finding(s)`;- case 'complete': return 'Review complete';- case 'canceled': return 'Review canceled';- case 'error': return `Review failed — ${f.error}`;- default: return f.type;- }-}-// Compact label for the per-finding fix run.function fixFrameLabel(f) {if (!f) return 'Working…';@@ -264,7 +241,14 @@ export default function SeriesReviewPanel({ series, onSeriesUpdate, onIssuesUpdaif (!seriesId) return null;- const reviewLabel = reviewing ? (reviewFrameLabel(reviewLatest) || 'Working…') : null;+ // The review's background passes (foundation judge, canon readiness) run+ // CONCURRENTLY with the editorial checks (#4108), so the frames interleave —+ // summarize the whole stream rather than labelling only the newest frame, or+ // the headline flickers between the checks pass and a step that just settled.+ const { headline: reviewHeadline, alsoRunning: reviewAlsoRunning } = reviewing+ ? summarizeReviewProgress(reviewFrames)+ : { headline: null, alsoRunning: [] };+ const reviewLabel = reviewing ? (reviewHeadline || 'Working…') : null;const groups = review ? groupFindings(review.findings) : [];const hasIssues = review?.verdict === 'issues';// Only the manuscript-review findings are auto-fixable; a verdict that is@@ -336,10 +320,17 @@ export default function SeriesReviewPanel({ series, onSeriesUpdate, onIssuesUpda{/* Live review progress */}{reviewing ? (<div className="px-3 pb-3 border-t border-port-border pt-2">- <div className="text-xs text-gray-300 flex items-center gap-2">+ <div className="text-xs text-gray-300 flex items-center gap-2 flex-wrap"><Loader2 size={12} className="animate-spin text-port-accent" />{reviewLabel}</div>+ {/* The passes running alongside the headline step, so a long foundation+ judge stays visible while the checks pass owns the line above. */}+ {reviewAlsoRunning.length ? (+ <div className="mt-1 text-[11px] text-gray-500">+ also running: {reviewAlsoRunning.join(' · ')}+ </div>+ ) : null}{reviewFrames?.length ? (<div className="mt-2 max-h-24 overflow-y-auto text-[11px] text-gray-500 space-y-0.5">{reviewFrames.slice(-6).map((f, i) => <div key={i}>{reviewFrameLabel(f)}</div>)}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex bacceaa2c8..a0c91c65ec 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -139,6 +139,7 @@ grep -i "what you want to do" client/src/lib/README.md| `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; the triage filter/sort helpers (#1600) `deriveFindingFacets(groups)` (enumerate present severities/statuses/scopes/checks/issues), `applyFindingsView(groups, filters, sort)` (filter + recount + sort findings and groups), `normalizeFindingSort`, `findingIssueKey`, and the `FINDING_SORT_OPTIONS` table; the per-check maturity/quality helpers (#1629) `checkDismissalRate(group)` and `checkMaturity(group)` (→ `{ findings, dismissalRate, falsePositiveRate, level }`, `level` ∈ new/unproven/noisy/reliable) plus the `CHECK_MATURITY_MIN_SAMPLE`/`CHECK_NOISY_DISMISSAL_RATE` thresholds; 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; `orderedChecks(openByCheck, labelFor)` sorts the per-check breakdown resolving each id to its catalog label (#1597); `checkCountSeries(points, checkId)` extracts one check's count series across the trend points; `countSparklineGeometry(values, box)` projects a non-negative count series into SVG polyline coords normalized to its own max (per-check finding-count sparkline); `diffCountMaps(current, previous)` lists the buckets whose open-finding count changed between two snapshots (#1630); `snapshotDiff(point, previous)` builds a trend snapshot's drill-down (its own breakdown + per-severity/category/check diff vs the prior revision, null-aware for pre-#1597 per-check telemetry, #1630); plus the `SEVERITY_ORDER`/`SEVERITY_LABELS` and `READINESS_GATE_LABELS`/`READINESS_GATE_ORDER` tables. No React/window — the panel and its tests share them. |+| `seriesReviewProgress.js` | Pure helpers for the "Review this series" SSE progress stream (`SeriesReviewPanel.jsx`, #4108): `REVIEW_STEP_LABELS` + `reviewFrameLabel(frame)` label a single frame, and `summarizeReviewProgress(frames)` folds the whole stream into `{ headline, alsoRunning }`. Since the review runs the foundation judge and canon readiness concurrently with the editorial-checks pass, frames interleave — labelling only the newest frame made the headline flicker between a background step that just settled and the current check. The summarizer tracks which steps are still in flight, gives the headline to the editorial-checks pass while it runs, and reports the other in-flight steps alongside it. No React/window. || `drumKits.js` | The three selectable synth kits for the SongBook drum play-along — `DRUM_KIT_LIST` (the one ordered source of truth, first entry = default; the picker renders it directly) plus the derived `DRUM_KITS` / `DRUM_KIT_IDS` / `DEFAULT_DRUM_KIT` (`909` punchy, `808` deep-sub, `acoustic`), `resolveDrumKit(id)` (unknown/stale id → the default, never silence), `kitVoiceLayers(kit, sound)` (unmapped piece → the snare, never silence) and the kit-independent `CLICK_VOICE`. Pure DATA: each voice is a list of LAYERS — `tone` (`wave, from, to, pitchDecay, drive`), `noise` (`filter`), or `metal` (N square `partials` summed into one filter+envelope) — that `drumPlayback.js` realizes in Web Audio. Three properties carry the kit's punch and are easy to undo by accident: `pitchDecay` is INDEPENDENT of the amplitude `decay` (a membrane snaps to its fundamental in ~30–60ms then holds while the tail runs on — coupling the two is what made the original kick sound weak), `drive` tanh-saturates a layer so a sub-50 Hz kick generates the harmonics a phone/laptop speaker can actually reproduce, and a `metal` layer's high-pass cutoffs are far LOWER (and gains far higher) than the noise voices beside them because a square's harmonics fall off 6 dB/octave — see the calibration warning in the file before "harmonizing" those numbers. || `drumNotation.js` | Parser for the PortOS drum-kit notation (#3115) — a dependency-free GRID DSL (`HH: x x x x`) for the SongBook `drum` content format, drawn by `<DrumSheetView>` (hand-rolled SVG, no engraving lib). `parseDrumChart(text)` → `{ time, tempo, subdivision, stepsPerBar, bars:[{index,label,repeat,repeatPass,rows:[{piece,cells}]}], pieces, errors }` — `key: value` headers (`time`/`tempo`/`subdivision`/`kit` row-order override), blank-line-separated bar blocks with a `# label x2` repeat suffix expanded into real bars, nine kit pieces (`CR RD HH T1 T2 S FT K HF`, long aliases accepted), six cell glyphs (`-` rest, `x` normal, `X` accent, `o` open, `g` ghost, `f` flam) with spacing optional. Forgiving: short rows pad with rests, over-long rows truncate, unknown pieces/cells collect into `errors` — never throws. Plus `KIT_PIECES` (label / GM `midi` / synth `sound` / `glyph`), `kitPiece(id)`, `CELL_GLYPHS` (per-glyph velocity + flags), `isDrumNotation(text)` (import-page format sniff, runs BEFORE `tabNotation.detectFormat`), `drumChartHasMusic(text)` and its already-parsed twin `chartHasMusic(chart)`. Also the plain-language explainers the sheet's tap-a-note readout and Legend panel read — `describeDrumCell(pieceId, cell)` → `{ pieceLabel, char, articulation, detail, technique, velocityPercent, rest }` (piece-aware: `o` is "Open" on a hi-hat/cymbal but a normal hit on a drum; a null/unknown cell describes as a rest, an unknown piece returns null), `describeDrumPosition(bar, step, subdivision)` → `bar 6, count “2 e”` (count-along syllables, exact `+n/N` fallback for an unconventional subdivision), `drumGlyphLegend(pieceIds)` (all six cell characters, with the `o` row resolved for the pieces a chart uses — a fixed row would tell a crash-only chart to work the hi-hat pedal; a mixed kit gets every applicable reading) and each `KIT_PIECES` row's `technique` (how that piece is struck). Only the hi-hat voice sustains an `o` in playback, so the `open` wording follows the piece's `sound`, not its glyph shape. NOT the lead-sheet parser (`scoreNotation.js`). || `drumPlayback.js` | Synthesized drum-kit play-along for the SongBook `drum` format (#3115) — the third consumer of `lookaheadTransport.js` alongside `scorePlayback`/`midiPlayback`. `buildDrumSchedule(chart, { bpm, loop, countInBars })` is the PURE chart→`[{ bar, step, piece, sound, velocity, startSec, durSec, countIn }]` mapping (one notated beat = `60/bpm`, one grid step = beat/`subdivision`; per-glyph velocity; a looped bar range is sliced and rebased while keeping the CHART's bar numbers for the playhead) — unit-tested with no Web Audio; `resolveLoopRange(barCount, loop)` clamps/normalizes a 1-based inclusive bar range; the count-in is scheduled as real `countIn: true` events on the same clock so there is no second timer. `createDrumPlayer(chart, { bpm, countInBars, loopBars, clickEnabled, clickVolume, kit, onStep, onEnded })` sounds it on the shared `AudioContext` from a SYNTHESIZED kit (no shipped samples — recipes in `drumKits.js`, realized here as per-layer oscillator/noise + optional tanh drive + optional filter into a soft-clipped master bus; open-hat tail, flam grace note) with an optional layered metronome click, loops the range scheduler-exactly (count-in only on the first pass), and reports `onStep({ bar, step, countIn })` for the `<DrumSheetView>` playhead. The metronome — the through-music click AND the count-in, which both sound `CLICK_VOICE`, never a kit piece — rides its OWN gain bus into the master, so `setClickVolume(0–1)` moves clicks already queued in the lookahead window instead of only the next ones (a level of 0 additionally schedules no click voice at all — the level persists, so a silenced click must not keep building a voice per beat forever) (`clampClickVolume` returns null for an unset/garbled level so a caller can tell "never chosen" from a stored `DEFAULT_CLICK_VOLUME`-vs-silence). `setKit(id)`, `setClick(enabled)` and `setClickVolume(level)` apply LIVE (they touch no timing, unlike `setBpm`/`setLoop`/`setCountIn`, which only rebuild while idle). Pure (no React) — `SongBookViewer` owns the transport UI. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 08f0e2b92c..f7dcbde6e1 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -117,6 +117,7 @@ export * from './midiNotes.js';export * from './midiPlayback.js';export * from './pianoKeyboard.js';export * from './pitchDetect.js';+export * from './seriesReviewProgress.js';export * from './powersBreakdown.js';export * from './promptStageGroups.js';export * from './referenceAnalysis.js';diff --git a/client/src/lib/seriesReviewProgress.js b/client/src/lib/seriesReviewProgress.jsnew file mode 100644index 0000000000..8a42328d00--- /dev/null+++ b/client/src/lib/seriesReviewProgress.js@@ -0,0 +1,96 @@+/**+ * Pure helpers for the "Review this series" SSE progress stream+ * (`server/services/pipeline/seriesReview.js#runSeriesReview`).+ *+ * Since #4108 the review runs the foundation judge and canon readiness+ * CONCURRENTLY with the editorial-checks pass, so the frame stream interleaves:+ * a `step:complete` for `foundation`/`canon` can land in the middle of a run of+ * `check:start`/`check:complete` frames. Labelling the single newest frame (the+ * pre-#4108 behaviour) therefore made the headline flip between "Judging+ * foundation done" and the current editorial check.+ *+ * `summarizeReviewProgress` fixes that by folding the whole frame list into the+ * set of steps still in flight plus the newest check frame, and picking ONE+ * stable headline (the editorial-checks pass while it runs — it is the noisiest+ * and longest-lived step) with the other in-flight steps reported alongside it.+ *+ * No React/window — the panel and its tests share these.+ */++// One-line label per review step kind.+export const REVIEW_STEP_LABELS = {+ foundation: 'Judging foundation',+ feedback: 'Routing your feedback',+ editorialChecks: 'Running editorial checks',+ canon: 'Checking canon descriptions',+ health: 'Scoring editorial health',+};++const stepLabel = (kind) => REVIEW_STEP_LABELS[kind] || kind;++// The frames that end a run — once one lands it is always the headline.+const TERMINAL_TYPES = new Set(['complete', 'canceled', 'error']);++/** One-line label for a single review SSE frame. */+export function reviewFrameLabel(f) {+ if (!f) return null;+ switch (f.type) {+ case 'start': return 'Starting review…';+ case 'step:start': return `${stepLabel(f.kind)}…`;+ case 'step:complete': return `${stepLabel(f.kind)} done`;+ case 'check:start': return `Editorial check: ${f.label || f.checkId}…`;+ case 'check:complete': return `Editorial check: ${f.label || f.checkId} — ${f.count ?? 0} finding(s)`;+ case 'complete': return 'Review complete';+ case 'canceled': return 'Review canceled';+ case 'error': return `Review failed — ${f.error}`;+ default: return f.type;+ }+}++/**+ * Fold the review frame stream into a coherent progress summary.+ *+ * @param {Array<object>} frames every frame received so far, in arrival order+ * @returns {{ headline: string|null, alsoRunning: string[] }}+ * `headline` — the single line to show as the current activity (null when no+ * frame has arrived yet, so the caller can fall back to its own placeholder).+ * `alsoRunning` — labels of the OTHER steps still in flight, so a concurrent+ * foundation judge stays visible while the checks pass owns the headline.+ */+export function summarizeReviewProgress(frames) {+ const list = Array.isArray(frames) ? frames.filter((f) => f && typeof f === 'object') : [];+ if (!list.length) return { headline: null, alsoRunning: [] };++ const terminal = [...list].reverse().find((f) => TERMINAL_TYPES.has(f.type));+ if (terminal) return { headline: reviewFrameLabel(terminal), alsoRunning: [] };++ // In-flight steps, in the order they started (a Map keeps insertion order and+ // re-adding after a delete moves the kind to the end, which is what we want).+ const active = new Map();+ let latestCheck = null;+ for (const f of list) {+ if (f.type === 'step:start' && f.kind) active.set(f.kind, true);+ else if (f.type === 'step:complete' && f.kind) active.delete(f.kind);+ else if (f.type === 'check:start' || f.type === 'check:complete') latestCheck = f;+ }++ // The editorial-checks pass owns the headline while it runs — it emits its own+ // per-check frames, so surfacing those keeps the line moving with real work+ // instead of flickering to a background step that just settled.+ if (active.has('editorialChecks') && latestCheck) {+ return { headline: reviewFrameLabel(latestCheck), alsoRunning: otherLabels(active, 'editorialChecks') };+ }+ const kinds = [...active.keys()];+ if (kinds.length) {+ // No checks pass in flight — the most recently started step is the headline.+ const primary = kinds[kinds.length - 1];+ return { headline: `${stepLabel(primary)}…`, alsoRunning: otherLabels(active, primary) };+ }+ // Nothing in flight and no terminal frame yet (e.g. between two steps) — fall+ // back to the newest frame so the line never goes blank mid-run.+ return { headline: reviewFrameLabel(list[list.length - 1]), alsoRunning: [] };+}++function otherLabels(active, primary) {+ return [...active.keys()].filter((k) => k !== primary).map(stepLabel);+}diff --git a/client/src/lib/seriesReviewProgress.test.js b/client/src/lib/seriesReviewProgress.test.jsnew file mode 100644index 0000000000..2ecccd4259--- /dev/null+++ b/client/src/lib/seriesReviewProgress.test.js@@ -0,0 +1,113 @@+import { describe, it, expect } from 'vitest';+import { reviewFrameLabel, summarizeReviewProgress, REVIEW_STEP_LABELS } from './seriesReviewProgress.js';++describe('reviewFrameLabel', () => {+ it('labels each step frame from the step table', () => {+ expect(reviewFrameLabel({ type: 'step:start', kind: 'foundation' })).toBe('Judging foundation…');+ expect(reviewFrameLabel({ type: 'step:complete', kind: 'canon' })).toBe('Checking canon descriptions done');+ });++ it('falls back to the raw kind for an unknown step', () => {+ expect(reviewFrameLabel({ type: 'step:start', kind: 'mystery' })).toBe('mystery…');+ });++ it('labels the editorial-check frames with their count', () => {+ expect(reviewFrameLabel({ type: 'check:start', label: 'Pacing' })).toBe('Editorial check: Pacing…');+ expect(reviewFrameLabel({ type: 'check:complete', label: 'Pacing', count: 3 })).toBe('Editorial check: Pacing — 3 finding(s)');+ expect(reviewFrameLabel({ type: 'check:complete', checkId: 'pacing' })).toBe('Editorial check: pacing — 0 finding(s)');+ });++ it('labels the terminal frames and tolerates a null frame', () => {+ expect(reviewFrameLabel({ type: 'complete' })).toBe('Review complete');+ expect(reviewFrameLabel({ type: 'canceled' })).toBe('Review canceled');+ expect(reviewFrameLabel({ type: 'error', error: 'boom' })).toBe('Review failed — boom');+ expect(reviewFrameLabel(null)).toBeNull();+ });+});++describe('summarizeReviewProgress', () => {+ it('returns a null headline before any frame arrives', () => {+ expect(summarizeReviewProgress([])).toEqual({ headline: null, alsoRunning: [] });+ expect(summarizeReviewProgress(undefined)).toEqual({ headline: null, alsoRunning: [] });+ });++ it('gives the headline to the only step in flight', () => {+ const s = summarizeReviewProgress([+ { type: 'start' },+ { type: 'step:start', kind: 'foundation' },+ ]);+ expect(s.headline).toBe('Judging foundation…');+ expect(s.alsoRunning).toEqual([]);+ });++ // The #4108 concurrency: foundation + canon are kicked off at entry, so their+ // frames interleave with the editorial checks' per-check frames.+ it('keeps the headline on the current editorial check while background passes run', () => {+ const s = summarizeReviewProgress([+ { type: 'step:start', kind: 'foundation' },+ { type: 'step:start', kind: 'canon' },+ { type: 'step:start', kind: 'editorialChecks' },+ { type: 'check:start', label: 'Pacing' },+ { type: 'step:complete', kind: 'canon' },+ { type: 'check:complete', label: 'Pacing', count: 2 },+ { type: 'check:start', label: 'Continuity' },+ ]);+ expect(s.headline).toBe('Editorial check: Continuity…');+ // Canon settled mid-pass, so only the still-running foundation is reported.+ expect(s.alsoRunning).toEqual(['Judging foundation']);+ });++ it('does not let a settled background step steal the headline', () => {+ const s = summarizeReviewProgress([+ { type: 'step:start', kind: 'foundation' },+ { type: 'step:start', kind: 'editorialChecks' },+ { type: 'check:start', label: 'Pacing' },+ { type: 'step:complete', kind: 'foundation', weightedScore: 8 },+ ]);+ expect(s.headline).toBe('Editorial check: Pacing…');+ expect(s.alsoRunning).toEqual([]);+ });++ it('falls back to the checks step itself before its first check frame', () => {+ const s = summarizeReviewProgress([+ { type: 'step:start', kind: 'foundation' },+ { type: 'step:start', kind: 'editorialChecks' },+ ]);+ expect(s.headline).toBe('Running editorial checks…');+ expect(s.alsoRunning).toEqual(['Judging foundation']);+ });++ it('moves to the health step once the checks pass completes', () => {+ const s = summarizeReviewProgress([+ { type: 'step:start', kind: 'foundation' },+ { type: 'step:start', kind: 'editorialChecks' },+ { type: 'check:complete', label: 'Pacing', count: 0 },+ { type: 'step:complete', kind: 'editorialChecks' },+ { type: 'step:start', kind: 'health' },+ ]);+ expect(s.headline).toBe('Scoring editorial health…');+ expect(s.alsoRunning).toEqual(['Judging foundation']);+ });++ it('shows the newest frame when nothing is in flight between steps', () => {+ const s = summarizeReviewProgress([+ { type: 'step:start', kind: 'feedback' },+ { type: 'step:complete', kind: 'feedback' },+ ]);+ expect(s.headline).toBe('Routing your feedback done');+ expect(s.alsoRunning).toEqual([]);+ });++ it('a terminal frame always wins, even with steps still marked in flight', () => {+ const s = summarizeReviewProgress([+ { type: 'step:start', kind: 'foundation' },+ { type: 'complete', verdict: 'issues' },+ ]);+ expect(s).toEqual({ headline: 'Review complete', alsoRunning: [] });+ });++ it('ignores non-object entries in the frame list', () => {+ const s = summarizeReviewProgress([null, 'nope', { type: 'step:start', kind: 'canon' }]);+ expect(s.headline).toBe(`${REVIEW_STEP_LABELS.canon}…`);+ });+});diff --git a/server/services/pipeline/seriesReview.js b/server/services/pipeline/seriesReview.jsindex 767c906061..971992ff19 100644--- a/server/services/pipeline/seriesReview.js+++ b/server/services/pipeline/seriesReview.js@@ -19,6 +19,11 @@* - free-text feedback → routed through runStageScopedInlineLLM to the best* issue/section and seeded as an anchored finding*+ * The foundation judge and canon readiness are kicked off at entry and awaited+ * just before the verdict, so they overlap the editorial-checks pass (#4108).+ * The only hard ordering constraint is the seed→read chain feedback-seed →+ * checks-seed → health/getReview, which stays strictly sequential.+ ** The review performs NO manuscript writes, so it is safe to run repeatedly. The* FIX path is deliberately NOT here: "Fix these issues" drives the existing* Series Autopilot revision cycle (cos-domain gate + budget + SSE) and the@@ -241,32 +246,63 @@ export async function runSeriesReview(seriesId, {const weights = mergeSeverityWeights(series?.severityWeights);const aborted = () => signal?.aborted;- // Stages that errored / never ran this pass — any of these makes the verdict- // untrustworthy, so it must never read 'ready' (fail closed). Surfaced on the- // result so the UI can warn the review is incomplete.- const failedStages = [];- // 1. Foundation judge (holistic pre-draft quality — catches "looks complete- // but no development"). Writes only its own snapshot. A throw is a genuine- // failure (judgeFoundation otherwise always returns a snapshot), not an- // absent-but-fine result — record it so the verdict fails closed.- onProgress({ type: 'step:start', kind: 'foundation' });- const foundation = await judgeFoundation(seriesId, { providerId: providerOverride, model: modelOverride, force })- .catch((err) => { console.error(`⚠️ series-review foundation judge failed — series=${seriesId.slice(0, 12)} ${err.message}`); failedStages.push('foundation'); return null; });- onProgress({ type: 'step:complete', kind: 'foundation', weightedScore: foundation?.weightedScore ?? null });- if (aborted()) return null;+ // The ONLY hard ordering constraint in this flow is the seed→read chain:+ // feedback-seed → checks-seed → health/getReview (both of which read the store+ // the first two write). The foundation judge writes only its own snapshot and+ // canon readiness is deterministic + store-independent, so both are kicked off+ // here at entry and awaited just before the verdict — overlapping the full+ // foundation LLM round-trip with the editorial-checks pass instead of running+ // before/after it (#4108).+ //+ // Each background pass owns its own `step:start`/`step:complete` frames and+ // swallows its own failure, so it resolves to `{ value, failed }` and never+ // rejects on the normal path. `kickOff` still attaches a no-op catch the+ // instant the promise exists, so an unexpected throw (e.g. from the caller's+ // `onProgress`) can't surface as an unhandled rejection when an early cancel+ // returns before the `await`.+ const kickOff = (fn) => { const p = fn(); p.catch(() => {}); return p; };++ const foundationTask = kickOff(async () => {+ // Foundation judge (holistic pre-draft quality — catches "looks complete but+ // no development"). A throw is a genuine failure (judgeFoundation otherwise+ // always returns a snapshot), not an absent-but-fine result — record it so+ // the verdict fails closed.+ onProgress({ type: 'step:start', kind: 'foundation' });+ let failed = false;+ const value = await judgeFoundation(seriesId, { providerId: providerOverride, model: modelOverride, force })+ .catch((err) => { console.error(`⚠️ series-review foundation judge failed — series=${seriesId.slice(0, 12)} ${err.message}`); failed = true; return null; });+ onProgress({ type: 'step:complete', kind: 'foundation', weightedScore: value?.weightedScore ?? null });+ return { value, failed };+ });++ const canonTask = kickOff(async () => {+ // Canon readiness (deterministic — no LLM). A throw is a genuine failure —+ // record it so the verdict fails closed rather than treating the missing+ // result as "canon fine".+ onProgress({ type: 'step:start', kind: 'canon' });+ let failed = false;+ const value = await checkSeriesCanonReadiness(seriesId)+ .catch((err) => { console.error(`⚠️ series-review canon readiness failed — series=${seriesId.slice(0, 12)} ${err.message}`); failed = true; return null; });+ onProgress({ type: 'step:complete', kind: 'canon', ready: value?.ready !== false });+ return { value, failed };+ });++ // A canceled run still settles the background passes before returning, so their+ // progress frames can never land after the SSE wrapper's `canceled` frame.+ const canceledResult = async () => { await Promise.allSettled([foundationTask, canonTask]); return null; };- // 2. Optional free-text feedback → anchored finding (before the checks pass so+ // 1. Optional free-text feedback → anchored finding (before the checks pass so// it merges into the same review the verdict reads).if (feedback && String(feedback).trim()) {onProgress({ type: 'step:start', kind: 'feedback' });await routeFeedbackToFinding(seriesId, feedback, { providerOverride, modelOverride, issues }).catch((err) => { console.error(`⚠️ series-review feedback seed failed — series=${seriesId.slice(0, 12)} ${err.message}`); });onProgress({ type: 'step:complete', kind: 'feedback' });- if (aborted()) return null;+ if (aborted()) return canceledResult();}- // 3. Editorial checks — registry-driven review; seeds the shared review store.+ // 2. Editorial checks — registry-driven review; seeds the shared review store.onProgress({ type: 'step:start', kind: 'editorialChecks' });// A runner-level REJECT (e.g. it threw while building shared context, before// producing any perCheck entries) is a whole-pass failure — the checks never@@ -277,7 +313,7 @@ export async function runSeriesReview(seriesId, {modelOverride,signal,onProgress,- }).catch((err) => { console.error(`⚠️ series-review editorial checks failed — series=${seriesId.slice(0, 12)} ${err.message}`); checksRunFailed = true; failedStages.push('editorialChecks'); return { findings: [], perCheck: [], canceled: false }; });+ }).catch((err) => { console.error(`⚠️ series-review editorial checks failed — series=${seriesId.slice(0, 12)} ${err.message}`); checksRunFailed = true; return { findings: [], perCheck: [], canceled: false }; });// A single check that threw (e.g. an unavailable LLM provider) is caught// internally by the runner and surfaced in perCheck as `{ checkId, error }` —// that dimension was never evaluated, so it too must block a 'ready' verdict.@@ -285,17 +321,9 @@ export async function runSeriesReview(seriesId, {.filter((p) => p && p.error).map((p) => p.checkId);const checksErrored = erroredCheckIds.length;onProgress({ type: 'step:complete', kind: 'editorialChecks', findingCount: checks?.findings?.length ?? 0, errored: checksErrored, failed: checksRunFailed });- if (aborted() || checks?.canceled) return null;+ if (aborted() || checks?.canceled) return canceledResult();- // 4. Canon readiness (deterministic — no LLM). A throw is a genuine failure —- // record it so the verdict fails closed rather than treating the missing- // result as "canon fine".- onProgress({ type: 'step:start', kind: 'canon' });- const canon = await checkSeriesCanonReadiness(seriesId)- .catch((err) => { console.error(`⚠️ series-review canon readiness failed — series=${seriesId.slice(0, 12)} ${err.message}`); failedStages.push('canon'); return null; });- onProgress({ type: 'step:complete', kind: 'canon', ready: canon?.ready !== false });-- // 5. Health + readiness + the seeded findings — both only READ the store the+ // 3. Health + readiness + the seeded findings — both only READ the store the// checks just seeded, so resolve them concurrently.onProgress({ type: 'step:start', kind: 'health' });const [health, review] = await Promise.all([@@ -304,6 +332,20 @@ export async function runSeriesReview(seriesId, {]);onProgress({ type: 'step:complete', kind: 'health', ready: health?.ready === true, score: health?.score ?? null });const findings = collectReviewFindings(review.comments);++ // 4. Join the background passes. Both resolve (never reject) with their own+ // failure flag, so the failed-stage list is assembled here in ONE place and+ // keeps a deterministic order regardless of which pass settled first.+ const [foundationRes, canonRes] = await Promise.all([foundationTask, canonTask]);+ const foundation = foundationRes.value;+ const canon = canonRes.value;+ // Stages that errored / never ran this pass — any of these makes the verdict+ // untrustworthy, so it must never read 'ready' (fail closed). Surfaced on the+ // result so the UI can warn the review is incomplete.+ const failedStages = [];+ if (foundationRes.failed) failedStages.push('foundation');+ if (checksRunFailed) failedStages.push('editorialChecks');+ if (canonRes.failed) failedStages.push('canon');if (!health) failedStages.push('health');const threshold = Number.isFinite(settings?.pipelineEditorialChecks?.foundationThreshold)? settings.pipelineEditorialChecks.foundationThresholddiff --git a/server/services/pipeline/seriesReview.run.test.js b/server/services/pipeline/seriesReview.run.test.jsnew file mode 100644index 0000000000..add76293b1--- /dev/null+++ b/server/services/pipeline/seriesReview.run.test.js@@ -0,0 +1,210 @@+/**+ * `runSeriesReview` orchestration — the concurrency + SSE-frame contract (#4108).+ *+ * The main `seriesReview.test.js` suite covers the pure composition helpers; this+ * one drives the whole runner with every collaborator stubbed, so it can assert+ * the two properties the parallelization has to preserve:+ *+ * 1. the seed→read chain stays strictly sequential (feedback-seed →+ * checks-seed → health/getReview), and+ * 2. the foundation judge + canon readiness actually OVERLAP the editorial+ * checks pass rather than bracketing it — including that a failure in one+ * still fails the verdict closed and never surfaces as an unhandled+ * rejection.+ */+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import { mkdtempSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'series-review-run-test-'));++vi.mock('../../lib/fileUtils.js', async (importActual) => {+ const actual = await importActual();+ return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };+});++// Every collaborator is a PARTIAL mock (spread the actual module first) — the+// pipeline modules re-export constants to each other, so a bare factory breaks+// an unrelated transitive import rather than this suite's subject.+// A function DECLARATION, not a const — `vi.mock` calls are hoisted above the+// module body, so a const initializer would not have run yet.+function partial(overrides) {+ return async (importActual) => ({ ...(await importActual()), ...overrides });+}++vi.mock('./series.js', partial({ getSeries: vi.fn(async () => ({ id: 'ser-test', severityWeights: null })) }));+vi.mock('./issues.js', partial({ listIssues: vi.fn(async () => []) }));+vi.mock('../settings.js', partial({ getSettings: vi.fn(async () => ({})) }));+vi.mock('../../lib/stageRunner.js', partial({ runStageScopedInlineLLM: vi.fn(async () => ({ content: {} })) }));++// The four passes whose interleaving this suite is about. Each appends to the+// shared `order` log so the test can read the real execution sequence.+const order = [];+vi.mock('./foundationJudge.js', partial({ judgeFoundation: vi.fn() }));+vi.mock('./canonReadiness.js', partial({ checkSeriesCanonReadiness: vi.fn() }));+vi.mock('./editorial/checkRunner.js', partial({ runEditorialChecks: vi.fn() }));+vi.mock('./editorialScore.js', partial({ getSeriesHealth: vi.fn() }));+vi.mock('./manuscriptReview.js', partial({ getReview: vi.fn(), seedReviewFromFindings: vi.fn() }));++const { judgeFoundation } = await import('./foundationJudge.js');+const { checkSeriesCanonReadiness } = await import('./canonReadiness.js');+const { runEditorialChecks } = await import('./editorial/checkRunner.js');+const { getSeriesHealth } = await import('./editorialScore.js');+const { getReview, seedReviewFromFindings } = await import('./manuscriptReview.js');+const { runSeriesReview } = await import('./seriesReview.js');++afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));++const tick = (n = 1) => Array.from({ length: n }).reduce((p) => p.then(() => {}), Promise.resolve());++beforeEach(() => {+ order.length = 0;+ vi.clearAllMocks();+ judgeFoundation.mockImplementation(async () => {+ order.push('foundation:start');+ await tick(4);+ order.push('foundation:end');+ return { weightedScore: 9, dimensions: {}, oneLineVerdict: 'fine', weakest: null, stale: false };+ });+ checkSeriesCanonReadiness.mockImplementation(async () => {+ order.push('canon:start');+ await tick(2);+ order.push('canon:end');+ return { ready: true, blockingIssues: [], undescribed: [] };+ });+ runEditorialChecks.mockImplementation(async () => {+ order.push('checks:start');+ await tick(6);+ order.push('checks:end');+ return { findings: [], perCheck: [], canceled: false };+ });+ getSeriesHealth.mockImplementation(async () => {+ order.push('health');+ return { score: 100, ready: true, open: 0, openBySeverity: {}, gate: 'clean' };+ });+ getReview.mockImplementation(async () => {+ order.push('getReview');+ return { comments: [] };+ });+ seedReviewFromFindings.mockImplementation(async () => {+ order.push('feedback:seed');+ return { comments: [] };+ });+});++const run = (opts = {}) => runSeriesReview('ser-test', opts);++describe('runSeriesReview — pass concurrency (#4108)', () => {+ it('overlaps the foundation judge and canon readiness with the editorial checks pass', async () => {+ const result = await run();+ expect(result.verdict).toBe('ready');+ // All three are in flight together: both background passes start before the+ // checks pass ends, and the checks pass starts before either finishes.+ expect(order.indexOf('foundation:start')).toBeLessThan(order.indexOf('checks:end'));+ expect(order.indexOf('canon:start')).toBeLessThan(order.indexOf('checks:end'));+ expect(order.indexOf('checks:start')).toBeLessThan(order.indexOf('foundation:end'));+ expect(order.indexOf('checks:start')).toBeLessThan(order.indexOf('canon:end'));+ });++ it('keeps the seed→read chain sequential: feedback-seed → checks-seed → health/getReview', async () => {+ await run({ feedback: 'the middle sags' });+ expect(order.indexOf('feedback:seed')).toBeLessThan(order.indexOf('checks:start'));+ expect(order.indexOf('checks:end')).toBeLessThan(order.indexOf('health'));+ expect(order.indexOf('checks:end')).toBeLessThan(order.indexOf('getReview'));+ });++ it('still carries every dimension into the verdict payload', async () => {+ const result = await run();+ expect(result.foundation).toMatchObject({ weightedScore: 9 });+ expect(result.canon).toMatchObject({ ready: true });+ expect(result.health).toMatchObject({ score: 100, ready: true });+ expect(result.failedStages).toEqual([]);+ expect(result.incomplete).toBe(false);+ });+});++describe('runSeriesReview — SSE frames under interleaving', () => {+ it('emits both background step:start frames before the checks pass starts', async () => {+ const frames = [];+ await run({ onProgress: (e) => frames.push(e) });+ const kinds = frames.filter((f) => f.type === 'step:start').map((f) => f.kind);+ expect(kinds).toEqual(['foundation', 'canon', 'editorialChecks', 'health']);+ });++ it('pairs every step:start with exactly one step:complete', async () => {+ const frames = [];+ await run({ feedback: 'note', onProgress: (e) => frames.push(e) });+ const starts = frames.filter((f) => f.type === 'step:start').map((f) => f.kind).sort();+ const completes = frames.filter((f) => f.type === 'step:complete').map((f) => f.kind).sort();+ expect(starts).toEqual(completes);+ expect(starts).toEqual(['canon', 'editorialChecks', 'feedback', 'foundation', 'health'].sort());+ });++ it('carries the settled values on the background step:complete frames', async () => {+ const frames = [];+ await run({ onProgress: (e) => frames.push(e) });+ expect(frames.find((f) => f.type === 'step:complete' && f.kind === 'foundation')).toMatchObject({ weightedScore: 9 });+ expect(frames.find((f) => f.type === 'step:complete' && f.kind === 'canon')).toMatchObject({ ready: true });+ });+});++describe('runSeriesReview — failure and cancellation paths', () => {+ it('fails the verdict closed when the foundation judge throws, in a stable stage order', async () => {+ judgeFoundation.mockRejectedValue(new Error('provider down'));+ checkSeriesCanonReadiness.mockRejectedValue(new Error('canon blew up'));+ const result = await run();+ expect(result.verdict).toBe('issues');+ expect(result.incomplete).toBe(true);+ expect(result.failedStages).toEqual(['foundation', 'canon']);+ expect(result.foundation).toBeNull();+ expect(result.canon).toBeNull();+ });++ it('reports a whole-pass editorial-checks failure without losing the background passes', async () => {+ runEditorialChecks.mockRejectedValue(new Error('context build failed'));+ const result = await run();+ expect(result.failedStages).toEqual(['editorialChecks']);+ expect(result.foundation).toMatchObject({ weightedScore: 9 });+ expect(result.canon).toMatchObject({ ready: true });+ });++ it('returns null on a canceled run only after the background passes have settled', async () => {+ const controller = new AbortController();+ runEditorialChecks.mockImplementation(async () => {+ order.push('checks:start');+ controller.abort();+ order.push('checks:end');+ return { findings: [], perCheck: [], canceled: true };+ });+ const result = await run({ signal: controller.signal });+ expect(result).toBeNull();+ // Both background passes ran to completion before the null return, so no+ // progress frame can land after the SSE wrapper's `canceled` frame.+ expect(order).toContain('foundation:end');+ expect(order).toContain('canon:end');+ });++ // The hazard the kicked-off-early/awaited-late shape introduces: when the MAIN+ // flow throws, it returns without ever awaiting the background tasks — so a+ // background task that also rejected would surface as an unhandled rejection+ // (fatal on Node ≥15). `runSeriesReview` attaches a catch at kickoff to make+ // that impossible.+ it('never leaves an unhandled background rejection when the main flow throws', async () => {+ const unhandled = [];+ const onUnhandled = (err) => unhandled.push(err);+ process.on('unhandledRejection', onUnhandled);+ // `onProgress` is caller-supplied (the SSE broadcast) — a throw from it+ // rejects the background task AND aborts the main flow at the same time.+ const err = await run({+ onProgress: (e) => { if (e.kind === 'foundation' || e.kind === 'editorialChecks') throw new Error('broadcast failed'); },+ }).catch((e) => e);+ // `unhandledRejection` fires when the microtask queue drains, so wait a full+ // macrotask — a microtask-only `tick()` would report a clean run either way.+ await new Promise((r) => setTimeout(r, 10));+ process.off('unhandledRejection', onUnhandled);+ expect(err).toBeInstanceOf(Error);+ expect(err.message).toBe('broadcast failed');+ expect(unhandled).toEqual([]);+ });+});