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([issue-2664]): holistic 'Review this series' flow — one verdict + confirm + fix at anchor
[._.]/ Adam Eivyd59d2d59a997
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 852cb8ede1..b458b8fba2 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -12,6 +12,8 @@## Added+- **[issue-2664] Holistic "Review this series" flow.** The series detail page gains a **Review this series** panel (above Autonomous mode) that runs every read-only check at once — the foundation judge (world/characters/arc/craft quality), the full editorial-checks pass, editorial health + readiness, and canon descriptive-integrity — and composes them into a single verdict (`ready` / `issues`) with signal chips (Foundation, Health, Canon) and every finding grouped by the issue it'd be patched at, each deep-linked to that section and to a per-finding **Fix here** in the manuscript editor. An optional free-text note ("Volume 1 looks complete but nothing develops") is routed by an LLM to the best issue/section and seeded as an anchored finding, so your own observation lands where it can be fixed. When issues are found, an inline confirm (no `window.confirm`) asks whether the story is good to move forward — **Looks good** dismisses, **Fix these issues** drives the existing Series Autopilot revision cycle (reusing the CoS-domain autonomy gate + budget + SSE — no second orchestrator) to patch findings at their anchors. The review performs no manuscript writes (safe to run repeatedly) and streams progress over SSE; with the CoS auto-run domain off it degrades gracefully — review still works read-only and each finding is fixable by hand. New service `server/services/pipeline/seriesReview.js` + `POST/GET /api/pipeline/series/:id/review`, both unit-tested.+- **[issue-2656] SongBook per-instrument view with chord voicings.** The song viewer's play mode gains a Guitar/Ukulele/Piano toggle (URL-addressable via `?view=`, defaulting to the song's own instrument — bass/voice/other render guitar shapes) that swaps how chords are visualized without touching the record. Every chord token in the sheet is now tappable/keyboard-accessible and opens a viewport-clamped popover with the voicing for the active instrument: an SVG fretbox (nut, finger dots, open/muted markers, and a fret-window label for barre shapes) for guitar and ukulele, or spelled note chips (letter-accurate — the 3rd of E is G#, never Ab) for piano. Slash chords voice the base chord and show the bass separately; unknown chords degrade to "no diagram" without crashing. A collapsible "Chords used" strip above the sheet shows a mini diagram for each unique chord in first-appearance order, diagrams follow the transpose control's chord names, and guitar-specific tab staffs collapse to a one-line note (with an inline "show" expand) in the ukulele/piano views. New pure lib `client/src/lib/chordShapes.js` (curated first-position guitar shapes + movable E-/A-form barre templates, an exact lowest-position search for ukulele GCEA, interval math for piano) and `ChordDiagram` component, both unit-tested.- **[issue-2593] URL-addressable building focus mode in City.** Clicking a building, minimap marker, or search match now focuses it in place at `/city/apps/:appId` instead of leaving City for `/apps/:id` — the camera flies to frame the whole borough (aspect- and HUD-safe-area aware, guarded against intersecting geometry) and the Intel pane is replaced (never overlapped) by a building-detail panel showing status, a process summary with unhealthy processes, and the app's active agents, plus an explicit **Open app** action to the real detail page and a **Close** back to the overview. The focused borough is visually distinguished (accent selection ring + expanded hologram) and its minimap dot exposes `aria-current` to assistive tech. Because the selection lives in the URL, reload/deep-link restores it once positions load, and browser back/forward moves between focused buildings and the overview; stale/deleted ids get an inline "building not found" fallback with a return-to-overview action. Entering Photo, History, or Drop In while focused deterministically clears focus first. On compact viewports the details render as the responsive HUD bottom sheet. New pure helpers `cityFocusCamera` (framing math, unit-tested) and `cityFocusState` (route-param resolution, unit-tested); new `CityFocusCamera` (in-canvas controller) and `CityFocusPanel` components.diff --git a/PLAN.md b/PLAN.mdindex 76c9e26bca..bd787d83c2 100644--- a/PLAN.md+++ b/PLAN.md@@ -65,3 +65,8 @@ by `/do:replan --issues`:drain parks. Prompt change → PROMPT_VERSIONS bump for claim-issue +claim-issue-gitlab (+ jira) with outgoing defaults preserved. Surfaced whilediagnosing a managed-app perpetual-drain churn.++### Series review ("Review this series", #2664) follow-ups++- [ ] **Parallelize the foundation judge + canon readiness with the editorial-checks pass in `runSeriesReview`** (`server/services/pipeline/seriesReview.js`). Today foundation (a full LLM round-trip) runs to completion before `runEditorialChecks` even starts, and canon sits idle until checks finish; only the seed→read chain (feedback-seed → checks-seed → health/getReview) is a real ordering constraint. `judgeFoundation` writes only its own snapshot and `checkSeriesCanonReadiness` is store-independent, so both can be kicked off at function entry and awaited just before `computeReviewVerdict`. Deferred from the /simplify pass because it changes the SSE progress-frame ordering (foundation/canon `step:*` frames would interleave with `check:*` frames) — needs the progress emits moved to kickoff/settle and a quick UX check that the interleaved stream still reads cleanly. Largest wall-clock win (~the foundation-judge duration).+- [ ] **Hoist the pipeline `port-error/port-warning` severity palette to a shared export** and use it in `SeriesReviewPanel.jsx` (`SEVERITY_STYLES`), `AutopilotPanel.jsx` (`SEVERITY_COLORS`), and `ArcCanvas.jsx` — three byte-for-byte inline copies today. Candidate home: `client/src/components/pipeline/manuscript/constants.js`. Deferred from /simplify because it touches two files outside the #2664 diff.diff --git a/client/src/components/pipeline/SeriesReviewPanel.jsx b/client/src/components/pipeline/SeriesReviewPanel.jsxnew file mode 100644index 0000000000..68668ea093--- /dev/null+++ b/client/src/components/pipeline/SeriesReviewPanel.jsx@@ -0,0 +1,384 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { Link } from 'react-router-dom';+import {+ ClipboardCheck, Loader2, CheckCircle2, AlertCircle, AlertTriangle, Wrench,+ ThumbsUp, X, MessageSquarePlus, ChevronRight,+} from 'lucide-react';+import toast from '../ui/Toast';+import { usePipelineProgress } from '../../hooks/usePipelineProgress';+import { severityRank } from '../../lib/editorialChecks';+import {+ startPipelineSeriesReview,+ getPipelineSeriesReview,+ getPipelineSeriesReviewStatus,+ cancelPipelineSeriesReview,+ pipelineSeriesReviewSseUrl,+ startPipelineAutopilot,+ pipelineAutopilotSseUrl,+ getPipelineSeries,+ listPipelineIssues,+} from '../../services/api';++const SEVERITY_STYLES = {+ high: 'text-port-error border-port-error/40 bg-port-error/10',+ medium: 'text-port-warning border-port-warning/40 bg-port-warning/10',+ low: 'text-gray-400 border-gray-500/30 bg-gray-700/20',+};++const RUN_ENDED = new Set(['complete', 'canceled', 'error']);+// The autopilot fix run also has a terminal `paused` state (budget / findings).+const FIX_RUN_ENDED = new Set(['complete', 'canceled', 'error', 'paused']);++// 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 autopilot fix run (the fix path reuses the autopilot+// orchestrator's SSE; we only need a terse "still working" line here).+function fixFrameLabel(f) {+ if (!f) return 'Working…';+ switch (f.type) {+ case 'start': return 'Starting fixes…';+ case 'step:start': return 'Fixing…';+ case 'paused': return `Paused — ${f.reason || 'needs review'}`;+ case 'complete': return 'Fixes complete';+ case 'canceled': return 'Fixing canceled';+ case 'error': return `Fixing failed — ${f.error}`;+ default: return 'Fixing…';+ }+}++// Group findings by the issue they'd be patched at (series-wide → null bucket,+// rendered last). Each group is deep-linked to that issue's manuscript section.+function groupFindings(findings) {+ const map = new Map();+ for (const f of Array.isArray(findings) ? findings : []) {+ const key = Number.isInteger(f.issueNumber) ? f.issueNumber : null;+ if (!map.has(key)) map.set(key, []);+ map.get(key).push(f);+ }+ return [...map.entries()]+ .sort((a, b) => (a[0] ?? Infinity) - (b[0] ?? Infinity))+ .map(([issueNumber, items]) => ({+ issueNumber,+ items: items.sort((x, y) => severityRank(x.severity) - severityRank(y.severity)),+ }));+}++/**+ * Holistic "Review this series" surface (#2664): one action runs the read-only+ * review passes, renders a single verdict with findings grouped by where they'd+ * be patched, and — via an inline confirm — drives the existing autopilot+ * revision cycle (or per-finding fixes) to patch them. No `window.confirm`.+ */+export default function SeriesReviewPanel({ series, onSeriesUpdate, onIssuesUpdate }) {+ const seriesId = series?.id;+ const [feedback, setFeedback] = useState('');+ const [reviewing, setReviewing] = useState(false);+ const [starting, setStarting] = useState(false);+ const [review, setReview] = useState(null);+ const [fixAvail, setFixAvail] = useState(null);+ const [fixing, setFixing] = useState(false);+ const [fixStarting, setFixStarting] = useState(false);+ const [confirmDismissed, setConfirmDismissed] = useState(false);++ const reviewRunIdRef = useRef(null);+ const fixRunIdRef = useRef(null);+ const onSeriesUpdateRef = useRef(onSeriesUpdate);+ const onIssuesUpdateRef = useRef(onIssuesUpdate);+ onSeriesUpdateRef.current = onSeriesUpdate;+ onIssuesUpdateRef.current = onIssuesUpdate;++ const { latest: reviewLatest, frames: reviewFrames } = usePipelineProgress(+ pipelineSeriesReviewSseUrl, [seriesId], { enabled: reviewing },+ );+ const { latest: fixLatest } = usePipelineProgress(+ pipelineAutopilotSseUrl, [seriesId], { enabled: fixing },+ );++ const loadVerdict = useCallback(async () => {+ if (!seriesId) return;+ const res = await getPipelineSeriesReview(seriesId, { silent: true }).catch(() => null);+ if (!res) return;+ if (res.review) { setReview(res.review); setConfirmDismissed(false); }+ if (res.fix) setFixAvail(res.fix);+ }, [seriesId]);++ // Initial load — restore the last verdict + re-attach to an in-flight review.+ useEffect(() => {+ if (!seriesId) return undefined;+ let canceled = false;+ loadVerdict();+ getPipelineSeriesReviewStatus(seriesId, { silent: true })+ .then((s) => { if (!canceled && s?.active) setReviewing(true); })+ .catch(() => null);+ return () => { canceled = true; };+ }, [seriesId, loadVerdict]);++ // Review run ended — fetch the fresh verdict on success.+ useEffect(() => {+ if (!reviewing || !reviewLatest || !RUN_ENDED.has(reviewLatest.type)) return;+ if (reviewRunIdRef.current && reviewLatest.runId && reviewLatest.runId !== reviewRunIdRef.current) return;+ setReviewing(false);+ if (reviewLatest.type === 'complete') {+ loadVerdict();+ toast.success(reviewLatest.verdict === 'ready' ? 'Review complete — looks ready' : 'Review complete — found issues to address');+ } else if (reviewLatest.type === 'canceled') {+ toast.success('Review canceled');+ } else {+ toast.error(reviewLatest.error || 'Review failed');+ }+ }, [reviewing, reviewLatest, loadVerdict]);++ // Fix run ended — refresh series + issues, re-run nothing (the user re-reviews+ // when ready).+ useEffect(() => {+ if (!fixing || !fixLatest || !FIX_RUN_ENDED.has(fixLatest.type)) return;+ if (fixRunIdRef.current && fixLatest.runId && fixLatest.runId !== fixRunIdRef.current) return;+ setFixing(false);+ getPipelineSeries(seriesId, { silent: true }).then((s) => { if (s) onSeriesUpdateRef.current?.(s); }).catch(() => null);+ listPipelineIssues(seriesId, { silent: true }).then((is) => onIssuesUpdateRef.current?.(Array.isArray(is) ? is : [])).catch(() => null);+ if (fixLatest.type === 'complete') toast.success('Fixes complete — re-review when ready');+ else if (fixLatest.type === 'paused') toast.warning(`Fixing paused — ${fixLatest.reason || 'needs review'}`);+ else if (fixLatest.type === 'canceled') toast.success('Fixing canceled');+ else toast.error(fixLatest.error || 'Fixing failed');+ }, [fixing, fixLatest, seriesId]);++ const runReview = useCallback(async () => {+ setStarting(true);+ // Only submit feedback while the textarea is actually shown (before the first+ // verdict). A Re-review after a verdict must NOT silently re-seed the same+ // stale note — the LLM-routed anchor can vary run-to-run, so it wouldn't dedup.+ const body = (!review && feedback.trim()) ? { feedback: feedback.trim() } : {};+ const res = await startPipelineSeriesReview(seriesId, body, { silent: true })+ .catch((err) => { toast.error(err.message || 'Could not start review'); return null; });+ setStarting(false);+ if (!res) return;+ reviewRunIdRef.current = res.runId || null;+ setReviewing(true);+ }, [seriesId, feedback, review]);++ const cancelReview = useCallback(async () => {+ await cancelPipelineSeriesReview(seriesId, { silent: true }).catch(() => null);+ }, [seriesId]);++ const startFix = useCallback(async () => {+ setFixStarting(true);+ // Reuse the existing autopilot orchestrator's revision cycle — no second+ // orchestrator. It reuses the cos-domain autonomy gate + budget + SSE.+ const res = await startPipelineAutopilot(seriesId, { revisionEnabled: true }, { silent: true })+ .catch((err) => {+ // cos domain off → 409; degrade gracefully (review still works read-only).+ toast.error(err?.message || 'Autonomous fixing is disabled — set the CoS auto-run domain to dry-run or execute.');+ return null;+ });+ setFixStarting(false);+ if (!res) return;+ fixRunIdRef.current = res.runId || null;+ setConfirmDismissed(true);+ setFixing(true);+ toast.success('Fixing started — iterating the weakest issues');+ }, [seriesId]);++ if (!seriesId) return null;++ const reviewLabel = reviewing ? (reviewFrameLabel(reviewLatest) || 'Working…') : null;+ const groups = review ? groupFindings(review.findings) : [];+ const hasIssues = review?.verdict === 'issues';+ const canFix = fixAvail?.canFix !== false;+ const showConfirm = hasIssues && !confirmDismissed && !fixing && !reviewing;++ return (+ <div className="border border-port-border rounded-lg bg-port-card/40">+ <div className="flex items-center gap-2 flex-wrap p-3">+ <ClipboardCheck size={15} className="text-port-accent" />+ <span className="text-sm font-medium text-white">Review this series</span>+ <span className="text-xs text-gray-500">runs every check, tells you what's wrong, then fixes it where best patched</span>++ <div className="ml-auto flex items-center gap-2">+ {!reviewing ? (+ <button+ type="button"+ onClick={runReview}+ disabled={starting}+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded text-sm font-medium border bg-port-bg text-port-accent border-port-border hover:border-port-accent/40 disabled:opacity-40"+ >+ {starting ? <Loader2 size={14} className="animate-spin" /> : <ClipboardCheck size={14} />}+ {review ? 'Re-review' : 'Review series'}+ </button>+ ) : (+ <button+ type="button"+ onClick={cancelReview}+ className="inline-flex items-center gap-1 px-3 py-1.5 rounded text-xs text-port-warning hover:text-white border border-port-warning/40 bg-port-bg hover:bg-port-warning/10"+ >+ <X size={12} /> Stop+ </button>+ )}+ </div>+ </div>++ {/* Optional free-text feedback */}+ {!reviewing && !review ? (+ <div className="px-3 pb-3 flex flex-col gap-1">+ <label htmlFor="series-review-feedback" className="text-xs text-gray-400 flex items-center gap-1.5">+ <MessageSquarePlus size={12} /> Anything specific you want the reviewer to look at or fix? (optional)+ </label>+ <textarea+ id="series-review-feedback"+ value={feedback}+ onChange={(e) => setFeedback(e.target.value)}+ rows={2}+ maxLength={4000}+ placeholder="e.g. Volume 1 looks complete but little actually develops — check the pacing."+ className="w-full px-2 py-1.5 rounded text-xs bg-port-bg border border-port-border text-gray-200 resize-y"+ />+ </div>+ ) : null}++ {/* 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">+ <Loader2 size={12} className="animate-spin text-port-accent" />+ {reviewLabel}+ </div>+ {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>)}+ </div>+ ) : null}+ </div>+ ) : null}++ {/* Verdict + findings */}+ {review && !reviewing ? (+ <div className="px-3 pb-3 border-t border-port-border pt-2 space-y-3">+ {/* Headline verdict */}+ <div className="flex items-center gap-2 text-sm">+ {review.verdict === 'ready' ? (+ <><CheckCircle2 size={15} className="text-port-success" /><span className="text-port-success">Looks ready to move forward.</span></>+ ) : (+ <><AlertTriangle size={15} className="text-port-warning" /><span className="text-port-warning">{review.findingCount || 0} issue(s) to address before moving forward.</span></>+ )}+ </div>++ {/* Signal chips */}+ <div className="flex flex-wrap gap-2 text-[11px]">+ {review.foundation && Number.isFinite(review.foundation.weightedScore) ? (+ <span className="px-2 py-0.5 rounded border border-port-border bg-port-bg text-gray-300" title={review.foundation.oneLineVerdict || ''}>+ Foundation {review.foundation.weightedScore}/10{review.foundation.weakest ? ` · weakest: ${review.foundation.weakest}` : ''}+ </span>+ ) : null}+ {review.health && Number.isFinite(review.health.score) ? (+ <span className={`px-2 py-0.5 rounded border ${review.health.ready ? 'border-port-success/40 text-port-success' : 'border-port-warning/40 text-port-warning'} bg-port-bg`}>+ Health {review.health.score}/100{review.health.ready ? ' · clean' : ''}+ </span>+ ) : null}+ {review.canon ? (+ <span className={`px-2 py-0.5 rounded border ${review.canon.ready ? 'border-port-success/40 text-port-success' : 'border-port-warning/40 text-port-warning'} bg-port-bg`}>+ Canon {review.canon.ready ? 'described' : `${review.canon.undescribed?.length || 0} undescribed`}+ </span>+ ) : null}+ </div>++ {/* Findings grouped by where they'd be patched */}+ {groups.length ? (+ <div className="space-y-2">+ {groups.map((g) => (+ <div key={g.issueNumber ?? 'series'} className="text-xs">+ <div className="uppercase tracking-wider text-gray-500 mb-1">+ {g.issueNumber != null ? (+ <Link to={`/pipeline/series/${seriesId}/manuscript/${g.issueNumber}`} className="text-port-accent hover:underline">+ #{g.issueNumber} →+ </Link>+ ) : 'Series-wide'}+ </div>+ <ul className="space-y-1">+ {g.items.map((f) => (+ <li key={f.commentId} className={`p-2 rounded border ${SEVERITY_STYLES[f.severity] || SEVERITY_STYLES.medium}`}>+ <div className="flex items-center gap-2">+ <AlertCircle size={11} />+ <span className="uppercase tracking-wider font-semibold text-[10px]">{f.severity}</span>+ {f.checkId ? <span className="text-gray-500 text-[10px]">{f.checkId}</span> : null}+ <Link+ to={`/pipeline/findings/${f.commentId}`}+ className="ml-auto inline-flex items-center gap-0.5 text-port-accent hover:underline text-[10px]"+ title="Open this finding in the manuscript editor to generate and accept a fix"+ >+ Fix here <ChevronRight size={10} />+ </Link>+ </div>+ <p className="text-gray-200 mt-0.5">{f.summary}</p>+ </li>+ ))}+ </ul>+ </div>+ ))}+ </div>+ ) : null}++ {/* Inline confirm — "good to move forward?" (no window.confirm) */}+ {showConfirm ? (+ <div className="rounded border border-port-border bg-port-bg p-2 flex items-center gap-2 flex-wrap">+ <span className="text-xs text-gray-300">Is the story so far good to move forward?</span>+ <div className="ml-auto flex items-center gap-2">+ <button+ type="button"+ onClick={() => setConfirmDismissed(true)}+ className="inline-flex items-center gap-1 px-2.5 py-1 rounded text-xs text-gray-300 hover:text-white border border-port-border hover:border-port-success/40"+ >+ <ThumbsUp size={12} /> Looks good+ </button>+ <button+ type="button"+ onClick={startFix}+ disabled={fixStarting || !canFix}+ title={canFix ? 'Iterate the weakest issues via the autopilot revision cycle' : 'Autonomous fixing is disabled — set the CoS auto-run domain to dry-run or execute'}+ className="inline-flex items-center gap-1 px-2.5 py-1 rounded text-xs font-medium text-port-accent border border-port-border bg-port-bg hover:border-port-accent/40 disabled:opacity-40"+ >+ {fixStarting ? <Loader2 size={12} className="animate-spin" /> : <Wrench size={12} />} Fix these issues+ </button>+ </div>+ {!canFix ? (+ <p className="w-full text-[11px] text-gray-500 mt-1">+ Auto-fixing is off (CoS auto-run domain is disabled). You can still open each finding above and fix it manually.+ </p>+ ) : null}+ </div>+ ) : null}+ </div>+ ) : null}++ {/* Fix run progress */}+ {fixing ? (+ <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">+ <Loader2 size={12} className="animate-spin text-port-accent" />+ {fixFrameLabel(fixLatest)}+ </div>+ </div>+ ) : null}+ </div>+ );+}diff --git a/client/src/lib/editorialChecks.js b/client/src/lib/editorialChecks.jsindex 27c2864ec4..8a28783239 100644--- a/client/src/lib/editorialChecks.js+++ b/client/src/lib/editorialChecks.js@@ -253,7 +253,9 @@ export function findingManuscriptLink(seriesId, comment) {const FINDING_SEVERITY_RANK = Object.freeze({ high: 0, medium: 1, low: 2 });const FINDING_STATUS_RANK = Object.freeze({ open: 0, accepted: 1, dismissed: 2 });-const severityRank = (s) => (s in FINDING_SEVERITY_RANK ? FINDING_SEVERITY_RANK[s] : 2);+/** Sort rank for a finding severity (high=0, medium=1, low/unknown=2) — the+ * canonical order the triage view + any findings list sort by. */+export const severityRank = (s) => (s in FINDING_SEVERITY_RANK ? FINDING_SEVERITY_RANK[s] : 2);const statusRank = (s) => (s in FINDING_STATUS_RANK ? FINDING_STATUS_RANK[s] : 99);const normSeverity = (c) => (c?.severity in FINDING_SEVERITY_RANK ? c.severity : 'low');const normStatus = (c) => (c?.status === 'accepted' || c?.status === 'dismissed' ? c.status : 'open');diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsxindex d4a3a7604e..2b9ac5bca4 100644--- a/client/src/pages/PipelineSeries.jsx+++ b/client/src/pages/PipelineSeries.jsx@@ -20,6 +20,7 @@ import {import toast from '../components/ui/Toast';import ArcCanvas from '../components/pipeline/ArcCanvas';import AutopilotPanel from '../components/pipeline/AutopilotPanel';+import SeriesReviewPanel from '../components/pipeline/SeriesReviewPanel';import CatalogCastPanel from '../components/CatalogCastPanel';import TabPills from '../components/ui/TabPills';import {@@ -268,6 +269,12 @@ export default function PipelineSeries() {</button></header>+ <SeriesReviewPanel+ series={series}+ onSeriesUpdate={updateSeriesFromServer}+ onIssuesUpdate={handleIssuesUpdate}+ />+<AutopilotPanelseries={series}onSeriesUpdate={updateSeriesFromServer}diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex d3aa319b95..1fb6c57951 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -952,6 +952,40 @@ export const getPipelineAutopilotStatus = (seriesId, options = {}) =>export const pipelineAutopilotSseUrl = (seriesId) =>`/api/pipeline/series/${encodeURIComponent(seriesId)}/autopilot/progress`;+// ---- Holistic "Review this series" (#2664) ----+// Composes the foundation judge + editorial checks + health/readiness + canon+// into ONE read-only verdict (no manuscript writes). Optional free-text feedback+// is routed into an anchored finding. Fixing reuses the autopilot revision cycle+// (startPipelineAutopilot) + per-finding manuscriptFix — not a second orchestrator.++// Last stored verdict + current fix availability:+// { review: { verdict, foundation, health, canon, findings, ... } | null,+// fix: { mode, canFix } }.+export const getPipelineSeriesReview = (seriesId, options = {}) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/review`, options);++// Kick off a review. { runId, alreadyRunning, sseUrl } — subscribe via+// pipelineSeriesReviewSseUrl, then re-fetch the verdict on `complete`.+export const startPipelineSeriesReview = (seriesId, opts = {}, options = {}) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/review`, {+ method: 'POST',+ body: JSON.stringify(opts),+ ...options,+ });++// { active: boolean } — lets a (re)mounting view re-attach to an in-flight review.+export const getPipelineSeriesReviewStatus = (seriesId, options = {}) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/review/status`, options);++export const cancelPipelineSeriesReview = (seriesId, options = {}) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/review/cancel`, {+ method: 'POST',+ ...options,+ });++export const pipelineSeriesReviewSseUrl = (seriesId) =>+ `/api/pipeline/series/${encodeURIComponent(seriesId)}/review/progress`;+// ---- Canon descriptive-integrity (production readiness) ----// Read-only: which canon nouns appear where they'd be drawn but lack a// description (blocking visual production).diff --git a/server/routes/pipeline/editorial.js b/server/routes/pipeline/editorial.jsindex 469ccba12d..4cab37d7bd 100644--- a/server/routes/pipeline/editorial.js+++ b/server/routes/pipeline/editorial.js@@ -35,6 +35,7 @@ import * as readerPanelRunner from '../../services/pipeline/readerPanelRunner.jsimport * as comparativeRank from '../../services/pipeline/editorial/comparativeRank.js';import * as voiceFingerprint from '../../services/pipeline/voiceFingerprint.js';import * as checkRunner from '../../services/pipeline/editorial/checkRunner.js';+import * as seriesReview from '../../services/pipeline/seriesReview.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';@@ -215,6 +216,66 @@ router.post('/series/:id/editorial/rank', asyncHandler(async (req, res) => {res.json(await comparativeRank.runComparativeRank(req.params.id, body));}));+// ---------------------------------------------------------------------------+// Holistic "Review this series" flow (#2664) — composes the foundation judge ++// editorial checks + health/readiness + canon readiness into ONE read-only+// verdict, streamed over SSE. Optional free-text feedback is routed into an+// anchored finding. No manuscript writes (safe to run repeatedly). The FIX path+// reuses the existing autopilot revision cycle + per-finding manuscriptFix+// routes — it is NOT here.+// ---------------------------------------------------------------------------++// Optional free-text observation + provider/model overrides + a per-run+// readiness-gate override + `force` (re-judge an unchanged foundation).+const seriesReviewRunSchema = z.object({+ feedback: z.string().trim().max(4000).optional(),+ providerId: z.string().trim().max(80).optional(),+ model: z.string().trim().max(200).optional(),+ force: z.boolean().optional(),+ readinessGate: z.enum([...READINESS_GATES]).optional(),+});++// Last stored verdict (+ current fix availability from the cos-domain gate), or+// `{ review: null, fix }` when never run — so a (re)mounting client can reload+// without re-running.+router.get('/series/:id/review', asyncHandler(async (req, res) => {+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });+ res.json(await seriesReview.getSeriesReview(req.params.id));+}));++// Kick off the holistic review (batch — progress via SSE).+router.post('/series/:id/review', asyncHandler(async (req, res) => {+ const body = validateRequest(seriesReviewRunSchema, req.body ?? {});+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });+ const result = seriesReview.startSeriesReviewRun(req.params.id, {+ feedback: body.feedback,+ providerOverride: body.providerId,+ modelOverride: body.model,+ force: body.force,+ readinessGate: body.readinessGate,+ });+ res.json({+ ...result,+ sseUrl: `/api/pipeline/series/${req.params.id}/review/progress`,+ });+}));++router.get('/series/:id/review/progress', (req, res) => {+ const attached = seriesReview.attachClient(req.params.id, res);+ if (!attached) {+ throw new ServerError('No active series review for this series', { status: 404 });+ }+});++// Lightweight probe so a (re)mounting client can re-attach to an in-flight review.+router.get('/series/:id/review/status', (req, res) => {+ res.json({ active: seriesReview.isSeriesReviewActive(req.params.id) });+});++router.post('/series/:id/review/cancel', asyncHandler(async (req, res) => {+ res.json({ canceled: seriesReview.cancelSeriesReview(req.params.id) });+}));+// ---------------------------------------------------------------------------// Editorial checks (#1284) — registry-driven editorial review.// ---------------------------------------------------------------------------diff --git a/server/routes/pipeline/editorial.test.js b/server/routes/pipeline/editorial.test.jsindex 171ef64d6b..d3379cb6b9 100644--- a/server/routes/pipeline/editorial.test.js+++ b/server/routes/pipeline/editorial.test.js@@ -56,6 +56,18 @@ vi.mock('../../services/pipeline/editorialScore.js', async (importOriginal) => (getSeriesHealth: (...a) => getSeriesHealth(...a),}));+// Holistic series-review service (#2664) — stub so the route test exercises the+// param-validation + series-resolve wiring without running the composed passes.+const startSeriesReviewRun = vi.fn(() => ({ runId: 'rev-1', alreadyRunning: false }));+const getSeriesReview = vi.fn(async () => ({ review: { seriesId: 'ser-1', verdict: 'issues', findings: [] }, fix: { mode: 'execute', canFix: true } }));+vi.mock('../../services/pipeline/seriesReview.js', () => ({+ startSeriesReviewRun: (...a) => startSeriesReviewRun(...a),+ getSeriesReview: (...a) => getSeriesReview(...a),+ attachClient: vi.fn(() => false),+ isSeriesReviewActive: vi.fn(() => false),+ cancelSeriesReview: vi.fn(() => true),+}));+const editorialRoutes = (await import('./editorial.js')).default;const app = express();@@ -69,6 +81,53 @@ beforeEach(() => {previewCustomCheck.mockClear();getSeriesHealth.mockClear();getVoiceFingerprint.mockClear();+ startSeriesReviewRun.mockClear();+ getSeriesReview.mockClear();+});++describe('Holistic "Review this series" (#2664)', () => {+ it('POST /series/:id/review starts a run and returns the SSE url', async () => {+ const res = await request(app)+ .post('/api/pipeline/series/ser-1/review')+ .send({ feedback: 'volume 1 has no real development' });+ expect(res.status).toBe(200);+ expect(res.body.runId).toBe('rev-1');+ expect(res.body.sseUrl).toBe('/api/pipeline/series/ser-1/review/progress');+ expect(startSeriesReviewRun).toHaveBeenCalledWith('ser-1', expect.objectContaining({ feedback: 'volume 1 has no real development' }));+ });++ it('POST /series/:id/review threads provider/model/readinessGate overrides', async () => {+ await request(app)+ .post('/api/pipeline/series/ser-1/review')+ .send({ providerId: 'openai', model: 'gpt-x', readinessGate: 'noOpenHighOrMedium' });+ expect(startSeriesReviewRun).toHaveBeenCalledWith('ser-1', expect.objectContaining({+ providerOverride: 'openai', modelOverride: 'gpt-x', readinessGate: 'noOpenHighOrMedium',+ }));+ });++ it('POST /series/:id/review 400s on an invalid readiness gate', async () => {+ const res = await request(app).post('/api/pipeline/series/ser-1/review').send({ readinessGate: 'bogus' });+ expect(res.status).toBe(400);+ });++ it('POST /series/:id/review 404s for a missing series', async () => {+ const res = await request(app).post('/api/pipeline/series/missing/review').send({});+ expect(res.status).toBe(404);+ expect(startSeriesReviewRun).not.toHaveBeenCalled();+ });++ it('GET /series/:id/review returns the stored verdict + fix availability', async () => {+ const res = await request(app).get('/api/pipeline/series/ser-1/review');+ expect(res.status).toBe(200);+ expect(res.body.review.verdict).toBe('issues');+ expect(res.body.fix).toEqual({ mode: 'execute', canFix: true });+ });++ it('GET /series/:id/review/status reports active=false when no run is in flight', async () => {+ const res = await request(app).get('/api/pipeline/series/ser-1/review/status');+ expect(res.status).toBe(200);+ expect(res.body.active).toBe(false);+ });});describe('GET /api/pipeline/series/:id/voice-fingerprint (#2194)', () => {diff --git a/server/services/pipeline/seriesReview.js b/server/services/pipeline/seriesReview.jsnew file mode 100644index 0000000000..edc5a6bd14--- /dev/null+++ b/server/services/pipeline/seriesReview.js@@ -0,0 +1,383 @@+/**+ * Pipeline — holistic "Review this series" flow (#2664).+ *+ * Composes the existing read-only review passes into ONE structured verdict the+ * user can act on: run the foundation judge + editorial checks + editorial+ * health/readiness + canon readiness, optionally route a free-text user+ * observation into an anchored finding, and return a single+ * `{ verdict: 'ready' | 'issues', foundation, health, canon, findings }` payload.+ *+ * This is a COMPOSITION layer — it reuses the existing runners verbatim and adds+ * no new AI plumbing and no second orchestrator:+ * - foundation judge → foundationJudge.judgeFoundation (writes only its own+ * snapshot; never touches the manuscript)+ * - editorial checks → editorial/checkRunner.runEditorialChecks (seeds the+ * shared manuscript-review store with findings — the+ * same store the fix path reads; NOT a manuscript write)+ * - health/readiness → editorialScore.getSeriesHealth+ * - canon readiness → canonReadiness.checkSeriesCanonReadiness (deterministic)+ * - free-text feedback → routed through runStageScopedInlineLLM to the best+ * issue/section and seeded as an anchored finding+ *+ * 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+ * per-finding manuscriptFix routes — this service only produces the verdict.+ *+ * Progress streams over SSE via the shared `createSseRunner` (mirrors+ * checkRunner / editorialAnalysisRunner). The last verdict persists at+ * `data/pipeline-series-review/{seriesId}.json` so a (re)mounting client can+ * reload it without re-running.+ *+ * AI-provider policy: this fires ONLY from the explicit user "Review this+ * series" action — never at boot.+ */++import { join } from 'path';+import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../../lib/fileUtils.js';+import { createSseRunner } from '../../lib/sseUtils.js';+import { runStageScopedInlineLLM } from '../../lib/stageRunner.js';+import { getDomainMode } from '../../lib/domainAutonomy.js';+import { readReadinessGate, mergeSeverityWeights } from '../../lib/editorial/index.js';+import { loadState } from '../cosState.js';+import { getSettings } from '../settings.js';+import { getSeries } from './series.js';+import { listIssues } from './issues.js';+import { judgeFoundation, DEFAULT_FOUNDATION_THRESHOLD } from './foundationJudge.js';+import { runEditorialChecks } from './editorial/checkRunner.js';+import { getSeriesHealth, isOpenFinding, DEFAULT_READINESS_GATE } from './editorialScore.js';+import { checkSeriesCanonReadiness } from './canonReadiness.js';+import { getReview, seedReviewFromFindings } from './manuscriptReview.js';++// The stage whose provider/model pins the free-text-feedback routing call, so a+// user observation about the manuscript is judged on the SAME provider the arc+// authoring uses (never silently routed elsewhere). Mirrors foundationJudge's+// WRITER_STAGE indirection.+const FEEDBACK_STAGE = 'pipeline-arc-overview';+const FEEDBACK_MAX = 4000;++const nowIso = () => new Date().toISOString();++// Defense-in-depth: refuse path-traversal-shaped ids before interpolating into+// the on-disk snapshot path (series ids are `ser-<uuid>`). Mirrors the sibling+// pipeline services.+function assertValidSeriesId(id) {+ if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(id)) {+ throw new Error(`Invalid series id: ${id}`);+ }+}++const reviewDir = () => join(PATHS.data, 'pipeline-series-review');+const snapshotPath = (seriesId) => join(reviewDir(), `${seriesId}.json`);++const SEVERITY_RANK = { high: 0, medium: 1, low: 2 };++// ---------------------------------------------------------------------------+// Pure composition helpers (unit-tested in isolation).+// ---------------------------------------------------------------------------++/**+ * The single 'ready' | 'issues' verdict. A series is only "ready to move+ * forward" when the editorial-health readiness gate is clean AND the foundation+ * clears the quality threshold AND every drawn noun is described (canon ready).+ * Any of those failing → 'issues'. Pure.+ */+export function computeReviewVerdict({ health, foundation, canon, threshold = DEFAULT_FOUNDATION_THRESHOLD } = {}) {+ const healthReady = health?.ready === true;+ const foundationReady = !foundation || !Number.isFinite(foundation.weightedScore)+ ? true+ : foundation.weightedScore >= threshold;+ const canonReady = canon?.ready !== false;+ return healthReady && foundationReady && canonReady ? 'ready' : 'issues';+}++/**+ * Project the manuscript-review store's OPEN comments into the review's flat+ * findings list, each carrying the `commentId` the per-finding fix path needs+ * plus the anchoring fields the UI groups + deep-links by. Sorted high→low+ * severity, then by issue number (series-scoped nulls last). Pure.+ */+export function collectReviewFindings(comments) {+ const open = (Array.isArray(comments) ? comments : []).filter((c) => c && typeof c === 'object' && isOpenFinding(c));+ return open+ .map((c) => ({+ commentId: c.id,+ severity: c.severity in SEVERITY_RANK ? c.severity : 'medium',+ checkId: typeof c.checkId === 'string' ? c.checkId : null,+ issueId: typeof c.issueId === 'string' ? c.issueId : null,+ issueNumber: Number.isInteger(c.issueNumber) ? c.issueNumber : null,+ location: typeof c.location === 'string' ? c.location : '',+ anchorQuote: typeof c.anchorQuote === 'string' ? c.anchorQuote : '',+ summary: typeof c.problem === 'string' ? c.problem : '',+ }))+ .sort((a, b) => {+ const s = (SEVERITY_RANK[a.severity] ?? 1) - (SEVERITY_RANK[b.severity] ?? 1);+ if (s !== 0) return s;+ return (a.issueNumber ?? Infinity) - (b.issueNumber ?? Infinity);+ });+}++/**+ * Build the inline prompt that routes a free-text user observation to the best+ * issue + anchor. Given the issue roster (number + title) and the feedback, the+ * model returns a single finding JSON. Pure.+ */+export function buildFeedbackRoutePrompt(feedback, issues) {+ const roster = (Array.isArray(issues) ? issues : [])+ .map((i) => `- #${i.number}: ${i.title || '(untitled)'}`)+ .join('\n') || '(no issues yet)';+ return [+ 'You are an editorial triage assistant. A reader has left a free-text note about a series.',+ 'Route the note to the single BEST place to patch it, as one JSON object.',+ '',+ 'Series issues (number: title):',+ roster,+ '',+ 'Reader note:',+ `"""${feedback}"""`,+ '',+ 'Return ONLY a JSON object with these keys:',+ ' issueNumber — the issue number the note is about, or null if it is series-wide',+ ' severity — "high" | "medium" | "low"',+ ' location — a short human label for where this applies (e.g. "Volume 1 pacing")',+ ' problem — a one-to-two sentence restatement of the concern as an editorial finding',+ ' suggestion — a concrete suggested fix (may be empty)',+ ' anchorQuote — a short verbatim quote from the manuscript to anchor the fix, or "" if unknown',+ '',+ 'Do not invent an issue number that is not in the list above; use null when unsure.',+ ].join('\n');+}++/**+ * Shape the LLM's routed-feedback response into a finding for+ * seedReviewFromFindings, tolerant of malformed/absent output. Falls back to a+ * series-level finding carrying the raw feedback so a user observation ALWAYS+ * lands (never silently dropped). `validNumbers` is the set of real issue+ * numbers — a hallucinated number degrades to a series-level (null) finding.+ * Pure.+ */+export function shapeFeedbackFinding(parsed, { feedback, validNumbers } = {}) {+ const p = parsed && typeof parsed === 'object' ? parsed : {};+ const valid = validNumbers instanceof Set ? validNumbers : new Set(validNumbers || []);+ const issueNumber = Number.isInteger(p.issueNumber) && valid.has(p.issueNumber) ? p.issueNumber : null;+ const severity = p.severity in SEVERITY_RANK ? p.severity : 'medium';+ const problem = (typeof p.problem === 'string' && p.problem.trim())+ ? p.problem.trim()+ : String(feedback || '').trim();+ return {+ issueNumber,+ severity,+ category: 'user-feedback',+ location: typeof p.location === 'string' ? p.location.slice(0, 200) : '',+ problem: problem.slice(0, 2000),+ suggestion: typeof p.suggestion === 'string' ? p.suggestion.slice(0, 8000) : '',+ anchorQuote: typeof p.anchorQuote === 'string' ? p.anchorQuote.slice(0, 400) : '',+ // Marks the finding as a user observation so it groups distinctly from the+ // automated checks and the dedup key can't collide with a real check.+ checkId: 'user-feedback',+ };+}++// ---------------------------------------------------------------------------+// Free-text feedback routing (one inline LLM call, seeded as a finding).+// ---------------------------------------------------------------------------++async function routeFeedbackToFinding(seriesId, feedback, { providerOverride, modelOverride, issues }) {+ const trimmed = String(feedback || '').trim();+ if (!trimmed) return null;+ const prompt = buildFeedbackRoutePrompt(trimmed.slice(0, FEEDBACK_MAX), issues);+ // Never fail the whole review on a bad routing call — fall back to a+ // series-level finding carrying the raw note so the observation still lands.+ let parsed = null;+ await runStageScopedInlineLLM(FEEDBACK_STAGE, prompt, {+ returnsJson: true,+ providerOverride,+ modelOverride,+ source: 'series-review-feedback',+ })+ .then((r) => { parsed = r?.content ?? null; })+ .catch((err) => { console.error(`⚠️ series-review feedback routing failed — series=${seriesId.slice(0, 12)} ${err.message}`); });+ const validNumbers = new Set((Array.isArray(issues) ? issues : []).map((i) => i.number).filter(Number.isInteger));+ const finding = shapeFeedbackFinding(parsed, { feedback: trimmed, validNumbers });+ const review = await seedReviewFromFindings(seriesId, [finding], { mode: 'merge', checkId: 'user-feedback' });+ return { finding, review };+}++// ---------------------------------------------------------------------------+// Core read-only review.+// ---------------------------------------------------------------------------++/**+ * Run the holistic read-only review. Returns the structured verdict. Emits+ * progress via `onProgress(event)` (each event a `{ type, ... }` frame). No+ * manuscript writes — safe to run repeatedly.+ *+ * @param {string} seriesId+ * @param {object} [opts]+ * @param {string} [opts.feedback] optional free-text user observation+ * @param {string} [opts.providerOverride] provider override for the LLM passes+ * @param {string} [opts.modelOverride] model override for the LLM passes+ * @param {boolean} [opts.force] re-judge an unchanged foundation+ * @param {string} [opts.readinessGate] per-run readiness-gate override+ * @param {AbortSignal} [opts.signal] cancellation+ * @param {(event: object) => void} [opts.onProgress]+ */+export async function runSeriesReview(seriesId, {+ feedback, providerOverride, modelOverride, force = false, readinessGate, signal, onProgress = () => {},+} = {}) {+ assertValidSeriesId(seriesId);+ // Three independent reads — resolve concurrently.+ const [series, settings, issues] = await Promise.all([+ getSeries(seriesId),+ getSettings().catch(() => null),+ listIssues({ seriesId }).catch(() => []),+ ]);+ const gate = readinessGate || readReadinessGate(settings) || DEFAULT_READINESS_GATE;+ const weights = mergeSeverityWeights(series?.severityWeights);++ const aborted = () => signal?.aborted;++ // 1. Foundation judge (holistic pre-draft quality — catches "looks complete+ // but no development"). Writes only its own snapshot.+ 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}`); return null; });+ onProgress({ type: 'step:complete', kind: 'foundation', weightedScore: foundation?.weightedScore ?? null });+ if (aborted()) return null;++ // 2. 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;+ }++ // 3. Editorial checks — registry-driven review; seeds the shared review store.+ onProgress({ type: 'step:start', kind: 'editorialChecks' });+ const checks = await runEditorialChecks(seriesId, {+ providerOverride,+ modelOverride,+ signal,+ onProgress,+ }).catch((err) => { console.error(`⚠️ series-review editorial checks failed — series=${seriesId.slice(0, 12)} ${err.message}`); return { findings: [], perCheck: [], canceled: false }; });+ onProgress({ type: 'step:complete', kind: 'editorialChecks', findingCount: checks?.findings?.length ?? 0 });+ if (aborted() || checks?.canceled) return null;++ // 4. Canon readiness (deterministic — no LLM).+ onProgress({ type: 'step:start', kind: 'canon' });+ const canon = await checkSeriesCanonReadiness(seriesId).catch(() => null);+ onProgress({ type: 'step:complete', kind: 'canon', ready: canon?.ready !== false });++ // 5. 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([+ getSeriesHealth(seriesId, { gate, weights }).catch(() => null),+ getReview(seriesId).catch(() => ({ comments: [] })),+ ]);+ onProgress({ type: 'step:complete', kind: 'health', ready: health?.ready === true, score: health?.score ?? null });+ const findings = collectReviewFindings(review.comments);+ const threshold = Number.isFinite(settings?.pipelineEditorialChecks?.foundationThreshold)+ ? settings.pipelineEditorialChecks.foundationThreshold+ : DEFAULT_FOUNDATION_THRESHOLD;+ const verdict = computeReviewVerdict({ health, foundation, canon, threshold });++ const result = {+ seriesId,+ verdict,+ generatedAt: nowIso(),+ gate,+ foundationThreshold: threshold,+ foundation: foundation+ ? { weightedScore: foundation.weightedScore, dimensions: foundation.dimensions, oneLineVerdict: foundation.oneLineVerdict, weakest: foundation.weakest, stale: foundation.stale === true }+ : null,+ health: health+ ? { score: health.score, ready: health.ready, open: health.open, openBySeverity: health.openBySeverity, gate: health.gate }+ : null,+ canon: canon+ ? { ready: canon.ready, blockingIssues: canon.blockingIssues, undescribed: canon.undescribed }+ : null,+ findings,+ findingCount: findings.length,+ hadFeedback: !!(feedback && String(feedback).trim()),+ };+ await saveSnapshot(result);+ console.log(`🔎 series review — series=${seriesId.slice(0, 12)} verdict=${verdict} findings=${findings.length} foundation=${foundation?.weightedScore ?? '—'} health=${health?.score ?? '—'}`);+ return result;+}++// ---------------------------------------------------------------------------+// Persistence — last verdict per series.+// ---------------------------------------------------------------------------++async function saveSnapshot(result) {+ await ensureDir(reviewDir());+ await atomicWrite(snapshotPath(result.seriesId), result);+}++/**+ * Read the last stored review verdict for a series (null when never run). Also+ * reports whether the FIX path is currently available (cos-domain autonomy):+ * with the domain `off`, review still works read-only but fixing is disabled.+ */+export async function getSeriesReview(seriesId) {+ assertValidSeriesId(seriesId);+ const content = await tryReadFile(snapshotPath(seriesId));+ const verdict = content === null+ ? null+ : safeJSONParse(content, null, { allowArray: false, logError: true, context: snapshotPath(seriesId) });+ const fix = await getFixAvailability();+ return { review: verdict, fix };+}++/**+ * Whether the autopilot-driven fix path can run right now, from the cos-domain+ * autonomy mode. `off` → review is read-only, fixing disabled (graceful+ * degrade); `dry-run`/`execute` → fixing available.+ */+export async function getFixAvailability() {+ const state = await loadState().catch(() => ({ config: {} }));+ const mode = getDomainMode(state?.config, 'cos');+ return { mode, canFix: mode !== 'off' };+}++// ---------------------------------------------------------------------------+// SSE runner (shared factory — mirrors checkRunner / editorialAnalysisRunner).+// ---------------------------------------------------------------------------++const runner = createSseRunner({ logLabel: 'series review' });++export function startSeriesReviewRun(seriesId, options = {}) {+ return runner.start(seriesId, async ({ runId, signal, record, broadcast }) => {+ broadcast({ type: 'start', runId });+ const result = await runSeriesReview(seriesId, {+ feedback: options.feedback,+ providerOverride: options.providerOverride,+ modelOverride: options.modelOverride,+ force: options.force,+ readinessGate: options.readinessGate,+ signal,+ onProgress: (event) => broadcast({ ...event, runId }),+ });+ if (record.cancelRequested || result === null) {+ broadcast({ type: 'canceled', runId, canceledAt: nowIso() });+ return;+ }+ broadcast({+ type: 'complete',+ runId,+ verdict: result.verdict,+ findingCount: result.findingCount,+ completedAt: nowIso(),+ });+ });+}++export const attachClient = (seriesId, res) => runner.attachClient(seriesId, res);+export const isSeriesReviewActive = (seriesId) => runner.isActive(seriesId);+export const cancelSeriesReview = (seriesId) => runner.cancel(seriesId);++export const __testing = { runs: runner.runs };diff --git a/server/services/pipeline/seriesReview.test.js b/server/services/pipeline/seriesReview.test.jsnew file mode 100644index 0000000000..9b9d39423a--- /dev/null+++ b/server/services/pipeline/seriesReview.test.js@@ -0,0 +1,143 @@+import { describe, it, expect } from 'vitest';+import {+ computeReviewVerdict,+ collectReviewFindings,+ shapeFeedbackFinding,+ buildFeedbackRoutePrompt,+} from './seriesReview.js';++describe('computeReviewVerdict', () => {+ it("is 'ready' when health is clean, foundation clears the threshold, and canon is ready", () => {+ expect(computeReviewVerdict({+ health: { ready: true },+ foundation: { weightedScore: 8.2 },+ canon: { ready: true },+ threshold: 7.5,+ })).toBe('ready');+ });++ it("is 'issues' when the health gate is not clean", () => {+ expect(computeReviewVerdict({+ health: { ready: false },+ foundation: { weightedScore: 9 },+ canon: { ready: true },+ })).toBe('issues');+ });++ it("is 'issues' when the foundation is below the threshold", () => {+ expect(computeReviewVerdict({+ health: { ready: true },+ foundation: { weightedScore: 6 },+ canon: { ready: true },+ threshold: 7.5,+ })).toBe('issues');+ });++ it("is 'issues' when canon is not ready", () => {+ expect(computeReviewVerdict({+ health: { ready: true },+ foundation: { weightedScore: 9 },+ canon: { ready: false },+ })).toBe('issues');+ });++ it('treats a missing foundation / canon as non-blocking (absent, not failing)', () => {+ expect(computeReviewVerdict({ health: { ready: true }, foundation: null, canon: null })).toBe('ready');+ });++ it('treats a non-finite foundation score as non-blocking', () => {+ expect(computeReviewVerdict({+ health: { ready: true },+ foundation: { weightedScore: NaN },+ canon: { ready: true },+ })).toBe('ready');+ });+});++describe('collectReviewFindings', () => {+ const comments = [+ { id: 'a', severity: 'low', status: 'open', issueNumber: 2, problem: 'nit', checkId: 'style' },+ { id: 'b', severity: 'high', status: 'open', issueNumber: 3, problem: 'big', checkId: 'continuity', anchorQuote: 'q', location: 'V1' },+ { id: 'c', severity: 'high', status: 'open', issueNumber: 1, problem: 'also big' },+ { id: 'd', severity: 'medium', status: 'accepted', issueNumber: 1, problem: 'fixed already' },+ { id: 'e', severity: 'medium', status: 'dismissed', issueNumber: 1, problem: 'waived' },+ ];++ it('keeps only OPEN findings (drops accepted + dismissed)', () => {+ const out = collectReviewFindings(comments);+ expect(out.map((f) => f.commentId)).not.toContain('d');+ expect(out.map((f) => f.commentId)).not.toContain('e');+ expect(out).toHaveLength(3);+ });++ it('sorts high→low severity, then by issue number', () => {+ const out = collectReviewFindings(comments);+ // Both highs first (issue 1 before 3), then the low.+ expect(out.map((f) => f.commentId)).toEqual(['c', 'b', 'a']);+ });++ it('surfaces the commentId + anchoring fields the fix path needs', () => {+ const out = collectReviewFindings(comments);+ const b = out.find((f) => f.commentId === 'b');+ expect(b).toMatchObject({ severity: 'high', issueNumber: 3, anchorQuote: 'q', location: 'V1', summary: 'big', checkId: 'continuity' });+ });++ it('tolerates a non-array input', () => {+ expect(collectReviewFindings(null)).toEqual([]);+ });+});++describe('shapeFeedbackFinding', () => {+ const validNumbers = new Set([1, 2, 3]);++ it('adopts a valid routed issue number + severity', () => {+ const f = shapeFeedbackFinding(+ { issueNumber: 2, severity: 'high', problem: 'pacing drags', suggestion: 'cut', location: 'V2', anchorQuote: 'the quiet' },+ { feedback: 'raw', validNumbers },+ );+ expect(f).toMatchObject({+ issueNumber: 2, severity: 'high', problem: 'pacing drags', suggestion: 'cut', location: 'V2', anchorQuote: 'the quiet',+ checkId: 'user-feedback', category: 'user-feedback',+ });+ });++ it('degrades a hallucinated issue number to a series-level (null) finding', () => {+ const f = shapeFeedbackFinding({ issueNumber: 99, problem: 'x' }, { feedback: 'raw', validNumbers });+ expect(f.issueNumber).toBeNull();+ });++ it('falls back to the raw feedback as the problem when the model omits it', () => {+ const f = shapeFeedbackFinding({}, { feedback: 'volume 1 has no real development', validNumbers });+ expect(f.problem).toBe('volume 1 has no real development');+ expect(f.severity).toBe('medium');+ expect(f.issueNumber).toBeNull();+ });++ it('defaults an invalid severity to medium', () => {+ const f = shapeFeedbackFinding({ severity: 'critical', problem: 'x' }, { feedback: 'raw', validNumbers });+ expect(f.severity).toBe('medium');+ });++ it('accepts an array of valid numbers (not only a Set)', () => {+ const f = shapeFeedbackFinding({ issueNumber: 3, problem: 'x' }, { feedback: 'raw', validNumbers: [1, 2, 3] });+ expect(f.issueNumber).toBe(3);+ });+});++describe('buildFeedbackRoutePrompt', () => {+ it('lists the issue roster and embeds the feedback', () => {+ const prompt = buildFeedbackRoutePrompt('check the pacing', [+ { number: 1, title: 'Origins' },+ { number: 2, title: 'Fallout' },+ ]);+ expect(prompt).toContain('#1: Origins');+ expect(prompt).toContain('#2: Fallout');+ expect(prompt).toContain('check the pacing');+ expect(prompt).toContain('issueNumber');+ });++ it('handles an empty roster', () => {+ const prompt = buildFeedbackRoutePrompt('note', []);+ expect(prompt).toContain('(no issues yet)');+ });+});