Skip to content

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

feat([issue-2170]): reader panel personas + disagreement mining

[._.]/ Adam Eivyb532e5c4df63
diff --git a/client/src/components/pipeline/ReaderPanelView.jsx b/client/src/components/pipeline/ReaderPanelView.jsx
new file mode 100644
index 0000000000..da02205278
--- /dev/null
+++ b/client/src/components/pipeline/ReaderPanelView.jsx
@@ -0,0 +1,223 @@
+/**
+ * Reader Panel view (#2170, CWQE Phase 6) — the "Reader Panel" tab on the Reader
+ * Map page. Four personas each read a condensed arc digest and answer the same
+ * qualitative questions; this renders their answers side-by-side plus the mined
+ * disagreement list (consensus concerns routed to manuscript-review findings,
+ * softer "editorial attention" judgment calls, and best-vs-worst polarizing
+ * splits). Convening the panel spends one LLM call per persona and runs only from
+ * the explicit button here (AI-provider policy).
+ */
+
+import { Link } from 'react-router-dom';
+import { Loader2, Sparkles, Users, AlertTriangle, Scale, Split, ArrowRight } from 'lucide-react';
+import { useReaderPanel } from '../../hooks/useReaderPanel';
+
+// Mirror server/lib/editorial/panelDisagreement.js persona + question labels
+// (keep in sync — the two are small, stable vocabularies).
+const PERSONA_LABELS = {
+ editor: 'The Editor',
+ 'genre-reader': 'The Genre Reader',
+ writer: 'The Writer',
+ 'first-reader': 'The First Reader',
+};
+const PERSONA_ORDER = ['editor', 'genre-reader', 'writer', 'first-reader'];
+const QUESTION_LABELS = [
+ ['momentum_loss', 'Momentum lost'],
+ ['earned_ending', 'Earned ending'],
+ ['cut_candidate', 'Cut candidate'],
+ ['missing_scene', 'Missing scene'],
+ ['thinnest_character', 'Thinnest character'],
+ ['best_scene', 'Best scene'],
+ ['worst_scene', 'Worst scene'],
+ ['would_recommend', 'Would recommend'],
+ ['haunts_you', 'Haunts you'],
+ ['next_book', 'Next book'],
+];
+
+const personaLabel = (id) => PERSONA_LABELS[id] || id;
+const IssueTags = ({ issues }) => (
+ issues?.length ? (
+ <span className="ml-1 inline-flex flex-wrap gap-1 align-middle">
+ {issues.map((n) => (
+ <span key={n} className="text-[9px] font-mono px-1 rounded bg-port-bg text-gray-400 border border-port-border">#{n}</span>
+ ))}
+ </span>
+ ) : null
+);
+
+function PersonaColumn({ response }) {
+ const answers = response.answers || {};
+ return (
+ <div className="border border-port-border rounded-lg bg-port-card flex flex-col min-w-0">
+ <div className="p-2.5 border-b border-port-border">
+ <div className="flex items-center gap-2">
+ <Users size={13} className="text-port-accent shrink-0" />
+ <span className="text-sm font-medium text-gray-100 truncate">{personaLabel(response.persona)}</span>
+ </div>
+ {response.verdict ? <p className="mt-1 text-[11px] text-gray-400 italic">“{response.verdict}”</p> : null}
+ </div>
+ <dl className="p-2.5 space-y-2 overflow-y-auto">
+ {QUESTION_LABELS.map(([qid, label]) => {
+ const a = answers[qid];
+ if (!a || !a.text) return null;
+ return (
+ <div key={qid}>
+ <dt className="text-[10px] uppercase tracking-wider text-gray-500">{label}<IssueTags issues={a.issues} /></dt>
+ <dd className="text-[11px] text-gray-300 mt-0.5">{a.text}</dd>
+ </div>
+ );
+ })}
+ </dl>
+ </div>
+ );
+}
+
+function PersonaChips({ ids }) {
+ return (
+ <span className="inline-flex flex-wrap gap-1">
+ {(ids || []).map((id) => (
+ <span key={id} className="text-[9px] px-1.5 py-0.5 rounded-full bg-port-bg text-gray-300 border border-port-border">{personaLabel(id)}</span>
+ ))}
+ </span>
+ );
+}
+
+function DisagreementList({ disagreements }) {
+ const { consensus = [], attention = [], polarizing = [], totalPersonas = 0 } = disagreements || {};
+ const nothing = !consensus.length && !attention.length && !polarizing.length;
+ if (nothing) {
+ return <p className="text-xs text-gray-500 italic">The panel found no notable disagreements — a rare and suspicious consensus.</p>;
+ }
+ return (
+ <div className="space-y-4">
+ {consensus.length ? (
+ <div>
+ <h3 className="text-[11px] uppercase tracking-wider text-port-error/80 mb-1.5 flex items-center gap-1.5">
+ <AlertTriangle size={12} /> Consensus concerns — routed to editorial findings
+ </h3>
+ <ul className="space-y-1.5">
+ {consensus.map((c, i) => (
+ <li key={`${c.questionId}-${c.issueNumber}-${i}`} className="border border-port-error/30 bg-port-error/5 rounded p-2">
+ <div className="flex items-center gap-2 flex-wrap text-xs text-gray-200">
+ <span className="font-mono text-[10px] text-gray-400">#{c.issueNumber}</span>
+ <span className="font-medium">{c.questionLabel}</span>
+ <span className="text-[10px] text-gray-500">{c.count}/{totalPersonas}</span>
+ <PersonaChips ids={c.personas} />
+ </div>
+ </li>
+ ))}
+ </ul>
+ </div>
+ ) : null}
+
+ {attention.length ? (
+ <div>
+ <h3 className="text-[11px] uppercase tracking-wider text-port-warning/80 mb-1.5 flex items-center gap-1.5">
+ <Scale size={12} /> Editorial attention — some flagged, some didn’t
+ </h3>
+ <ul className="space-y-1.5">
+ {attention.map((c, i) => (
+ <li key={`${c.questionId}-${c.issueNumber}-${i}`} className="border border-port-border rounded p-2 bg-port-bg/40">
+ <div className="flex items-center gap-2 flex-wrap text-xs text-gray-300">
+ <span className="font-mono text-[10px] text-gray-500">#{c.issueNumber}</span>
+ <span>{c.questionLabel}</span>
+ <span className="text-[10px] text-gray-600">{c.count}/{totalPersonas}</span>
+ <PersonaChips ids={c.personas} />
+ </div>
+ </li>
+ ))}
+ </ul>
+ </div>
+ ) : null}
+
+ {polarizing.length ? (
+ <div>
+ <h3 className="text-[11px] uppercase tracking-wider text-port-accent/80 mb-1.5 flex items-center gap-1.5">
+ <Split size={12} /> Polarizing — one persona’s best is another’s worst
+ </h3>
+ <ul className="space-y-1.5">
+ {polarizing.map((p, i) => (
+ <li key={`${p.issueNumber}-${i}`} className="border border-port-accent/30 bg-port-accent/5 rounded p-2">
+ <div className="flex items-center gap-2 flex-wrap text-xs text-gray-300">
+ <span className="font-mono text-[10px] text-gray-500">#{p.issueNumber}</span>
+ <span className="text-emerald-300">loved:</span><PersonaChips ids={p.lovedBy} />
+ <span className="text-rose-300">worst:</span><PersonaChips ids={p.hatedBy} />
+ </div>
+ </li>
+ ))}
+ </ul>
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
+export default function ReaderPanelView({ seriesId, hasContent }) {
+ const { panel, loading, running, starting, convene, cancel, progressText } = useReaderPanel(seriesId);
+ const hasPanel = panel && panel.status === 'complete' && Array.isArray(panel.personas) && panel.personas.length;
+ const orderedPersonas = hasPanel
+ ? [...panel.personas].sort((a, b) => PERSONA_ORDER.indexOf(a.persona) - PERSONA_ORDER.indexOf(b.persona))
+ : [];
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center gap-2 flex-wrap">
+ <p className="text-[11px] text-gray-500 flex-1 min-w-0">
+ Four reader personas read a condensed arc digest and answer the same questions. Their disagreements are the editorial signal;
+ issues flagged by 3+ personas enter the{' '}
+ <Link to="/pipeline/editorial-checks" className="text-port-accent hover:underline">editorial findings</Link> triage flow.
+ </p>
+ {running ? (
+ <button type="button" onClick={cancel} className="inline-flex items-center gap-1.5 text-xs px-3 py-1.5 rounded border border-port-border text-gray-300 hover:border-port-error/50 shrink-0">
+ <Loader2 size={13} className="animate-spin" /> {progressText || 'Convening…'} (cancel)
+ </button>
+ ) : (
+ <button
+ type="button"
+ onClick={convene}
+ disabled={starting || !hasContent}
+ className="inline-flex items-center gap-1.5 text-xs px-3 py-1.5 rounded bg-port-accent/15 border border-port-accent/40 text-port-accent hover:bg-port-accent/25 disabled:opacity-40 disabled:cursor-not-allowed shrink-0"
+ title={!hasContent ? 'No drafted content to read yet' : 'Convene the four-persona reader panel (one LLM call per persona)'}
+ >
+ {starting ? <Loader2 size={13} className="animate-spin" /> : <Sparkles size={13} />}
+ {hasPanel ? 'Re-convene panel' : 'Convene panel'}
+ </button>
+ )}
+ </div>
+
+ {panel?.stale ? (
+ <p className="text-[11px] text-port-warning flex items-center gap-1.5">
+ <AlertTriangle size={12} /> The manuscript changed since this panel met — re-convene for a current read.
+ </p>
+ ) : null}
+
+ {loading ? (
+ <div className="text-xs text-gray-500 flex items-center gap-1.5"><Loader2 size={12} className="animate-spin" /> Loading panel…</div>
+ ) : !hasPanel ? (
+ <div className="border border-dashed border-port-border rounded-lg p-6 text-center">
+ <Users size={20} className="text-gray-600 mx-auto mb-2" />
+ <p className="text-sm text-gray-400">The reader panel hasn’t met yet.</p>
+ <p className="text-[11px] text-gray-600 mt-1">
+ {hasContent ? 'Convene the panel to hear four distinct reads of the series.' : 'Draft some issue content first, then convene the panel.'}
+ </p>
+ </div>
+ ) : (
+ <>
+ <section className="bg-port-card border border-port-border rounded-lg p-4">
+ <h2 className="text-xs uppercase tracking-wider text-gray-500 mb-3 flex items-center gap-1.5">
+ <ArrowRight size={13} className="text-port-accent" /> Where the panel disagrees
+ </h2>
+ <DisagreementList disagreements={panel.disagreements} />
+ </section>
+
+ <section>
+ <h2 className="text-xs uppercase tracking-wider text-gray-500 mb-2">The four reads</h2>
+ <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-3 items-start">
+ {orderedPersonas.map((r) => <PersonaColumn key={r.persona} response={r} />)}
+ </div>
+ </section>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 17a6243c7b..3692597f55 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -47,6 +47,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useOpenClawStream` | OpenClaw SSE chat stream. | OpenClaw file-browser chat surface only. |
| `usePipelineProgress` | Id-derived runner SSE stream: builds the URL from `(urlBuilder, ids)`, connects only when every id is truthy. | Any runner SSE keyed by record ids (pipeline auto-run, editorial, manuscript completeness, volume beats, story steps). |
| `useSeriesEditorial` | Editorial-roadmap aggregate + batch lifecycle (load, re-attach, SSE, start/cancel, reload). | Any view of the editorial roadmap (panel or Reader Map page). |
+| `useReaderPanel` | Reader-panel snapshot (four personas + mined disagreements) + convene lifecycle (load, re-attach, per-persona SSE, run/cancel, reload). | The Reader Map page's Reader Panel tab (#2170). |
## Media (annotations, completion, attachments)
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 29c61da0be..9f0224eda5 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -70,6 +70,7 @@ export * from './useImporterProgress.js';
export * from './useInstallStream.js';
export * from './useOpenClawStream.js';
export * from './usePipelineProgress.js';
+export * from './useReaderPanel.js';
export * from './useSeriesEditorial.js';
export * from './useSseProgress.js';
export * from './useModelDownloadStatus.js';
diff --git a/client/src/hooks/useReaderPanel.js b/client/src/hooks/useReaderPanel.js
new file mode 100644
index 0000000000..7eb614b9ce
--- /dev/null
+++ b/client/src/hooks/useReaderPanel.js
@@ -0,0 +1,79 @@
+import { useCallback, useEffect, useState } from 'react';
+import {
+ getReaderPanel, getReaderPanelStatus,
+ runReaderPanel, cancelReaderPanel, readerPanelSseUrl,
+} from '../services/api';
+import toast from '../components/ui/Toast';
+import { usePipelineProgress } from './usePipelineProgress';
+
+/**
+ * Owns the reader-panel snapshot for a series plus the convene lifecycle:
+ * initial load, re-attach to an in-flight run on (re)mount, per-persona SSE
+ * progress, run/cancel, and a reload when the run ends. Mirrors
+ * useSeriesEditorial — the panel is a sibling editorial view on the Reader Map
+ * page (#2170).
+ *
+ * Returns the stored `panel` (personas[] + mined disagreements), the run state
+ * (`running`/`starting`/`progressText`), and `reload`/`convene`/`cancel`.
+ */
+export function useReaderPanel(seriesId) {
+ const [panel, setPanel] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [running, setRunning] = useState(false);
+ const [starting, setStarting] = useState(false);
+
+ const reload = useCallback(() => {
+ if (!seriesId) return Promise.resolve();
+ return getReaderPanel(seriesId, { silent: true })
+ .then((data) => setPanel(data))
+ .catch(() => setPanel(null));
+ }, [seriesId]);
+
+ // Initial load + re-attach to a run still going from a prior visit so its
+ // completion still refreshes this view. The `canceled` guard prevents a slow
+ // response for a previous seriesId from overwriting the current one.
+ useEffect(() => {
+ if (!seriesId) { setLoading(false); return undefined; }
+ let canceled = false;
+ setLoading(true);
+ getReaderPanel(seriesId, { silent: true })
+ .then((data) => { if (!canceled) setPanel(data); })
+ .catch(() => { if (!canceled) setPanel(null); })
+ .finally(() => { if (!canceled) setLoading(false); });
+ getReaderPanelStatus(seriesId, { silent: true })
+ .then((s) => { if (!canceled && s?.active) setRunning(true); })
+ .catch(() => {});
+ return () => { canceled = true; };
+ }, [seriesId]);
+
+ // Reload when the run ends. `closed` covers a terminal frame OR a dropped/404
+ // stream, so the UI never hangs in "Convening…".
+ const { latest, closed } = usePipelineProgress(readerPanelSseUrl, [seriesId], { enabled: running });
+ useEffect(() => {
+ if (closed && running) {
+ setRunning(false);
+ reload();
+ }
+ }, [closed, running, reload]);
+
+ const convene = useCallback(() => {
+ if (!seriesId) return;
+ setStarting(true);
+ runReaderPanel(seriesId, {}, { silent: true })
+ .then(() => setRunning(true))
+ .catch((err) => toast.error(err?.message || 'Failed to convene panel'))
+ .finally(() => setStarting(false));
+ }, [seriesId]);
+
+ const cancel = useCallback(() => {
+ if (seriesId) cancelReaderPanel(seriesId).catch(() => {});
+ setRunning(false);
+ reload();
+ }, [seriesId, reload]);
+
+ const progressText = running
+ ? (latest?.label ? `${latest.label}… (${latest.done || 0}/${latest.total || 4})` : 'Convening panel…')
+ : null;
+
+ return { panel, loading, reload, running, starting, convene, cancel, progressText };
+}
diff --git a/client/src/pages/PipelineSeriesRoadmap.jsx b/client/src/pages/PipelineSeriesRoadmap.jsx
index 65720ae355..eb7119e3a6 100644
--- a/client/src/pages/PipelineSeriesRoadmap.jsx
+++ b/client/src/pages/PipelineSeriesRoadmap.jsx
@@ -12,17 +12,27 @@
*/
import { useCallback, useEffect, useState } from 'react';
-import { Link, useParams, useNavigate } from 'react-router-dom';
+import { Link, useParams, useNavigate, useSearchParams } from 'react-router-dom';
import {
- ArrowLeft, Loader2, Sparkles, ChevronRight, ChevronDown, AlertTriangle, Crown, ChartSpline,
+ ArrowLeft, Loader2, Sparkles, ChevronRight, ChevronDown, AlertTriangle, Crown, ChartSpline, Users,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import { ArcRoadmapChart } from '../components/pipeline/ArcCanvas';
+import ReaderPanelView from '../components/pipeline/ReaderPanelView';
+import TabPills from '../components/ui/TabPills';
import {
getPipelineSeries, getIssueEditorial, analyzeIssueEditorial,
} from '../services/api';
import { useSeriesEditorial } from '../hooks/useSeriesEditorial';
+// Deep-linkable tabs (?tab=roadmap|panel) — the URL is the source of truth for
+// which view is open, per the ID-based deep-linking convention.
+const TABS = [
+ { id: 'roadmap', label: 'Reader Map', icon: ChartSpline },
+ { id: 'panel', label: 'Reader Panel', icon: Users },
+];
+const TAB_IDS = TABS.map((t) => t.id);
+
const DIR_TONE = {
rising: 'text-emerald-300',
falling: 'text-rose-300',
@@ -180,10 +190,19 @@ function CharacterArcs({ protagonist, supportingArcs, protagonistArcText }) {
export default function PipelineSeriesRoadmap() {
const { seriesId } = useParams();
const navigate = useNavigate();
+ const [searchParams, setSearchParams] = useSearchParams();
const [series, setSeries] = useState(null);
const [loading, setLoading] = useState(true);
const [perIssueBusy, setPerIssueBusy] = useState(null); // issueId currently analyzing solo
+ // A stale/typo'd deep link degrades to the roadmap tab rather than a blank view.
+ const activeTab = TAB_IDS.includes(searchParams.get('tab')) ? searchParams.get('tab') : 'roadmap';
+ const setActiveTab = useCallback((id) => {
+ const next = new URLSearchParams(searchParams);
+ if (id === 'roadmap') next.delete('tab'); else next.set('tab', id);
+ setSearchParams(next, { replace: true });
+ }, [searchParams, setSearchParams]);
+
// Shared editorial-roadmap state + batch lifecycle (load, re-attach, SSE,
// start/cancel, reload). The EditorialRoadmapPanel uses the same hook.
const {
@@ -239,7 +258,7 @@ export default function PipelineSeriesRoadmap() {
<p className="text-xs text-gray-500 truncate">{series?.name}</p>
</div>
<div className="ml-auto flex items-center gap-2">
- {running ? (
+ {activeTab !== 'roadmap' ? null : running ? (
<button type="button" onClick={cancelAnalysis} className="inline-flex items-center gap-1.5 text-xs px-3 py-1.5 rounded border border-port-border text-gray-300 hover:border-port-error/50">
<Loader2 size={13} className="animate-spin" /> {progressText || 'Analyzing…'} (cancel)
</button>
@@ -258,6 +277,20 @@ export default function PipelineSeriesRoadmap() {
</div>
</div>
+ <TabPills
+ tabs={TABS}
+ activeTab={activeTab}
+ onChange={setActiveTab}
+ size="sm"
+ ariaLabel="Reader Map view"
+ mobileDropdown
+ mobileSelectId="reader-map-tab"
+ />
+
+ {activeTab === 'panel' ? (
+ <ReaderPanelView seriesId={seriesId} hasContent={coverage.withContent > 0} />
+ ) : (
+ <>
<div className="grid grid-cols-1 lg:grid-cols-[minmax(0,1.4fr)_minmax(300px,0.6fr)] gap-4 items-start">
<section className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">
<div className="flex items-center justify-between">
@@ -313,6 +346,8 @@ export default function PipelineSeriesRoadmap() {
<p className="text-xs text-gray-500 italic">This series has no issues yet.</p>
)}
</section>
+ </>
+ )}
</div>
);
}
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index 90e2b672f2..bcb67c9ff6 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -665,6 +665,32 @@ export const getSeriesEditorialStatus = (seriesId, options = {}) =>
export const pipelineEditorialSseUrl = (seriesId) =>
`/api/pipeline/series/${encodeURIComponent(seriesId)}/editorial/analyze/progress`;
+// ---- Reader panel (#2170 — four-persona panel + disagreement mining) ----
+// Stored panel: { status, personas[], disagreements:{consensus,attention,polarizing,totalPersonas}, seededFindings, stale } or { status: 'none' }.
+export const getReaderPanel = (seriesId, options = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/editorial/panel`, options);
+
+// Convene the panel (batch). { runId, alreadyRunning, sseUrl } — subscribe via
+// readerPanelSseUrl to stream per-persona progress.
+export const runReaderPanel = (seriesId, opts = {}, options = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/editorial/panel/run`, {
+ method: 'POST',
+ body: JSON.stringify(opts),
+ ...options,
+ });
+
+export const cancelReaderPanel = (seriesId) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/editorial/panel/run/cancel`, {
+ method: 'POST',
+ });
+
+// { active: boolean } — lets a (re)mounting view re-attach to an in-flight run.
+export const getReaderPanelStatus = (seriesId, options = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/editorial/panel/run/status`, options);
+
+export const readerPanelSseUrl = (seriesId) =>
+ `/api/pipeline/series/${encodeURIComponent(seriesId)}/editorial/panel/run/progress`;
+
// ---- Perspective rewrite (#1290 — rewrite a passage in another POV + analyze) ----
// Stored alternate-POV rewrites + cast (for the picker) + per-rewrite stale flags:
// { issueId, seriesId, cast[], hasContent, rewrites[] }
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index f361c26600..efe7aeedad 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -289,6 +289,34 @@
"returnsJson": true,
"variables": []
},
+ "pipeline-panel-editor": {
+ "name": "Pipeline — Reader Panel: The Editor",
+ "description": "Reader-panel persona (#2170, CWQE Phase 6). A senior developmental/line editor reads a condensed arc digest of the series and answers ~10 qualitative questions (momentum, earned ending, cut candidate, missing scene, thinnest character, best/worst scene, would recommend, haunts you, next book), citing issue numbers. One of four personas whose disagreements feed the panel view + consensus findings.",
+ "model": "heavy",
+ "returnsJson": true,
+ "variables": ["seriesName", "logline", "issueCount", "digest"]
+ },
+ "pipeline-panel-genre-reader": {
+ "name": "Pipeline — Reader Panel: The Genre Reader",
+ "description": "Reader-panel persona (#2170, CWQE Phase 6). A voracious genre reader (50+ novels/year) reads a condensed arc digest and answers the panel's ~10 qualitative questions from a pure page-turn-pull perspective, citing issue numbers. One of four personas whose disagreements feed the panel view + consensus findings.",
+ "model": "heavy",
+ "returnsJson": true,
+ "variables": ["seriesName", "logline", "issueCount", "digest"]
+ },
+ "pipeline-panel-writer": {
+ "name": "Pipeline — Reader Panel: The Writer",
+ "description": "Reader-panel persona (#2170, CWQE Phase 6). A working novelist reads a condensed arc digest for craft — structure, beats, setup/payoff — and answers the panel's ~10 qualitative questions citing issue numbers. One of four personas whose disagreements feed the panel view + consensus findings.",
+ "model": "heavy",
+ "returnsJson": true,
+ "variables": ["seriesName", "logline", "issueCount", "digest"]
+ },
+ "pipeline-panel-first-reader": {
+ "name": "Pipeline — Reader Panel: The First Reader",
+ "description": "Reader-panel persona (#2170, CWQE Phase 6). An ordinary reader with no craft vocabulary reads a condensed arc digest and answers the panel's ~10 qualitative questions as pure emotional response, citing issue numbers. One of four personas whose disagreements feed the panel view + consensus findings.",
+ "model": "heavy",
+ "returnsJson": true,
+ "variables": ["seriesName", "logline", "issueCount", "digest"]
+ },
"pipeline-reverse-outline": {
"name": "Pipeline — Reverse Outline (scene segmentation + plotline tagging)",
"description": "Read the whole drafted manuscript and produce a reverse outline: identify the recurring plotlines, then segment the prose into scenes (each tagged to the plotline it advances, with POV, setting, and narrative/action/dialogue mix). Feeds the color-coded Reverse Outline view and is the canonical scene-segmentation substrate other editorial checks read. Runs at `heavy` tier — reads the full stitched manuscript.",
diff --git a/data.reference/prompts/stages/pipeline-panel-editor.md b/data.reference/prompts/stages/pipeline-panel-editor.md
new file mode 100644
index 0000000000..449af8db8d
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-panel-editor.md
@@ -0,0 +1,52 @@
+# Pipeline — Reader Panel: The Editor
+
+You are **The Editor** on a simulated reader panel — a senior developmental/line editor with decades at a serious literary imprint. You read for **prose texture, subtext, and over-explaining**: you catch where the writing tells what it should trust the reader to feel, where a scene explains its own theme aloud, and where the sentences go slack. You admire restraint and precision; you distrust prose that flatters itself.
+
+You are reading a condensed **arc digest** of a serialized story — one entry per issue, each with a short summary, an opening and closing excerpt, and a few notable lines of dialogue. Judge the whole series as a body of work, in your own voice.
+
+## Series
+
+- Title: {{seriesName}}
+{{#logline}}- Logline: {{logline}}{{/logline}}
+- Issues in the digest: {{issueCount}}
+
+## Arc digest
+
+{{digest}}
+
+## Your task
+
+Answer every question below **in character as The Editor**. Ground each answer in the digest and **cite the specific issue number(s)** your judgment rests on (use the issue numbers exactly as they appear above). Be candid and specific — a vague answer is useless to the writer.
+
+- `momentum_loss` — Where does the story lose momentum or go slack? Cite issue number(s).
+- `earned_ending` — Does the ending feel earned by what came before, or asserted? Cite the issue(s) that set it up or undercut it.
+- `cut_candidate` — What could be cut with no loss (or a gain)? Cite issue number(s).
+- `missing_scene` — What scene is the story missing that it needs? Cite the issue(s) it belongs near.
+- `thinnest_character` — Which character is thinnest or least realized? Name them; cite where it shows.
+- `best_scene` — The single best scene or moment. Cite the issue number.
+- `worst_scene` — The weakest scene or moment. Cite the issue number.
+- `would_recommend` — Would you recommend this, and to whom? Cite the issue(s) that decided it.
+- `haunts_you` — What image or line stays with you after finishing? Cite the issue number.
+- `next_book` — Would you read the next book, and what would make you? Cite issue number(s).
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary. Every `issues` value is an array of integer issue numbers drawn from the digest (empty array if genuinely none applies):
+
+```json
+{
+ "verdict": "one-sentence overall judgment in your voice",
+ "answers": {
+ "momentum_loss": { "text": "string", "issues": [1] },
+ "earned_ending": { "text": "string", "issues": [1] },
+ "cut_candidate": { "text": "string", "issues": [1] },
+ "missing_scene": { "text": "string", "issues": [1] },
+ "thinnest_character": { "text": "string", "issues": [1] },
+ "best_scene": { "text": "string", "issues": [1] },
+ "worst_scene": { "text": "string", "issues": [1] },
+ "would_recommend": { "text": "string", "issues": [1] },
+ "haunts_you": { "text": "string", "issues": [1] },
+ "next_book": { "text": "string", "issues": [1] }
+ }
+}
+```
diff --git a/data.reference/prompts/stages/pipeline-panel-first-reader.md b/data.reference/prompts/stages/pipeline-panel-first-reader.md
new file mode 100644
index 0000000000..eada9842d0
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-panel-first-reader.md
@@ -0,0 +1,52 @@
+# Pipeline — Reader Panel: The First Reader
+
+You are **The First Reader** on a simulated reader panel — an ordinary, enthusiastic reader with **no craft vocabulary at all**. You don't know what a "beat" or "arc" or "setup and payoff" is, and you never use words like *pacing*, *prose*, *structure*, or *subtext*. You just know how the story made you **feel**: what gripped you, what confused you, who you rooted for, where you got bored, what made you gasp or cry or roll your eyes. You are pure emotional response — the reader every book is ultimately written for.
+
+You are reading a condensed **arc digest** of a serialized story — one entry per issue, each with a short summary, an opening and closing excerpt, and a few notable lines of dialogue. React honestly, like you're texting a friend about a book you just finished.
+
+## Series
+
+- Title: {{seriesName}}
+{{#logline}}- Logline: {{logline}}{{/logline}}
+- Issues in the digest: {{issueCount}}
+
+## Arc digest
+
+{{digest}}
+
+## Your task
+
+Answer every question below **in character as The First Reader** — in plain, feeling words, never craft terms. Ground each answer in the digest and **cite the specific issue number(s)** the feeling came from (use the issue numbers exactly as they appear above).
+
+- `momentum_loss` — Where did you get bored or start skimming? Cite issue number(s).
+- `earned_ending` — Did the ending make you happy / satisfied, or did it feel like a cheat? Cite the issue(s).
+- `cut_candidate` — What part did you wish you could skip? Cite issue number(s).
+- `missing_scene` — What did you really want to see that the story never showed you? Cite the issue(s).
+- `thinnest_character` — Which character did you not care about at all? Name them; cite where.
+- `best_scene` — The part you loved most. Cite the issue number.
+- `worst_scene` — The part you liked least. Cite the issue number.
+- `would_recommend` — Would you tell a friend to read this? Cite the issue(s) that decided it.
+- `haunts_you` — What part do you keep thinking about after finishing? Cite the issue number.
+- `next_book` — Would you read the next one, and why? Cite issue number(s).
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary. Every `issues` value is an array of integer issue numbers drawn from the digest (empty array if genuinely none applies):
+
+```json
+{
+ "verdict": "one-sentence overall feeling in your voice",
+ "answers": {
+ "momentum_loss": { "text": "string", "issues": [1] },
+ "earned_ending": { "text": "string", "issues": [1] },
+ "cut_candidate": { "text": "string", "issues": [1] },
+ "missing_scene": { "text": "string", "issues": [1] },
+ "thinnest_character": { "text": "string", "issues": [1] },
+ "best_scene": { "text": "string", "issues": [1] },
+ "worst_scene": { "text": "string", "issues": [1] },
+ "would_recommend": { "text": "string", "issues": [1] },
+ "haunts_you": { "text": "string", "issues": [1] },
+ "next_book": { "text": "string", "issues": [1] }
+ }
+}
+```
diff --git a/data.reference/prompts/stages/pipeline-panel-genre-reader.md b/data.reference/prompts/stages/pipeline-panel-genre-reader.md
new file mode 100644
index 0000000000..fc17fb15fe
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-panel-genre-reader.md
@@ -0,0 +1,52 @@
+# Pipeline — Reader Panel: The Genre Reader
+
+You are **The Genre Reader** on a simulated reader panel — you read 50+ novels a year, mostly in this story's genre, and you read for **pull**. You want the page to turn itself. You track pacing, the strength of each hook, and whether a chapter *goes somewhere*. Your defining trait: you **get bored by beautiful prose that doesn't GO anywhere** — craft that doesn't earn its keep in momentum is dead weight to you. You're not a snob; you're the reader the book actually has to hold.
+
+You are reading a condensed **arc digest** of a serialized story — one entry per issue, each with a short summary, an opening and closing excerpt, and a few notable lines of dialogue. Judge whether this series would keep you up past midnight.
+
+## Series
+
+- Title: {{seriesName}}
+{{#logline}}- Logline: {{logline}}{{/logline}}
+- Issues in the digest: {{issueCount}}
+
+## Arc digest
+
+{{digest}}
+
+## Your task
+
+Answer every question below **in character as The Genre Reader**. Ground each answer in the digest and **cite the specific issue number(s)** your judgment rests on (use the issue numbers exactly as they appear above). Talk about momentum and page-turn pull, not craft vocabulary.
+
+- `momentum_loss` — Where did you feel the pull slacken — where would you have set the book down? Cite issue number(s).
+- `earned_ending` — Did the ending pay off the promise that kept you reading? Cite the issue(s).
+- `cut_candidate` — What dragged and could be cut to keep the pages turning? Cite issue number(s).
+- `missing_scene` — What scene did you keep waiting for that never came? Cite the issue(s) it belongs near.
+- `thinnest_character` — Which character never made you care? Name them; cite where it shows.
+- `best_scene` — The scene you'd tell a friend about. Cite the issue number.
+- `worst_scene` — The scene that lost you. Cite the issue number.
+- `would_recommend` — Would you press this on a fellow genre reader? Cite the issue(s) that decided it.
+- `haunts_you` — What moment stuck with you after you closed it? Cite the issue number.
+- `next_book` — Would you pre-order the next one, and what would make you? Cite issue number(s).
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary. Every `issues` value is an array of integer issue numbers drawn from the digest (empty array if genuinely none applies):
+
+```json
+{
+ "verdict": "one-sentence overall judgment in your voice",
+ "answers": {
+ "momentum_loss": { "text": "string", "issues": [1] },
+ "earned_ending": { "text": "string", "issues": [1] },
+ "cut_candidate": { "text": "string", "issues": [1] },
+ "missing_scene": { "text": "string", "issues": [1] },
+ "thinnest_character": { "text": "string", "issues": [1] },
+ "best_scene": { "text": "string", "issues": [1] },
+ "worst_scene": { "text": "string", "issues": [1] },
+ "would_recommend": { "text": "string", "issues": [1] },
+ "haunts_you": { "text": "string", "issues": [1] },
+ "next_book": { "text": "string", "issues": [1] }
+ }
+}
+```
diff --git a/data.reference/prompts/stages/pipeline-panel-writer.md b/data.reference/prompts/stages/pipeline-panel-writer.md
new file mode 100644
index 0000000000..3b67cd006b
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-panel-writer.md
@@ -0,0 +1,52 @@
+# Pipeline — Reader Panel: The Writer
+
+You are **The Writer** on a simulated reader panel — a working novelist who reads other people's books the way a builder walks another builder's house: you see the joinery. You read for **craft**: structure, beat placement, setup-and-payoff, whether foreshadowing lands, whether the shape of the arc is deliberate. Your **worst insult is "I can see the outline"** — when the machinery shows, when a scene exists only because the structure demanded it, when a payoff was planted so obviously it never surprised.
+
+You are reading a condensed **arc digest** of a serialized story — one entry per issue, each with a short summary, an opening and closing excerpt, and a few notable lines of dialogue. Judge the architecture.
+
+## Series
+
+- Title: {{seriesName}}
+{{#logline}}- Logline: {{logline}}{{/logline}}
+- Issues in the digest: {{issueCount}}
+
+## Arc digest
+
+{{digest}}
+
+## Your task
+
+Answer every question below **in character as The Writer**. Ground each answer in the digest and **cite the specific issue number(s)** your judgment rests on (use the issue numbers exactly as they appear above). Speak to structure, beats, and payoff.
+
+- `momentum_loss` — Where does the structure sag — a beat held too long, a turn that arrives late? Cite issue number(s).
+- `earned_ending` — Is the ending set up and paid off, or does the outline show? Cite the issue(s) that plant and pay it.
+- `cut_candidate` — What scene exists only because the structure demanded it? Cite issue number(s).
+- `missing_scene` — What beat is missing that the arc needs to earn its turns? Cite the issue(s) it belongs near.
+- `thinnest_character` — Whose arc is underbuilt? Name them; cite where the scaffolding shows.
+- `best_scene` — The best-constructed scene — setup and payoff working together. Cite the issue number.
+- `worst_scene` — Where you could most see the outline. Cite the issue number.
+- `would_recommend` — Would you recommend it to another writer as worth studying? Cite the issue(s).
+- `haunts_you` — What craft choice stayed with you afterward? Cite the issue number.
+- `next_book` — Would you follow this writer to the next book, and why? Cite issue number(s).
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary. Every `issues` value is an array of integer issue numbers drawn from the digest (empty array if genuinely none applies):
+
+```json
+{
+ "verdict": "one-sentence overall judgment in your voice",
+ "answers": {
+ "momentum_loss": { "text": "string", "issues": [1] },
+ "earned_ending": { "text": "string", "issues": [1] },
+ "cut_candidate": { "text": "string", "issues": [1] },
+ "missing_scene": { "text": "string", "issues": [1] },
+ "thinnest_character": { "text": "string", "issues": [1] },
+ "best_scene": { "text": "string", "issues": [1] },
+ "worst_scene": { "text": "string", "issues": [1] },
+ "would_recommend": { "text": "string", "issues": [1] },
+ "haunts_you": { "text": "string", "issues": [1] },
+ "next_book": { "text": "string", "issues": [1] }
+ }
+}
+```
diff --git a/scripts/migrations/164-reader-panel-persona-stages.js b/scripts/migrations/164-reader-panel-persona-stages.js
new file mode 100644
index 0000000000..d745b2a3b8
--- /dev/null
+++ b/scripts/migrations/164-reader-panel-persona-stages.js
@@ -0,0 +1,26 @@
+/**
+ * Seed the four reader-panel persona stages into existing installs (#2170 —
+ * CWQE Phase 6, "reader panel personas + disagreement mining").
+ *
+ * Mirrors `095-pov-rewrite-stages.js`: copies each `.md` template from
+ * `data.reference/prompts/stages/` and merges the matching stage-config entry
+ * into `data/prompts/stage-config.json`. Boot runs migrations (server/index.js)
+ * but NOT `setup-data.js`, so an upgrade that pulls + `pm2 restart`s (rather than
+ * running `update.sh`) would otherwise leave the new persona stages unseeded and
+ * convening the reader panel would throw "Stage not found" on the first run.
+ *
+ * Four persona stages ship together (Editor / Genre Reader / Writer / First
+ * Reader). Each stage-config entry — and its `returnsJson` flag — is copied
+ * verbatim from the shipped sample by `makeSeedMigrations`; the migration never
+ * inspects or branches on it, so the shared multi-stage helper is equivalent to a
+ * hand-rolled per-stage loop.
+ */
+
+import { makeSeedMigrations } from './_seedStageHelpers.js';
+
+export default makeSeedMigrations([
+ 'pipeline-panel-editor',
+ 'pipeline-panel-genre-reader',
+ 'pipeline-panel-writer',
+ 'pipeline-panel-first-reader',
+]);
diff --git a/scripts/migrations/164-reader-panel-persona-stages.test.js b/scripts/migrations/164-reader-panel-persona-stages.test.js
new file mode 100644
index 0000000000..a5807c5a2e
--- /dev/null
+++ b/scripts/migrations/164-reader-panel-persona-stages.test.js
@@ -0,0 +1,91 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+
+import migration from './164-reader-panel-persona-stages.js';
+
+// scripts/migrations/<this> → ../.. is the repo root (matches _testHelpers.js).
+const repoRoot = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
+
+// First-shipment seed migration (mirrors 095/133) — no MD5 bookkeeping, so the
+// seed / no-clobber behavior is asserted directly.
+
+const STAGE_KEYS = [
+ 'pipeline-panel-editor',
+ 'pipeline-panel-genre-reader',
+ 'pipeline-panel-writer',
+ 'pipeline-panel-first-reader',
+];
+
+describe('migration 164 — seed reader-panel persona stages', () => {
+ let rootDir;
+ let stagesDir;
+ let refStagesDir;
+ let installedConfigPath;
+
+ const seedReference = () => {
+ for (const key of STAGE_KEYS) writeFileSync(join(refStagesDir, `${key}.md`), `# ${key}\n\nshipped body\n`);
+ const refConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ const stages = Object.fromEntries(STAGE_KEYS.map((key) => [key, { name: key, description: 'desc', model: 'heavy', returnsJson: true, variables: [] }]));
+ writeFileSync(refConfigPath, JSON.stringify({ stages }, null, 2) + '\n');
+ };
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-164-'));
+ stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ refStagesDir = join(rootDir, 'data.reference', 'prompts', 'stages');
+ installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ mkdirSync(stagesDir, { recursive: true });
+ mkdirSync(refStagesDir, { recursive: true });
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ });
+
+ it('seeds all four persona templates and merges their stage-config entries', async () => {
+ seedReference();
+ await expect(migration.up({ rootDir })).resolves.not.toThrow();
+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));
+ for (const key of STAGE_KEYS) {
+ expect(readFileSync(join(stagesDir, `${key}.md`), 'utf8')).toContain(key);
+ expect(installed.stages[key]).toMatchObject({ returnsJson: true });
+ }
+ });
+
+ it('is idempotent and never clobbers a customized .md or an existing stage-config entry', async () => {
+ seedReference();
+ const customBody = '# CUSTOMIZED — do not overwrite\n';
+ writeFileSync(join(stagesDir, 'pipeline-panel-editor.md'), customBody);
+ writeFileSync(
+ installedConfigPath,
+ JSON.stringify({ stages: { 'pipeline-panel-editor': { name: 'user-tuned', model: 'custom' } } }, null, 2) + '\n',
+ );
+
+ await migration.up({ rootDir });
+
+ expect(readFileSync(join(stagesDir, 'pipeline-panel-editor.md'), 'utf8')).toBe(customBody);
+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));
+ expect(installed.stages['pipeline-panel-editor']).toEqual({ name: 'user-tuned', model: 'custom' });
+ // the other three still seed
+ expect(installed.stages['pipeline-panel-writer']).toMatchObject({ returnsJson: true });
+ });
+
+ it('does not throw when the data.reference samples are missing', async () => {
+ await expect(migration.up({ rootDir })).resolves.not.toThrow();
+ expect(existsSync(join(stagesDir, 'pipeline-panel-editor.md'))).toBe(false);
+ });
+
+ it('matches the live shipped stage-config keys + prompt files (drift catch)', () => {
+ const refConfig = JSON.parse(
+ readFileSync(join(repoRoot, 'data.reference', 'prompts', 'stage-config.json'), 'utf8'),
+ );
+ for (const key of STAGE_KEYS) {
+ expect(refConfig.stages[key], `stage-config missing ${key}`).toBeTruthy();
+ expect(refConfig.stages[key].returnsJson).toBe(true);
+ expect(existsSync(join(repoRoot, 'data.reference', 'prompts', 'stages', `${key}.md`))).toBe(true);
+ }
+ });
+});
diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.md
index 7102b9a254..e5682dc8f2 100644
--- a/server/lib/editorial/README.md
+++ b/server/lib/editorial/README.md
@@ -208,5 +208,6 @@ runner-injected `ctx.callInlineLLM` (an inline-prompt sibling of
| `dialogue.js` | Pure, dependency-free dialogue-tag primitives for the #1307 dialogue-craft group: `findSaidBookisms` (`dialogue.said-bookisms` — ornate speech tags like *expostulated*/*opined* and non-speech tags like "she smiled", matched only when adjacent to a double-quote span) and `findUnattributedDialogueRuns` (`dialogue.attribution-clarity` — runs of consecutive untagged/unbeated dialogue lines where the speaker can't be tracked), plus `attributeDialogueByOwner` (the coarse per-character dialogue-line tally behind `cast.representation-balance`'s dialogue-share signal, #1312 — credits each quoted paragraph to the first owner named in its beat) and the seed `SAID_BOOKISMS` / `NON_SPEECH_TAGS` lists. Also `inventoryDialogueTags` + `splitScenes` + `findDialogueTagVariety` (`dialogue.tag-variety`, #1587 — per-scene tag inventory flagging within-scene **monotony** (one verb dominates) and **over-variation** (a fresh verb on nearly every line); collapses inflections onto a base lemma via `PLAIN_SPEECH_TAG_GROUPS`). The LLM siblings `dialogue.on-the-nose` (subtext-free / "as you know, Bob" dialogue) and `dialogue.voice-distinctiveness` (per-character voice against canon `speechPattern`/`speechAccent`) handle the judgment cases. |
| `letteringDensity.js` | Pure, dependency-free comic lettering-density primitives for `comic.lettering-density` (#1313): `countWords`, `panelLetteringMetrics` (per-panel balloon/caption/SFX word + balloon tally over the `comicScriptParser` output), `analyzeComicLettering` (flags balloons/panels/pages over the configurable thresholds in `DEFAULT_LETTERING_THRESHOLDS`), `overflowSeverity` (severity scaled by how far over the limit), and `sanitizeLetteringThresholds`. Mirrored to `client/src/lib/letteringDensity.js` for the comic-script stage's inline warnings — keep the two in sync. |
| `balloonAttribution.js` | Pure, dependency-free comic speech-balloon attribution primitives for `comic.balloon-attribution`: `analyzeBalloonAttribution` (flags a dialogue line whose speaker isn't shown in the panel description and carries no off-panel/broadcast cue — the case the image model mis-attributes to a visible character), `splitSpeaker`, `nameInText`, and `OFFPANEL_OK_MODIFIER` (the broadcast/off-panel/V.O./transmission modifier vocabulary — mirrors `visualStages.js` `BALLOON_STYLE_HINTS`, keep in sync). Severity scales `medium`/`low` by whether another canon character is visibly named in the panel. |
+| `panelDisagreement.js` | Pure reader-panel disagreement-mining primitives for the four-persona reader panel (#2170 — CWQE Phase 6): the `PANEL_PERSONAS` / `PANEL_QUESTIONS` vocabulary, `sanitizePersonaResponse` (one persona's raw LLM answer → stable `{ persona, answers:{<qid>:{text,issues[]}}, verdict }` shape), `minePanelDisagreements` (cross-persona `consensus` ≥3-persona concern citations / `attention` some-but-not-all / `polarizing` best-vs-worst-scene splits), and `consensusToFindings` (consensus entries → `seedReviewFromFindings` finding shapes). Pure — all I/O (digest build, per-persona LLM calls, snapshot storage, review seeding) lives in `server/services/pipeline/readerPanel.js`. |
| `severityConfig.js` | Pure per-series severity-config helpers (#1616): the frozen `DEFAULT_SEVERITY_WEIGHTS` (high:12/medium:5/low:1) + `DEFAULT_BLOCKING_SEVERITIES` per autopilot gate (`BLOCKING_GATES` = arc/beatContinuity/editorial), `mergeSeverityWeights` (merge a per-series weight override over the defaults — absent/invalid keys keep the default), `resolveBlockingSet` (the per-gate blocking `Set` — `Array.isArray` first so an explicit empty `[]` "nothing blocks" is distinct from an absent gate's default), and the wire bounders `sanitizeSeverityWeights` / `sanitizeBlockingSeverities` (persisted on the series record, gated at `pipelineSeries` v9). Reuses `CHECK_SEVERITIES` from `checkRegistry.js` as the canonical enum so the wire gate can't drift. |
| `index.js` | Barrel re-export of the above. |
diff --git a/server/lib/editorial/index.js b/server/lib/editorial/index.js
index 0f0ed21eb7..d12542ad7a 100644
--- a/server/lib/editorial/index.js
+++ b/server/lib/editorial/index.js
@@ -14,3 +14,4 @@ export * from './repetition.js';
export * from './shotContinuity.js';
export * from './slopScore.js';
export * from './voiceFingerprint.js';
+export * from './panelDisagreement.js';
diff --git a/server/lib/editorial/panelDisagreement.js b/server/lib/editorial/panelDisagreement.js
new file mode 100644
index 0000000000..13b922dd5f
--- /dev/null
+++ b/server/lib/editorial/panelDisagreement.js
@@ -0,0 +1,225 @@
+/**
+ * Reader-panel disagreement mining (#2170, CWQE Phase 6).
+ *
+ * Four reader personas (The Editor, The Genre Reader, The Writer, The First
+ * Reader) each read a condensed arc digest of a series and answer the same set
+ * of qualitative questions, citing issue numbers. The editorial signal lives in
+ * where they DISAGREE — an issue flagged by one persona but loved by another is
+ * a deliberate trade-off surfaced for the human; an issue flagged by 3+ personas
+ * is a real problem that should enter the normal manuscript-review triage flow.
+ *
+ * This module is PURE (matches the directory contract): it defines the persona /
+ * question vocabulary, sanitizes a persona's raw LLM answer into a stable shape,
+ * mines the cross-persona (dis)agreement, and shapes consensus findings for
+ * `seedReviewFromFindings`. All I/O (digest build, LLM calls, snapshot storage)
+ * lives in `server/services/pipeline/readerPanel.js`.
+ */
+
+// The four personas, in render order. `id` is the stable machine key (also the
+// stage-prompt suffix `pipeline-panel-<id>.md`); `label` is the human name.
+export const PANEL_PERSONAS = Object.freeze([
+ { id: 'editor', label: 'The Editor', blurb: 'Senior editor — prose texture, subtext, over-explaining.' },
+ { id: 'genre-reader', label: 'The Genre Reader', blurb: 'Reads 50 novels a year — pacing and page-turn pull.' },
+ { id: 'writer', label: 'The Writer', blurb: 'Craft — structure, beats, foreshadowing payoff.' },
+ { id: 'first-reader', label: 'The First Reader', blurb: 'No craft vocabulary — pure emotional response.' },
+]);
+
+export const PANEL_PERSONA_IDS = Object.freeze(PANEL_PERSONAS.map((p) => p.id));
+
+const PERSONA_LABEL = new Map(PANEL_PERSONAS.map((p) => [p.id, p.label]));
+export const personaLabel = (id) => PERSONA_LABEL.get(id) || id;
+
+/**
+ * The ~10 qualitative questions every persona answers. `concern: true` marks a
+ * question whose cited issues are a *flag* (something wrong there) — those feed
+ * disagreement mining + consensus findings. `positive` questions (best/haunts)
+ * feed the "polarizing" cross-signal instead. `evaluative` questions are read by
+ * humans in the panel view but not mined into findings.
+ */
+export const PANEL_QUESTIONS = Object.freeze([
+ { id: 'momentum_loss', label: 'Where momentum is lost', concern: true, category: 'pacing', prompt: 'Where does the story lose momentum or drag? Cite the issue number(s).' },
+ { id: 'earned_ending', label: 'Is the ending earned', concern: false, category: 'structure', prompt: 'Does the ending feel earned by what came before? Cite the issue number(s) that set it up or undercut it.' },
+ { id: 'cut_candidate', label: 'What to cut', concern: true, category: 'pacing', prompt: 'What could be cut with no loss (or a gain)? Cite the issue number(s).' },
+ { id: 'missing_scene', label: 'A missing scene', concern: true, category: 'structure', prompt: 'What scene is missing that the story needs? Cite the issue number(s) it belongs near.' },
+ { id: 'thinnest_character', label: 'The thinnest character', concern: true, category: 'character', prompt: 'Which character is thinnest / least realized? Name them and cite the issue number(s) where it shows.' },
+ { id: 'best_scene', label: 'The best scene', concern: false, category: 'structure', prompt: 'What is the single best scene / moment? Cite the issue number.' },
+ { id: 'worst_scene', label: 'The worst scene', concern: true, category: 'structure', prompt: 'What is the weakest scene / moment? Cite the issue number.' },
+ { id: 'would_recommend', label: 'Would recommend', concern: false, category: 'other', prompt: 'Would you recommend this to a friend, and why or why not? Cite the issue number(s) that decided it.' },
+ { id: 'haunts_you', label: 'What haunts you', concern: false, category: 'other', prompt: 'What image, line, or moment haunts you after finishing? Cite the issue number.' },
+ { id: 'next_book', label: 'Read the next book', concern: false, category: 'other', prompt: 'Would you read the next book in the series, and what would make you? Cite the issue number(s).' },
+]);
+
+export const PANEL_QUESTION_IDS = Object.freeze(PANEL_QUESTIONS.map((q) => q.id));
+const QUESTION_BY_ID = new Map(PANEL_QUESTIONS.map((q) => [q.id, q]));
+const CONCERN_QUESTION_IDS = PANEL_QUESTIONS.filter((q) => q.concern).map((q) => q.id);
+
+// A concern flagged by this many distinct personas (of the four) is treated as a
+// real problem and routed into manuscript-review findings. Below it (but flagged
+// by at least one and not all) it's "editorial attention" — surfaced for the
+// human, not auto-routed.
+export const CONSENSUS_THRESHOLD = 3;
+
+const ANSWER_TEXT_MAX = 1500;
+const VERDICT_MAX = 600;
+const MAX_ISSUES_PER_ANSWER = 12;
+const PROBLEM_MAX = 1900;
+
+const cleanStr = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
+
+// Accept an array of issue numbers the persona cited; keep valid positive
+// integers, dedupe, cap. Optionally intersect with the known series issue
+// numbers so a hallucinated citation never reaches the findings store.
+function cleanIssueNumbers(raw, validSet) {
+ if (!Array.isArray(raw)) return [];
+ const out = [];
+ const seen = new Set();
+ for (const v of raw) {
+ const n = Number(v);
+ if (!Number.isInteger(n) || n <= 0) continue;
+ if (validSet && !validSet.has(n)) continue;
+ if (seen.has(n)) continue;
+ seen.add(n);
+ out.push(n);
+ if (out.length >= MAX_ISSUES_PER_ANSWER) break;
+ }
+ return out.sort((a, b) => a - b);
+}
+
+/**
+ * Sanitize one persona's raw LLM answer object into the stored shape:
+ * { persona, answers: { <qid>: { text, issues:[int] } }, verdict }
+ * Every question id is present (missing answers become empty) so the miner and
+ * the UI can iterate a stable set. `validIssueNumbers` (optional) filters cited
+ * numbers to the series' real issues.
+ */
+export function sanitizePersonaResponse(personaId, raw, { validIssueNumbers = null } = {}) {
+ const validSet = Array.isArray(validIssueNumbers) ? new Set(validIssueNumbers) : null;
+ const src = raw && typeof raw === 'object' ? (raw.answers && typeof raw.answers === 'object' ? raw.answers : raw) : {};
+ const answers = {};
+ for (const qid of PANEL_QUESTION_IDS) {
+ const a = src[qid];
+ if (a && typeof a === 'object' && !Array.isArray(a)) {
+ answers[qid] = { text: cleanStr(a.text ?? a.answer, ANSWER_TEXT_MAX), issues: cleanIssueNumbers(a.issues ?? a.issueNumbers, validSet) };
+ } else if (typeof a === 'string') {
+ answers[qid] = { text: cleanStr(a, ANSWER_TEXT_MAX), issues: [] };
+ } else {
+ answers[qid] = { text: '', issues: [] };
+ }
+ }
+ return {
+ persona: personaId,
+ answers,
+ verdict: cleanStr(raw?.verdict ?? raw?.summary, VERDICT_MAX),
+ };
+}
+
+// Build `Map<issueNumber, Set<personaId>>` of who cited each issue for one
+// question across the panel.
+function citationsForQuestion(responses, qid) {
+ const map = new Map();
+ for (const r of responses) {
+ const cited = r?.answers?.[qid]?.issues;
+ if (!Array.isArray(cited)) continue;
+ for (const n of cited) {
+ let set = map.get(n);
+ if (!set) { set = new Set(); map.set(n, set); }
+ set.add(r.persona);
+ }
+ }
+ return map;
+}
+
+const sortEntries = (arr) => arr.sort((a, b) => (b.count - a.count) || (a.issueNumber - b.issueNumber) || a.questionId.localeCompare(b.questionId));
+
+/**
+ * Mine the panel for disagreement. Returns:
+ * - `consensus`: concern citations agreed by ≥ CONSENSUS_THRESHOLD personas
+ * (routed to findings by `consensusToFindings`).
+ * - `attention`: concern citations by SOME but not all personas, below the
+ * consensus bar — surfaced for the human as a judgment call.
+ * - `polarizing`: issues one persona named their BEST scene while another named
+ * their WORST — the sharpest single-issue disagreements.
+ * `totalPersonas` echoes how many responses fed the mine (the "all" denominator).
+ */
+export function minePanelDisagreements(responses, { validIssueNumbers = null, consensusThreshold = CONSENSUS_THRESHOLD } = {}) {
+ const list = Array.isArray(responses) ? responses.filter((r) => r && typeof r === 'object' && r.persona) : [];
+ const validSet = Array.isArray(validIssueNumbers) ? new Set(validIssueNumbers) : null;
+ const totalPersonas = list.length;
+
+ const consensus = [];
+ const attention = [];
+ for (const qid of CONCERN_QUESTION_IDS) {
+ const q = QUESTION_BY_ID.get(qid);
+ const cites = citationsForQuestion(list, qid);
+ for (const [issueNumber, personaSet] of cites) {
+ if (validSet && !validSet.has(issueNumber)) continue;
+ const count = personaSet.size;
+ if (count < 1) continue;
+ const entry = {
+ questionId: qid,
+ questionLabel: q.label,
+ category: q.category,
+ issueNumber,
+ personas: [...personaSet],
+ count,
+ };
+ if (count >= consensusThreshold) consensus.push(entry);
+ else if (count < totalPersonas) attention.push(entry);
+ }
+ }
+
+ // Polarizing: best_scene vs worst_scene on the same issue.
+ const loved = citationsForQuestion(list, 'best_scene');
+ const hated = citationsForQuestion(list, 'worst_scene');
+ const polarizing = [];
+ for (const [issueNumber, lovedBy] of loved) {
+ if (validSet && !validSet.has(issueNumber)) continue;
+ const hatedBy = hated.get(issueNumber);
+ if (hatedBy && hatedBy.size) {
+ polarizing.push({ issueNumber, lovedBy: [...lovedBy], hatedBy: [...hatedBy] });
+ }
+ }
+ polarizing.sort((a, b) => a.issueNumber - b.issueNumber);
+
+ return {
+ totalPersonas,
+ consensusThreshold,
+ consensus: sortEntries(consensus),
+ attention: sortEntries(attention),
+ polarizing,
+ };
+}
+
+/**
+ * Shape consensus entries into `seedReviewFromFindings` findings. A concern
+ * agreed by every persona is `high`; one merely at/above the consensus bar is
+ * `medium`. `problem` names the agreeing personas and folds in a short quote from
+ * each so the triage view shows WHY it was flagged.
+ */
+export function consensusToFindings(consensus, responses, { checkId = 'reader-panel.consensus', totalPersonas } = {}) {
+ const list = Array.isArray(responses) ? responses : [];
+ const byPersona = new Map(list.map((r) => [r.persona, r]));
+ const denom = Number.isInteger(totalPersonas) ? totalPersonas : list.length;
+ const findings = [];
+ for (const entry of Array.isArray(consensus) ? consensus : []) {
+ const names = entry.personas.map(personaLabel).join(', ');
+ const snippets = entry.personas
+ .map((pid) => {
+ const text = byPersona.get(pid)?.answers?.[entry.questionId]?.text;
+ return text ? `${personaLabel(pid)}: “${text.slice(0, 220)}”` : '';
+ })
+ .filter(Boolean)
+ .join(' ');
+ const lead = `Reader panel (${entry.count}/${denom}: ${names}) agree on "${entry.questionLabel}" at issue #${entry.issueNumber}.`;
+ findings.push({
+ severity: entry.count >= denom ? 'high' : 'medium',
+ category: entry.category,
+ problem: `${lead}${snippets ? ` ${snippets}` : ''}`.slice(0, PROBLEM_MAX),
+ issueNumber: entry.issueNumber,
+ checkId,
+ });
+ }
+ return findings;
+}
+
+export const __testing = { cleanIssueNumbers, citationsForQuestion };
diff --git a/server/lib/editorial/panelDisagreement.test.js b/server/lib/editorial/panelDisagreement.test.js
new file mode 100644
index 0000000000..28b4f7429b
--- /dev/null
+++ b/server/lib/editorial/panelDisagreement.test.js
@@ -0,0 +1,193 @@
+import { describe, it, expect } from 'vitest';
+import {
+ PANEL_PERSONAS,
+ PANEL_PERSONA_IDS,
+ PANEL_QUESTION_IDS,
+ CONSENSUS_THRESHOLD,
+ personaLabel,
+ sanitizePersonaResponse,
+ minePanelDisagreements,
+ consensusToFindings,
+ __testing,
+} from './panelDisagreement.js';
+
+// Build a persona response with the given per-question issue citations.
+// `cites` maps questionId -> issue-number array; unlisted questions get a
+// generic non-empty answer with no citations.
+function persona(id, cites = {}) {
+ const answers = {};
+ for (const qid of PANEL_QUESTION_IDS) {
+ answers[qid] = { text: `${id} on ${qid}`, issues: cites[qid] || [] };
+ }
+ return { persona: id, answers, verdict: `${id} verdict` };
+}
+
+describe('panel vocabulary', () => {
+ it('has four personas whose ids match the stage-prompt suffixes', () => {
+ expect(PANEL_PERSONA_IDS).toEqual(['editor', 'genre-reader', 'writer', 'first-reader']);
+ expect(PANEL_PERSONAS).toHaveLength(4);
+ });
+ it('has ten questions including the required ids', () => {
+ for (const q of ['momentum_loss', 'earned_ending', 'cut_candidate', 'missing_scene', 'thinnest_character',
+ 'best_scene', 'worst_scene', 'would_recommend', 'haunts_you', 'next_book']) {
+ expect(PANEL_QUESTION_IDS).toContain(q);
+ }
+ expect(PANEL_QUESTION_IDS).toHaveLength(10);
+ });
+ it('labels personas', () => {
+ expect(personaLabel('editor')).toBe('The Editor');
+ expect(personaLabel('unknown')).toBe('unknown');
+ });
+});
+
+describe('sanitizePersonaResponse', () => {
+ it('normalizes a full answers object and clamps issue numbers', () => {
+ const raw = {
+ verdict: 'strong but slow',
+ answers: {
+ momentum_loss: { text: 'drags in the middle', issues: [3, 3, 4, '5', -1, 2.5, null] },
+ best_scene: { answer: 'the confrontation', issues: [7] },
+ },
+ };
+ const out = sanitizePersonaResponse('editor', raw);
+ expect(out.persona).toBe('editor');
+ expect(out.verdict).toBe('strong but slow');
+ // dedupes, drops non-positive-integers, sorts
+ expect(out.answers.momentum_loss.issues).toEqual([3, 4, 5]);
+ expect(out.answers.momentum_loss.text).toBe('drags in the middle');
+ // accepts `answer` alias
+ expect(out.answers.best_scene.text).toBe('the confrontation');
+ // every question id present even when absent from input
+ for (const qid of PANEL_QUESTION_IDS) expect(out.answers[qid]).toBeDefined();
+ expect(out.answers.worst_scene).toEqual({ text: '', issues: [] });
+ });
+
+ it('filters citations to the valid issue-number allow-list', () => {
+ const out = sanitizePersonaResponse('writer',
+ { answers: { cut_candidate: { text: 'x', issues: [2, 99, 4] } } },
+ { validIssueNumbers: [1, 2, 3, 4] });
+ expect(out.answers.cut_candidate.issues).toEqual([2, 4]);
+ });
+
+ it('tolerates a flat map (no answers wrapper) and string answers', () => {
+ const out = sanitizePersonaResponse('first-reader', { momentum_loss: 'got bored at the end' });
+ expect(out.answers.momentum_loss).toEqual({ text: 'got bored at the end', issues: [] });
+ });
+
+ it('cleanIssueNumbers dedupes, sorts, and caps', () => {
+ const many = Array.from({ length: 30 }, (_, i) => i + 1);
+ expect(__testing.cleanIssueNumbers(many)).toHaveLength(12);
+ expect(__testing.cleanIssueNumbers([5, 1, 5, 3])).toEqual([1, 3, 5]);
+ expect(__testing.cleanIssueNumbers('nope')).toEqual([]);
+ });
+});
+
+describe('minePanelDisagreements', () => {
+ it('routes a ≥3-persona concern into consensus, below into attention', () => {
+ const responses = [
+ persona('editor', { momentum_loss: [4], cut_candidate: [2] }),
+ persona('genre-reader', { momentum_loss: [4], cut_candidate: [9] }),
+ persona('writer', { momentum_loss: [4] }),
+ persona('first-reader', {}),
+ ];
+ const mined = minePanelDisagreements(responses, { validIssueNumbers: [2, 4, 9] });
+ expect(mined.totalPersonas).toBe(4);
+ expect(mined.consensusThreshold).toBe(CONSENSUS_THRESHOLD);
+
+ // issue #4 momentum_loss cited by 3 personas -> consensus
+ const c = mined.consensus.find((e) => e.issueNumber === 4 && e.questionId === 'momentum_loss');
+ expect(c).toBeTruthy();
+ expect(c.count).toBe(3);
+ expect(c.personas.sort()).toEqual(['editor', 'genre-reader', 'writer']);
+
+ // issue #2 cut_candidate cited by 1 persona -> attention (some but not all)
+ const a = mined.attention.find((e) => e.issueNumber === 2 && e.questionId === 'cut_candidate');
+ expect(a).toBeTruthy();
+ expect(a.count).toBe(1);
+ // consensus items never also appear in attention
+ expect(mined.attention.some((e) => e.issueNumber === 4 && e.questionId === 'momentum_loss')).toBe(false);
+ });
+
+ it('a unanimous concern is consensus, not attention', () => {
+ const responses = PANEL_PERSONA_IDS.map((id) => persona(id, { worst_scene: [5] }));
+ const mined = minePanelDisagreements(responses, { validIssueNumbers: [5] });
+ const c = mined.consensus.find((e) => e.issueNumber === 5 && e.questionId === 'worst_scene');
+ expect(c.count).toBe(4);
+ expect(mined.attention).toHaveLength(0);
+ });
+
+ it('only concern questions feed consensus/attention (evaluative ones do not)', () => {
+ // earned_ending is not a concern; three personas citing it must not surface.
+ const responses = [
+ persona('editor', { earned_ending: [1] }),
+ persona('genre-reader', { earned_ending: [1] }),
+ persona('writer', { earned_ending: [1] }),
+ persona('first-reader', {}),
+ ];
+ const mined = minePanelDisagreements(responses);
+ expect(mined.consensus).toHaveLength(0);
+ expect(mined.attention).toHaveLength(0);
+ });
+
+ it('detects polarizing best-vs-worst on the same issue', () => {
+ const responses = [
+ persona('editor', { best_scene: [7] }),
+ persona('genre-reader', { worst_scene: [7] }),
+ persona('writer', { best_scene: [3] }),
+ persona('first-reader', {}),
+ ];
+ const mined = minePanelDisagreements(responses, { validIssueNumbers: [3, 7] });
+ expect(mined.polarizing).toHaveLength(1);
+ expect(mined.polarizing[0]).toMatchObject({ issueNumber: 7, lovedBy: ['editor'], hatedBy: ['genre-reader'] });
+ });
+
+ it('drops hallucinated issue numbers when an allow-list is given', () => {
+ const responses = PANEL_PERSONA_IDS.map((id) => persona(id, { momentum_loss: [42] }));
+ const mined = minePanelDisagreements(responses, { validIssueNumbers: [1, 2, 3] });
+ expect(mined.consensus).toHaveLength(0);
+ });
+
+ it('respects a custom consensus threshold', () => {
+ const responses = [
+ persona('editor', { momentum_loss: [4] }),
+ persona('genre-reader', { momentum_loss: [4] }),
+ persona('writer', {}),
+ persona('first-reader', {}),
+ ];
+ const mined = minePanelDisagreements(responses, { validIssueNumbers: [4], consensusThreshold: 2 });
+ expect(mined.consensus.find((e) => e.issueNumber === 4)).toBeTruthy();
+ });
+});
+
+describe('consensusToFindings', () => {
+ const responses = [
+ persona('editor', { momentum_loss: [4] }),
+ persona('genre-reader', { momentum_loss: [4] }),
+ persona('writer', { momentum_loss: [4] }),
+ persona('first-reader', { momentum_loss: [4] }),
+ ];
+
+ it('maps consensus entries to seedable findings with severity by count', () => {
+ const mined = minePanelDisagreements(responses, { validIssueNumbers: [4] });
+ const findings = consensusToFindings(mined.consensus, responses, { totalPersonas: 4 });
+ expect(findings).toHaveLength(1);
+ const f = findings[0];
+ expect(f.issueNumber).toBe(4);
+ expect(f.checkId).toBe('reader-panel.consensus');
+ expect(f.category).toBe('pacing'); // momentum_loss category
+ expect(f.severity).toBe('high'); // 4/4 == all personas
+ expect(f.problem).toContain('#4');
+ expect(f.problem).toContain('The Editor');
+ });
+
+ it('grades a non-unanimous consensus as medium', () => {
+ const three = responses.slice(0, 3);
+ const mined = minePanelDisagreements(three, { validIssueNumbers: [4] });
+ const findings = consensusToFindings(mined.consensus, three, { totalPersonas: 4 });
+ expect(findings[0].severity).toBe('medium');
+ });
+
+ it('returns [] for empty consensus', () => {
+ expect(consensusToFindings([], responses, { totalPersonas: 4 })).toEqual([]);
+ });
+});
diff --git a/server/routes/pipeline/editorial.js b/server/routes/pipeline/editorial.js
index b71ae8628f..917591be92 100644
--- a/server/routes/pipeline/editorial.js
+++ b/server/routes/pipeline/editorial.js
@@ -29,6 +29,8 @@ import * as seriesSvc from '../../services/pipeline/series.js';
import * as issuesSvc from '../../services/pipeline/issues.js';
import * as editorialAnalysis from '../../services/pipeline/editorialAnalysis.js';
import * as editorialRunner from '../../services/pipeline/editorialAnalysisRunner.js';
+import * as readerPanel from '../../services/pipeline/readerPanel.js';
+import * as readerPanelRunner from '../../services/pipeline/readerPanelRunner.js';
import * as checkRunner from '../../services/pipeline/editorial/checkRunner.js';
import { getSeriesHealth, READINESS_GATES, DEFAULT_READINESS_GATE } from '../../services/pipeline/editorialScore.js';
import { getSettings, updateSettingsWith } from '../../services/settings.js';
@@ -92,6 +94,47 @@ router.post('/series/:id/editorial/analyze/cancel', asyncHandler(async (req, res
res.json({ canceled });
}));
+// ---------------------------------------------------------------------------
+// Reader panel (#2170, CWQE Phase 6) — four personas read a condensed arc
+// digest and answer qualitative questions; ≥3-persona consensus concerns route
+// into manuscript-review findings, disagreements surface for the human. One LLM
+// call per persona — runs only from this explicit action (AI-provider policy).
+// ---------------------------------------------------------------------------
+
+// Stored panel: { status, personas[], disagreements, seededFindings, stale, ... }
+// or { status: 'none' }.
+router.get('/series/:id/editorial/panel', asyncHandler(async (req, res) => {
+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ res.json(await readerPanel.getReaderPanel(req.params.id));
+}));
+
+// Convene the panel (batch — per-persona progress via SSE).
+router.post('/series/:id/editorial/panel/run', asyncHandler(async (req, res) => {
+ const body = validateRequest(editorialAnalyzeSchema, req.body ?? {});
+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const result = readerPanelRunner.startReaderPanel(req.params.id, body);
+ res.json({
+ ...result,
+ sseUrl: `/api/pipeline/series/${req.params.id}/editorial/panel/run/progress`,
+ });
+}));
+
+router.get('/series/:id/editorial/panel/run/progress', (req, res) => {
+ const attached = readerPanelRunner.attachClient(req.params.id, res);
+ if (!attached) {
+ throw new ServerError('No active reader-panel run for this series', { status: 404 });
+ }
+});
+
+// Lightweight probe so a (re)mounting client can re-attach to an in-flight run.
+router.get('/series/:id/editorial/panel/run/status', (req, res) => {
+ res.json({ active: readerPanelRunner.isReaderPanelActive(req.params.id) });
+});
+
+router.post('/series/:id/editorial/panel/run/cancel', asyncHandler(async (req, res) => {
+ res.json({ canceled: readerPanelRunner.cancelReaderPanel(req.params.id) });
+}));
+
// ---------------------------------------------------------------------------
// Editorial checks (#1284) — registry-driven editorial review.
// ---------------------------------------------------------------------------
diff --git a/server/services/pipeline/readerPanel.js b/server/services/pipeline/readerPanel.js
new file mode 100644
index 0000000000..b04d053dde
--- /dev/null
+++ b/server/services/pipeline/readerPanel.js
@@ -0,0 +1,154 @@
+/**
+ * Pipeline — Reader panel (#2170, CWQE Phase 6).
+ *
+ * Four reader personas each read a condensed arc digest of a series (see
+ * readerPanelDigest.js) and answer the same ~10 qualitative questions, citing
+ * issue numbers. The editorial value is the DISAGREEMENT between them: issues
+ * flagged by some-but-not-all personas are surfaced for the human as judgment
+ * calls; issues with ≥3-persona consensus are routed into the normal
+ * manuscript-review triage flow via `seedReviewFromFindings`.
+ *
+ * One LLM call per persona, run only from an explicit user action (the panel
+ * "Convene" button) or an autopilot step — never at boot (AI-provider policy).
+ * The snapshot persists at `data/pipeline-reader-panel/{seriesId}.json` and pins
+ * the digest's `sourceContentHash` so the UI can flag a stale panel after edits.
+ *
+ * The batch lifecycle (per-persona SSE progress) lives in readerPanelRunner.js;
+ * pure mining lives in server/lib/editorial/panelDisagreement.js. Errors bubble
+ * (no try/catch) — the runner owns the boundary.
+ */
+
+import { join } from 'path';
+import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../../lib/fileUtils.js';
+import { runStagedLLM } from '../../lib/stageRunner.js';
+import {
+ PANEL_PERSONAS,
+ PANEL_PERSONA_IDS,
+ minePanelDisagreements,
+ consensusToFindings,
+ sanitizePersonaResponse,
+} from '../../lib/editorial/panelDisagreement.js';
+import { buildDigestForSeries, renderDigestText } from './readerPanelDigest.js';
+import { seedReviewFromFindings } from './manuscriptReview.js';
+
+const CONSENSUS_CHECK_ID = 'reader-panel.consensus';
+const nowIso = () => new Date().toISOString();
+
+// Series ids are `ser-<uuid>` — restrict to a safe charset before interpolating
+// into the on-disk snapshot path (defense-in-depth against path traversal).
+function assertValidSeriesId(id) {
+ if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(id)) {
+ throw new Error(`Invalid series id: ${id}`);
+ }
+}
+
+const panelDir = () => join(PATHS.data, 'pipeline-reader-panel');
+const snapshotPath = (seriesId) => join(panelDir(), `${seriesId}.json`);
+
+async function loadSnapshot(seriesId) {
+ const content = await tryReadFile(snapshotPath(seriesId));
+ if (content === null) return null;
+ return safeJSONParse(content, null, { allowArray: false, logError: true, context: snapshotPath(seriesId) });
+}
+
+async function saveSnapshot(snapshot) {
+ await ensureDir(panelDir());
+ await atomicWrite(snapshotPath(snapshot.seriesId), snapshot);
+}
+
+const personaStage = (personaId) => `pipeline-panel-${personaId}`;
+
+// Shared variables every persona prompt reads — the rendered digest + series meta.
+function digestVariables(digest) {
+ return {
+ seriesName: digest.seriesName,
+ logline: digest.logline || '',
+ issueCount: digest.issueCount,
+ digest: renderDigestText(digest),
+ };
+}
+
+/**
+ * Run ONE persona over the digest. Returns the sanitized response
+ * `{ persona, answers, verdict }` plus provider/model/runId provenance. The
+ * `validIssueNumbers` from the digest clamp cited numbers to real issues.
+ */
+export async function runPersona(personaId, digest, { providerId, model } = {}) {
+ if (!PANEL_PERSONA_IDS.includes(personaId)) throw new Error(`Unknown reader-panel persona: ${personaId}`);
+ const result = await runStagedLLM(personaStage(personaId), digestVariables(digest), {
+ returnsJson: true,
+ providerOverride: providerId,
+ modelOverride: model,
+ source: `reader-panel:${personaId}`,
+ });
+ const response = sanitizePersonaResponse(personaId, result.content, { validIssueNumbers: digest.issueNumbers });
+ return { ...response, providerId: result.providerId, model: result.model, runId: result.runId, completedAt: nowIso() };
+}
+
+/**
+ * Finalize a panel: mine cross-persona disagreement, route ≥3-persona consensus
+ * concerns into manuscript-review findings, persist the snapshot, and return it.
+ * `mode: 'fresh'` scoped to the reader-panel check id reconciles a re-run's
+ * findings (a consensus that's no longer surfaced is auto-dismissed).
+ */
+export async function finalizePanel(seriesId, digest, responses, { runId = null } = {}) {
+ const disagreements = minePanelDisagreements(responses, { validIssueNumbers: digest.issueNumbers });
+ const findings = consensusToFindings(disagreements.consensus, responses, {
+ checkId: CONSENSUS_CHECK_ID,
+ totalPersonas: disagreements.totalPersonas,
+ });
+
+ let seededFindings = 0;
+ if (findings.length || responses.length) {
+ // Even with zero findings, run in 'fresh' mode so a re-run that resolved a
+ // prior consensus auto-dismisses that stale finding.
+ await seedReviewFromFindings(seriesId, findings, {
+ runId,
+ mode: 'fresh',
+ checkId: CONSENSUS_CHECK_ID,
+ });
+ seededFindings = findings.length;
+ }
+
+ const snapshot = {
+ seriesId,
+ status: 'complete',
+ sourceContentHash: digest.sourceContentHash,
+ digestGeneratedAt: digest.generatedAt,
+ issueCount: digest.issueCount,
+ personas: responses,
+ disagreements,
+ seededFindings,
+ checkId: CONSENSUS_CHECK_ID,
+ runId,
+ createdAt: nowIso(),
+ completedAt: nowIso(),
+ };
+ await saveSnapshot(snapshot);
+ console.log(`🪞 reader panel: series=${seriesId.slice(0, 12)} personas=${responses.length} consensus=${disagreements.consensus.length} attention=${disagreements.attention.length} seeded=${seededFindings}`);
+ return snapshot;
+}
+
+// Re-hash the current issue content to decide whether a stored panel is stale
+// (the drafts moved since the digest was built). Cheap — issues + content only,
+// no scene segmentation.
+async function isPanelStale(snapshot, seriesId) {
+ if (!snapshot || snapshot.status !== 'complete' || !snapshot.sourceContentHash) return false;
+ const digest = await buildDigestForSeries(seriesId).catch(() => null);
+ if (!digest) return false;
+ return digest.sourceContentHash !== snapshot.sourceContentHash;
+}
+
+/**
+ * Load the stored panel with a `stale` flag. Returns `{ status: 'none' }` when
+ * the panel has never been convened.
+ */
+export async function getReaderPanel(seriesId) {
+ assertValidSeriesId(seriesId);
+ const snapshot = await loadSnapshot(seriesId);
+ if (!snapshot) return { seriesId, status: 'none', personas: [], disagreements: null };
+ return { ...snapshot, stale: await isPanelStale(snapshot, seriesId) };
+}
+
+export const PANEL_META = { personas: PANEL_PERSONAS, consensusCheckId: CONSENSUS_CHECK_ID };
+export const __testing = { assertValidSeriesId, CONSENSUS_CHECK_ID };
diff --git a/server/services/pipeline/readerPanelDigest.js b/server/services/pipeline/readerPanelDigest.js
new file mode 100644
index 0000000000..4ccd290a9c
--- /dev/null
+++ b/server/services/pipeline/readerPanelDigest.js
@@ -0,0 +1,174 @@
+/**
+ * Pipeline — Reader-panel arc digest builder (#2170, CWQE Phase 6).
+ *
+ * A reader panel of four personas shouldn't be handed the raw 75k-word
+ * manuscript — it reads a condensed, content-hash-pinned digest. Per issue the
+ * digest carries a short summary, a ~150-word opening + closing excerpt, and the
+ * top few dialogue lines, reusing `reverseOutline.js` scene segmentation (scene
+ * `summary`s) where available and falling back to the drafted text otherwise.
+ *
+ * The pure assembly helpers (`buildIssueDigest`, `renderDigestText`, excerpt /
+ * dialogue extraction) are exported for unit testing; `buildDigestForSeries`
+ * wires the I/O (issues + scenes + series record).
+ */
+
+import { createHash } from 'crypto';
+import { pickAnalyzableContent } from './editorialAnalysis.js';
+import { getSceneSegmentation } from './reverseOutline.js';
+import { listIssues } from './issues.js';
+import { getSeries } from './series.js';
+
+const OPENING_WORDS = 150;
+const CLOSING_WORDS = 150;
+const SUMMARY_SENTENCES = 3;
+const DIALOGUE_LINES = 3;
+const SUMMARY_MAX = 600;
+
+const nowIso = () => new Date().toISOString();
+
+// Collapse whitespace so word/sentence slicing isn't skewed by markdown blank
+// lines. Strips markdown heading/emphasis markers that would leak into excerpts.
+function normalizeText(text) {
+ return String(text || '')
+ .replace(/[*_`#>]+/g, ' ')
+ .replace(/\s+/g, ' ')
+ .trim();
+}
+
+export function firstWords(text, n = OPENING_WORDS) {
+ const words = normalizeText(text).split(' ').filter(Boolean);
+ if (words.length <= n) return words.join(' ');
+ return `${words.slice(0, n).join(' ')}…`;
+}
+
+export function lastWords(text, n = CLOSING_WORDS) {
+ const words = normalizeText(text).split(' ').filter(Boolean);
+ if (words.length <= n) return words.join(' ');
+ return `…${words.slice(words.length - n).join(' ')}`;
+}
+
+export function firstSentences(text, n = SUMMARY_SENTENCES) {
+ const clean = normalizeText(text);
+ if (!clean) return '';
+ const sentences = clean.match(/[^.!?]+[.!?]+/g) || [clean];
+ return sentences.slice(0, n).join(' ').trim().slice(0, SUMMARY_MAX);
+}
+
+/**
+ * Pull the strongest dialogue lines out of drafted prose/script text — a simple
+ * pure heuristic (double-quoted spans of a sensible length), deduped and capped.
+ * Comic/teleplay dialogue that isn't quoted just yields fewer lines; the panel
+ * still gets summary + excerpts.
+ */
+export function extractDialogueLines(text, n = DIALOGUE_LINES) {
+ const clean = String(text || '').replace(/[“”]/g, '"').replace(/\s+/g, ' ');
+ const matches = clean.match(/"([^"]{8,160})"/g) || [];
+ const out = [];
+ const seen = new Set();
+ for (const m of matches) {
+ const line = m.slice(1, -1).trim();
+ const key = line.toLowerCase();
+ if (!line || seen.has(key)) continue;
+ seen.add(key);
+ out.push(line);
+ if (out.length >= n) break;
+ }
+ return out;
+}
+
+// A 3-sentence summary, preferring the reverse-outline scene summaries for the
+// issue (already condensed, editor-authored) and falling back to the opening of
+// the drafted text.
+function summarize(scenes, text) {
+ const sceneSummaries = scenes
+ .map((s) => (typeof s?.summary === 'string' ? s.summary.trim() : ''))
+ .filter(Boolean);
+ if (sceneSummaries.length) {
+ return sceneSummaries.slice(0, SUMMARY_SENTENCES).join(' ').slice(0, SUMMARY_MAX);
+ }
+ return firstSentences(text, SUMMARY_SENTENCES);
+}
+
+/**
+ * Build one issue's digest from its drafted text + the scenes segmented for it.
+ * Pure — callers supply the text and the (already issue-filtered) scenes.
+ */
+export function buildIssueDigest({ number, title, text, scenes = [] }) {
+ const body = String(text || '');
+ return {
+ number: Number.isInteger(number) ? number : null,
+ title: title || `Issue ${number ?? ''}`.trim(),
+ summary: summarize(scenes, body),
+ opening: firstWords(body, OPENING_WORDS),
+ closing: lastWords(body, CLOSING_WORDS),
+ dialogue: extractDialogueLines(body, DIALOGUE_LINES),
+ sceneCount: scenes.length,
+ };
+}
+
+// Render the structured digest into the compact markdown a persona prompt reads.
+export function renderDigestText(digest) {
+ const parts = [];
+ for (const iss of digest.issues || []) {
+ const lines = [`### Issue #${iss.number}: ${iss.title}`];
+ if (iss.summary) lines.push(`Summary: ${iss.summary}`);
+ if (iss.opening) lines.push(`Opening: ${iss.opening}`);
+ if (iss.closing) lines.push(`Closing: ${iss.closing}`);
+ if (iss.dialogue?.length) lines.push(`Notable dialogue:\n${iss.dialogue.map((d) => `- “${d}”`).join('\n')}`);
+ parts.push(lines.join('\n'));
+ }
+ return parts.join('\n\n');
+}
+
+const digestContentHash = (issues) =>
+ createHash('sha256')
+ .update(issues.map((i) => `${i.number}:${i.text || ''}`).sort().join('\n'))
+ .digest('hex');
+
+/**
+ * Build the full series digest the panel reads. Only issues with drafted
+ * reader-facing content are included. Returns the structured digest plus a
+ * `sourceContentHash` pinning the analyzed drafts (so a later edit flips the
+ * stored panel to stale) and the `issueNumbers` present (the citation allow-list
+ * for disagreement mining).
+ */
+export async function buildDigestForSeries(seriesId, { issues: issuesArg, series: seriesArg } = {}) {
+ const issues = Array.isArray(issuesArg) ? issuesArg : await listIssues({ seriesId });
+ const series = seriesArg !== undefined ? seriesArg : await getSeries(seriesId).catch(() => null);
+ const segmentation = await getSceneSegmentation(seriesId).catch(() => ({ scenes: [] }));
+ const scenesByNumber = new Map();
+ for (const scene of segmentation.scenes || []) {
+ const num = scene?.issueNumber;
+ if (!Number.isInteger(num)) continue;
+ if (!scenesByNumber.has(num)) scenesByNumber.set(num, []);
+ scenesByNumber.get(num).push(scene);
+ }
+
+ const ordered = [...issues].sort(
+ (a, b) => (a.arcPosition ?? 9999) - (b.arcPosition ?? 9999) || (a.number || 0) - (b.number || 0)
+ );
+
+ const withContent = [];
+ for (const issue of ordered) {
+ const picked = pickAnalyzableContent(issue);
+ if (!picked) continue;
+ withContent.push({ number: issue.number, title: issue.title, text: picked.text });
+ }
+
+ const digests = withContent.map((iss) =>
+ buildIssueDigest({ number: iss.number, title: iss.title, text: iss.text, scenes: scenesByNumber.get(iss.number) || [] })
+ );
+
+ return {
+ seriesId,
+ seriesName: series?.name || 'Untitled series',
+ logline: series?.logline || '',
+ issueCount: digests.length,
+ issueNumbers: withContent.map((i) => i.number).filter(Number.isInteger),
+ issues: digests,
+ sourceContentHash: digestContentHash(withContent),
+ generatedAt: nowIso(),
+ };
+}
+
+export const __testing = { normalizeText, summarize, digestContentHash };
diff --git a/server/services/pipeline/readerPanelDigest.test.js b/server/services/pipeline/readerPanelDigest.test.js
new file mode 100644
index 0000000000..d693fe2cc4
--- /dev/null
+++ b/server/services/pipeline/readerPanelDigest.test.js
@@ -0,0 +1,107 @@
+import { describe, it, expect } from 'vitest';
+import {
+ firstWords,
+ lastWords,
+ firstSentences,
+ extractDialogueLines,
+ buildIssueDigest,
+ renderDigestText,
+ __testing,
+} from './readerPanelDigest.js';
+
+const words = (n) => Array.from({ length: n }, (_, i) => `w${i + 1}`).join(' ');
+
+describe('excerpt helpers', () => {
+ it('firstWords caps and ellipsizes past the limit', () => {
+ expect(firstWords(words(10), 5)).toBe('w1 w2 w3 w4 w5…');
+ expect(firstWords(words(3), 5)).toBe('w1 w2 w3');
+ expect(firstWords('', 5)).toBe('');
+ });
+
+ it('lastWords takes the tail with a leading ellipsis', () => {
+ expect(lastWords(words(10), 3)).toBe('…w8 w9 w10');
+ expect(lastWords(words(2), 3)).toBe('w1 w2');
+ });
+
+ it('firstSentences takes N sentences and strips markdown', () => {
+ const text = '## Heading\nOne happened. Two happened! Three? Four.';
+ const out = firstSentences(text, 2);
+ expect(out).toContain('One happened.');
+ expect(out).toContain('Two happened!');
+ expect(out).not.toContain('Three');
+ expect(out).not.toContain('#');
+ });
+});
+
+describe('extractDialogueLines', () => {
+ it('pulls deduped quoted lines within the length window, capped', () => {
+ const text = 'She said "I will not go back there tonight." He replied "I understand." "I will not go back there tonight." said again. "Short" "This is another distinct spoken line of dialogue."';
+ const lines = extractDialogueLines(text, 3);
+ expect(lines).toContain('I will not go back there tonight.');
+ expect(lines).toContain('I understand.');
+ // "Short" is below the 8-char floor, so it's excluded
+ expect(lines).not.toContain('Short');
+ // dedupe: the repeated line appears once
+ expect(lines.filter((l) => l === 'I will not go back there tonight.')).toHaveLength(1);
+ expect(lines.length).toBeLessThanOrEqual(3);
+ });
+
+ it('handles curly quotes and no-dialogue text', () => {
+ expect(extractDialogueLines('He walked in silence to the door.')).toEqual([]);
+ expect(extractDialogueLines('“A curly-quoted line of dialogue here.”')).toEqual(['A curly-quoted line of dialogue here.']);
+ });
+});
+
+describe('buildIssueDigest', () => {
+ const text = 'The rain fell hard. She ran. "We have to move now," he said, breathless. They vanished into the dark alley and were gone.';
+
+ it('produces the digest shape with summary, opening, closing, dialogue', () => {
+ const d = buildIssueDigest({ number: 3, title: 'The Chase', text, scenes: [] });
+ expect(d).toMatchObject({ number: 3, title: 'The Chase', sceneCount: 0 });
+ expect(typeof d.summary).toBe('string');
+ expect(d.summary.length).toBeGreaterThan(0);
+ expect(typeof d.opening).toBe('string');
+ expect(typeof d.closing).toBe('string');
+ expect(Array.isArray(d.dialogue)).toBe(true);
+ expect(d.dialogue).toContain('We have to move now,');
+ });
+
+ it('prefers scene summaries over the drafted text for the summary', () => {
+ const scenes = [{ summary: 'A daring escape through the storm.' }, { summary: 'They regroup in safety.' }];
+ const d = buildIssueDigest({ number: 3, title: 'The Chase', text, scenes });
+ expect(d.summary).toContain('A daring escape through the storm.');
+ expect(d.sceneCount).toBe(2);
+ });
+
+ it('falls back to first sentences when no scenes', () => {
+ const d = buildIssueDigest({ number: 1, title: 'Open', text, scenes: [] });
+ expect(d.summary).toContain('The rain fell hard.');
+ });
+});
+
+describe('renderDigestText', () => {
+ it('renders each issue block with its sections', () => {
+ const digest = {
+ issues: [
+ { number: 1, title: 'A', summary: 'sum', opening: 'open', closing: 'close', dialogue: ['line one here'] },
+ { number: 2, title: 'B', summary: 'sum2', opening: '', closing: '', dialogue: [] },
+ ],
+ };
+ const out = renderDigestText(digest);
+ expect(out).toContain('### Issue #1: A');
+ expect(out).toContain('Summary: sum');
+ expect(out).toContain('Opening: open');
+ expect(out).toContain('“line one here”');
+ expect(out).toContain('### Issue #2: B');
+ });
+});
+
+describe('digestContentHash', () => {
+ it('is stable to ordering and changes with content', () => {
+ const a = __testing.digestContentHash([{ number: 1, text: 'x' }, { number: 2, text: 'y' }]);
+ const b = __testing.digestContentHash([{ number: 2, text: 'y' }, { number: 1, text: 'x' }]);
+ const c = __testing.digestContentHash([{ number: 1, text: 'x' }, { number: 2, text: 'z' }]);
+ expect(a).toBe(b);
+ expect(a).not.toBe(c);
+ });
+});
diff --git a/server/services/pipeline/readerPanelRunner.js b/server/services/pipeline/readerPanelRunner.js
new file mode 100644
index 0000000000..8b6056000f
--- /dev/null
+++ b/server/services/pipeline/readerPanelRunner.js
@@ -0,0 +1,78 @@
+/**
+ * Pipeline — Batch runner for the reader panel (#2170, CWQE Phase 6).
+ *
+ * Convenes the four-persona panel for a series, streaming per-persona progress
+ * to attached SSE clients. Mirrors editorialAnalysisRunner.js: one in-memory
+ * `runs` map keyed by `seriesId`, terminal-frame replay for late clients.
+ *
+ * This is the ONLY entry that spends LLM calls for the panel — it runs only from
+ * the explicit `POST /series/:id/editorial/panel/run` action (or an autopilot
+ * step), never at boot (AI-provider policy).
+ */
+
+import { createSseRunner } from '../../lib/sseUtils.js';
+import { PANEL_PERSONAS } from '../../lib/editorial/panelDisagreement.js';
+import { buildDigestForSeries } from './readerPanelDigest.js';
+import { runPersona, finalizePanel } from './readerPanel.js';
+
+const runner = createSseRunner({ logLabel: 'reader panel' });
+
+export function isReaderPanelActive(seriesId) {
+ return runner.isActive(seriesId);
+}
+
+export function attachClient(seriesId, res) {
+ return runner.attachClient(seriesId, res);
+}
+
+export function cancelReaderPanel(seriesId) {
+ return runner.cancel(seriesId);
+}
+
+/**
+ * Kick off the panel run. Returns the runId immediately; per-persona progress
+ * lands via SSE. Re-calling while a run is in flight resolves to the existing
+ * runId.
+ */
+export function startReaderPanel(seriesId, options = {}) {
+ return runner.start(seriesId, async ({ runId, record, broadcast }) => {
+ const digest = await buildDigestForSeries(seriesId);
+ if (!digest.issueCount) {
+ broadcast({ type: 'complete', runId, personas: 0, empty: true, completedAt: new Date().toISOString() });
+ return;
+ }
+
+ broadcast({ type: 'start', runId, total: PANEL_PERSONAS.length, issueCount: digest.issueCount });
+
+ const responses = [];
+ let done = 0;
+ for (const persona of PANEL_PERSONAS) {
+ if (record.cancelRequested) break;
+ broadcast({ type: 'persona:start', persona: persona.id, label: persona.label, done, total: PANEL_PERSONAS.length });
+ const response = await runPersona(persona.id, digest, {
+ providerId: options.providerId,
+ model: options.model,
+ });
+ responses.push(response);
+ done += 1;
+ broadcast({ type: 'persona:complete', persona: persona.id, label: persona.label, done, total: PANEL_PERSONAS.length });
+ }
+
+ if (record.cancelRequested) {
+ broadcast({ type: 'canceled', runId, personas: responses.length, canceledAt: new Date().toISOString() });
+ return;
+ }
+
+ const snapshot = await finalizePanel(seriesId, digest, responses, { runId });
+ broadcast({
+ type: 'complete',
+ runId,
+ personas: responses.length,
+ consensus: snapshot.disagreements?.consensus?.length || 0,
+ seededFindings: snapshot.seededFindings || 0,
+ completedAt: new Date().toISOString(),
+ });
+ });
+}
+
+export const __testing = { runs: runner.runs };