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(pipeline): real editorial reader-emotion / plot / character roadmap

Adam Eivy97062e76d825
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index b91956548c..c99a0ad216 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -8,6 +8,7 @@ TBD
## Added
+- **The Editorial Roadmap is now a real reader-emotion / plot / character analysis tool.** The Plot / Character / Reader chart on a Series page used to be a decorative placeholder — the curves were generated math, "98%" meant nothing, and "Reader: Draft eval pending" did nothing. Now an **Interpret reader map** button runs an LLM pass over each issue's actual content (prose, falling back to comic script or teleplay) and maps, section by section (scene/paragraph), what a reader feels — emotion, tension, and emotional valence — plus per-issue plot tension and character arcs. The panel's three curves and labeled cards are computed from that analysis: **Plot** = narrative tension, **Character** = the detected protagonist and how far their arc advances (with a count of supporting characters who have arcs), **Reader** = the reader's emotional journey. A new **Reader Map** page (`/pipeline/series/:id/roadmap`, reached via "View reader map") shows the full per-issue, section-by-section emotion log and a character-arc breakdown that answers "is this the protagonist? do other characters have arcs?". Analysis results are cached per issue and flagged **stale** when you edit the content, and you can re-run the whole series or a single issue. Batch progress streams live.
- **Hand coding tasks to an agent by voice.** Settings → Voice has a new "Enable coding-agent delegation" toggle (under Tools). With it on, you can say things like "have the agent fix the failing backup test" or "refactor the widget registry and open a PR" — the voice Chief-of-Staff hands the task to a CLI coding agent (Claude Code, Codex, Gemini) that works in an isolated git worktree and opens a pull request for review. Your fast local voice model stays the conversational layer; only the heavy coding work delegates out, so the chat stays snappy. Pick which coding agent runs the task (defaults to your active AI provider → model from Settings → Providers), and the assistant speaks the result when the task finishes (this completion announcement still respects quiet hours, and you can turn it off). The work runs in the background — your working tree is never touched; you review the PR.
- **Set your home location in Settings → General.** Enter a latitude and longitude and the voice assistant's weather command ("what's the weather?") reports conditions for where you are instead of a default city. Leave both fields blank to fall back to the default location.
diff --git a/client/src/App.jsx b/client/src/App.jsx
index d006481953..c04d277c2c 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -78,6 +78,7 @@ const Pipeline = lazyWithReload(() => import('./pages/Pipeline'));
const Sharing = lazyWithReload(() => import('./pages/Sharing'));
const Importer = lazyWithReload(() => import('./pages/Importer'));
const PipelineSeries = lazyWithReload(() => import('./pages/PipelineSeries'));
+const PipelineSeriesRoadmap = lazyWithReload(() => import('./pages/PipelineSeriesRoadmap'));
const PipelineIssue = lazyWithReload(() => import('./pages/PipelineIssue'));
// Loading fallback for lazy-loaded pages
@@ -267,6 +268,7 @@ export default function App() {
<Route path="importer" element={<Importer />} />
<Route path="pipeline" element={<Pipeline />} />
<Route path="pipeline/series/:seriesId" element={<PipelineSeries />} />
+ <Route path="pipeline/series/:seriesId/roadmap" element={<PipelineSeriesRoadmap />} />
<Route path="pipeline/series/:seriesId/sync" element={<SyncView kind="series" param="seriesId" backPath="/pipeline" />} />
<Route path="pipeline/issues/:issueId" element={<Navigate to="idea" replace />} />
<Route path="pipeline/issues/:issueId/:stage" element={<PipelineIssue />} />
diff --git a/client/src/components/pipeline/ArcCanvas.jsx b/client/src/components/pipeline/ArcCanvas.jsx
index 83f4eb39ef..d7aafa8e8a 100644
--- a/client/src/components/pipeline/ArcCanvas.jsx
+++ b/client/src/components/pipeline/ArcCanvas.jsx
@@ -49,6 +49,8 @@ import {
} from '../../services/api';
import useMediaJobProgress from '../../hooks/useMediaJobProgress';
import { usePipelineVolumeBeatsProgress } from '../../hooks/usePipelineVolumeBeatsProgress';
+import { useSeriesEditorial } from '../../hooks/useSeriesEditorial';
+import { dominant } from '../../lib/editorialRoadmap';
import SeriesLlmPicker from './SeriesLlmPicker';
import { ArcShapePicker, ArcShapeSparkline, getStoryShape } from './StoryShapes';
@@ -351,96 +353,156 @@ function VolumeNavigator({ seasons, issuesBySeason, activeSeasonId, onSelect })
}
function EditorialRoadmapPanel({ series, seasons, issues }) {
- const points = useMemo(() => buildRoadmapPoints(issues), [issues]);
const seasonCount = seasons.length;
const issueCount = issues.length;
- const arcReady = !!(series.arc?.summary || series.arc?.protagonistArc || issueCount);
+ const {
+ aggregate, loading, running, starting,
+ startAnalysis, cancelAnalysis, coverage, analyzedPoints, progressText,
+ } = useSeriesEditorial(series.id);
+
+ const hasData = analyzedPoints.length > 0;
+ const plotVals = analyzedPoints.map((p) => p.plot);
+ const avgPlot = plotVals.length ? Math.round(plotVals.reduce((a, b) => a + b, 0) / plotVals.length) : null;
+ const peakPlot = plotVals.length ? Math.max(...plotVals) : null;
+ const peakAt = peakPlot != null ? analyzedPoints.find((p) => p.plot === peakPlot)?.label : '';
+ const protagonist = aggregate?.protagonist || null;
+ const supportingCount = aggregate?.supportingArcs?.length || 0;
+ const readerEmotion = dominant(analyzedPoints.map((p) => p.primaryEmotion));
return (
<section className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">
<div className="flex items-center justify-between gap-3">
<div>
- <h2 className="text-xs uppercase tracking-wider text-gray-500">Editorial roadmap</h2>
- <p className="text-[11px] text-gray-600">{seasonCount} volumes, {issueCount} issues</p>
+ <h2 className="text-xs uppercase tracking-wider text-gray-500 flex items-center gap-1.5">
+ Editorial roadmap
+ <Info
+ size={12}
+ className="text-gray-600"
+ title="Plot = narrative tension (stakes/pace). Character = how far the protagonist's arc advances. Reader = the reader's emotional journey (low = bleak, high = joyful). All three are read from each issue's actual content by an LLM."
+ />
+ </h2>
+ <p className="text-[11px] text-gray-600">
+ {seasonCount} volume{seasonCount === 1 ? '' : 's'}, {issueCount} issue{issueCount === 1 ? '' : 's'}
+ {' · '}
+ <span className={coverage.stale ? 'text-port-warning' : ''}>
+ {coverage.analyzed}/{coverage.total} analyzed{coverage.stale ? ` · ${coverage.stale} stale` : ''}
+ </span>
+ </p>
</div>
<ChartSpline size={18} className="text-port-accent" />
</div>
+
<div className="h-48 rounded border border-port-border bg-port-bg/70 p-3">
- {arcReady ? (
- <ArcRoadmapChart points={points} />
+ {loading ? (
+ <div className="h-full flex items-center justify-center text-xs text-gray-500">
+ <Loader2 size={14} className="animate-spin mr-1.5" /> Loading roadmap…
+ </div>
+ ) : hasData ? (
+ <ArcRoadmapChart points={analyzedPoints} />
) : (
- <div className="h-full flex items-center justify-center text-xs text-gray-500 italic">
- Generate the arc to populate the roadmap.
+ <div className="h-full flex flex-col items-center justify-center text-center gap-2 px-3">
+ <p className="text-xs text-gray-500 italic">
+ {coverage.withContent === 0
+ ? 'No drafted content yet — write or generate prose/scripts, then run analysis.'
+ : 'Not analyzed yet. Run the reader analysis to map plot, character, and reader emotion from the actual content.'}
+ </p>
</div>
)}
</div>
+
<div className="grid grid-cols-3 gap-2">
- <RoadmapMetric label="Plot" value={points.length ? `${Math.round(points[points.length - 1].plot)}%` : 'Pending'} tone="text-port-accent" />
- <RoadmapMetric label="Character" value={series.arc?.protagonistArc ? 'Mapped' : 'Pending'} tone="text-emerald-300" />
- <RoadmapMetric label="Reader" value="Draft eval pending" tone="text-amber-300" />
+ <RoadmapMetric
+ label="Plot"
+ value={avgPlot != null ? `avg ${avgPlot}` : 'Run analysis'}
+ sub={peakPlot != null ? `peak ${peakPlot}${peakAt ? ` @ ${peakAt}` : ''}` : 'narrative tension'}
+ tone="text-port-accent"
+ title="Narrative tension across analyzed issues (0–100): stakes, danger, pace."
+ />
+ <RoadmapMetric
+ label="Character"
+ value={protagonist ? protagonist.name : 'Run analysis'}
+ sub={protagonist ? `${protagonist.arcDirection || 'arc'}${supportingCount ? ` · +${supportingCount} arc${supportingCount === 1 ? '' : 's'}` : ''}` : 'protagonist arc'}
+ tone="text-emerald-300"
+ title="The detected protagonist and arc direction, plus how many supporting characters have arcs."
+ />
+ <RoadmapMetric
+ label="Reader"
+ value={readerEmotion || 'Run analysis'}
+ sub={hasData ? 'dominant emotion' : 'emotional journey'}
+ tone="text-amber-300"
+ title="The reader's emotional journey, read section-by-section from the content. Open the reader map for the full log."
+ />
+ </div>
+
+ <div className="flex items-center justify-between gap-2">
+ {running ? (
+ <button
+ type="button"
+ onClick={cancelAnalysis}
+ className="inline-flex items-center gap-1.5 text-xs px-2.5 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>
+ ) : (
+ <button
+ type="button"
+ onClick={startAnalysis}
+ disabled={starting || coverage.withContent === 0}
+ className="inline-flex items-center gap-1.5 text-xs px-2.5 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"
+ title={coverage.withContent === 0 ? 'No drafted content to analyze yet' : 'Run an LLM pass over each issue to map reader emotion, plot tension, and character arcs'}
+ >
+ {starting ? <Loader2 size={13} className="animate-spin" /> : <Sparkles size={13} />}
+ {coverage.analyzed > 0 ? 'Re-run reader map' : 'Interpret reader map'}
+ </button>
+ )}
+ <Link
+ to={`/pipeline/series/${series.id}/roadmap`}
+ className="text-xs text-gray-400 hover:text-port-accent underline-offset-2 hover:underline"
+ >
+ View reader map →
+ </Link>
</div>
</section>
);
}
-function RoadmapMetric({ label, value, tone }) {
+function RoadmapMetric({ label, value, sub, tone, title }) {
return (
- <div className="rounded border border-port-border bg-port-bg/60 px-2 py-2 min-w-0">
+ <div className="rounded border border-port-border bg-port-bg/60 px-2 py-2 min-w-0" title={title}>
<div className="text-[10px] uppercase tracking-wider text-gray-500">{label}</div>
<div className={`mt-1 text-xs font-medium truncate ${tone}`}>{value}</div>
+ {sub ? <div className="text-[10px] text-gray-600 truncate">{sub}</div> : null}
</div>
);
}
-function buildRoadmapPoints(issues) {
- const ordered = [...issues].sort((a, b) => (a.number || 0) - (b.number || 0));
- const count = Math.max(ordered.length, 1);
- return ordered.map((issue, idx) => {
- const t = count === 1 ? 1 : idx / (count - 1);
- const role = String(issue.arcRole || '').toLowerCase();
- const roleBoost = role.includes('finale') ? 18
- : role.includes('midpoint') ? 12
- : role.includes('pilot') ? -4
- : role.includes('climax') ? 16
- : 0;
- const statusBoost = issue.status === 'shipped' ? 5 : issue.status === 'needs-review' ? -6 : 0;
- return {
- label: issue.arcPosition ? `E${issue.arcPosition}` : `#${issue.number || idx + 1}`,
- title: issue.title || 'Untitled',
- plot: Math.max(8, Math.min(98, 18 + (t * 68) + (Math.sin(t * Math.PI * 2) * 7) + roleBoost + statusBoost)),
- character: Math.max(10, Math.min(94, 24 + (t * 58) + (Math.sin((t + 0.18) * Math.PI) * 12))),
- reader: Math.max(12, Math.min(92, 34 + (Math.sin((t * 2.5 + 0.2) * Math.PI) * 22) + (t * 18))),
- };
- });
-}
-
-function ArcRoadmapChart({ points }) {
+// Real roadmap chart. `points` are the analyzed issues only, each carrying a
+// `frac` (0..1) x-position within the full ordered issue list so spacing
+// reflects arc position; unanalyzed gaps are skipped (the line bridges them).
+export function ArcRoadmapChart({ points }) {
const width = 320;
const height = 132;
- const chartPoints = points.length > 0 ? points : [{ plot: 0, character: 0, reader: 0, label: '' }];
- const toPolyline = (key) => chartPoints.map((point, idx) => {
- const x = chartPoints.length === 1 ? width : (idx / (chartPoints.length - 1)) * width;
+ const toPolyline = (key) => points.map((point) => {
+ const x = point.frac * width;
const y = height - ((point[key] / 100) * height);
return `${x.toFixed(1)},${y.toFixed(1)}`;
}).join(' ');
return (
<div className="h-full grid grid-rows-[1fr_auto] gap-2">
- <svg viewBox={`0 0 ${width} ${height}`} className="w-full h-full overflow-visible" role="img" aria-label="Arc roadmap chart">
+ <svg viewBox={`0 0 ${width} ${height}`} className="w-full h-full overflow-visible" role="img" aria-label="Editorial roadmap chart">
{[0.25, 0.5, 0.75].map((n) => (
<line key={n} x1="0" x2={width} y1={height * n} y2={height * n} stroke="rgba(148,163,184,0.16)" strokeWidth="1" />
))}
<polyline points={toPolyline('plot')} fill="none" stroke="rgb(96,165,250)" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
<polyline points={toPolyline('character')} fill="none" stroke="rgb(110,231,183)" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
- <polyline points={toPolyline('reader')} fill="none" stroke="rgb(251,191,36)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" strokeDasharray="6 5" opacity="0.75" />
- {chartPoints.map((point, idx) => {
- const x = chartPoints.length === 1 ? width : (idx / (chartPoints.length - 1)) * width;
- return (
- <circle key={`${point.label}-${idx}`} cx={x} cy={height - ((point.plot / 100) * height)} r="2.5" fill="rgb(96,165,250)">
- <title>{point.label}: {point.title}</title>
- </circle>
- );
- })}
+ <polyline points={toPolyline('reader')} fill="none" stroke="rgb(251,191,36)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" strokeDasharray="6 5" opacity="0.85" />
+ {points.map((point, idx) => (
+ <circle key={`${point.label}-${idx}`} cx={point.frac * width} cy={height - ((point.plot / 100) * height)} r={point.stale ? 3 : 2.5} fill={point.stale ? 'rgb(245,158,11)' : 'rgb(96,165,250)'} stroke={point.stale ? 'rgb(245,158,11)' : 'none'}>
+ <title>{point.label}: {point.title}{point.primaryEmotion ? ` — reader feels ${point.primaryEmotion}` : ''}{point.stale ? ' (stale — content changed since analysis)' : ''}</title>
+ </circle>
+ ))}
</svg>
<div className="flex items-center gap-3 text-[10px] uppercase tracking-wider text-gray-500">
<span className="inline-flex items-center gap-1"><span className="w-3 h-0.5 bg-blue-400 rounded" /> Plot</span>
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 1b7c149fc5..62416dd272 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -34,7 +34,9 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useMediaJobProgress` | Live progress for a single `mediaJobQueue` job. | Subscribing to a known media-job id. |
| `useOpenClawStream` | OpenClaw SSE chat stream. | OpenClaw file-browser chat surface only. |
| `usePipelineAutoRunProgress` | Auto-run-text SSE for a pipeline issue. | Pipeline auto-run UI surfaces only. |
+| `usePipelineEditorialProgress` | Series editorial reader-emotion batch SSE. | Editorial Roadmap analysis UI only. |
| `usePipelineVolumeBeatsProgress` | Volume beat-sheet SSE. | Volume beat-sheet UI only. |
+| `useSeriesEditorial` | Editorial-roadmap aggregate + batch lifecycle (load, re-attach, SSE, start/cancel, reload). | Any view of the editorial roadmap (panel or Reader Map page). |
## Media (annotations, completion, attachments)
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 23ea545dd0..2a3c765a05 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -43,7 +43,9 @@ export * from './useSharingNotifications.js';
export * from './useImageGenProgress.js';
export * from './useOpenClawStream.js';
export * from './usePipelineAutoRunProgress.js';
+export * from './usePipelineEditorialProgress.js';
export * from './usePipelineVolumeBeatsProgress.js';
+export * from './useSeriesEditorial.js';
export * from './useSseProgress.js';
// === Media (annotations, completion, attachments) ===
diff --git a/client/src/hooks/usePipelineEditorialProgress.js b/client/src/hooks/usePipelineEditorialProgress.js
new file mode 100644
index 0000000000..040f272099
--- /dev/null
+++ b/client/src/hooks/usePipelineEditorialProgress.js
@@ -0,0 +1,12 @@
+import { pipelineEditorialSseUrl } from '../services/api';
+import { useSseProgress } from './useSseProgress';
+
+/**
+ * Subscribe to the series editorial-analysis batch SSE stream. Frame shapes are
+ * documented in server/services/pipeline/editorialAnalysisRunner.js
+ * (start / issue:start / issue:complete / issue:error / complete / canceled / error).
+ */
+export function usePipelineEditorialProgress(seriesId, { enabled = true } = {}) {
+ const url = seriesId ? pipelineEditorialSseUrl(seriesId) : null;
+ return useSseProgress(url, { enabled });
+}
diff --git a/client/src/hooks/useSeriesEditorial.js b/client/src/hooks/useSeriesEditorial.js
new file mode 100644
index 0000000000..bf7f5292ea
--- /dev/null
+++ b/client/src/hooks/useSeriesEditorial.js
@@ -0,0 +1,91 @@
+import { useCallback, useEffect, useState } from 'react';
+import {
+ getSeriesEditorial, getSeriesEditorialStatus,
+ analyzeSeriesEditorial, cancelSeriesEditorial,
+} from '../services/api';
+import toast from '../components/ui/Toast';
+import { projectAnalyzedPoints } from '../lib/editorialRoadmap';
+import { usePipelineEditorialProgress } from './usePipelineEditorialProgress';
+
+const EMPTY_COVERAGE = { analyzed: 0, total: 0, withContent: 0, stale: 0, noContent: 0 };
+
+/**
+ * Owns the editorial-roadmap aggregate for a series plus the batch-analysis
+ * lifecycle: initial load, re-attach to an in-flight run on (re)mount, SSE
+ * progress, start/cancel, and a reload when the batch ends. Shared by the
+ * EditorialRoadmapPanel (Series page) and the Reader Map detail page so the two
+ * views can't drift (e.g. when to reload, how points are projected).
+ *
+ * Returns the aggregate + derived `coverage`/`roadmap`/`analyzedPoints`, the
+ * run state (`running`/`starting`/`progressText`), and `reload`/`startAnalysis`
+ * /`cancelAnalysis`. Callers render however they like on top.
+ */
+export function useSeriesEditorial(seriesId) {
+ const [aggregate, setAggregate] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [analysisEnabled, setAnalysisEnabled] = useState(false);
+ const [starting, setStarting] = useState(false);
+
+ const reload = useCallback(() => {
+ if (!seriesId) return Promise.resolve();
+ return getSeriesEditorial(seriesId, { silent: true })
+ .then((data) => setAggregate(data))
+ .catch(() => setAggregate(null));
+ }, [seriesId]);
+
+ // Initial load + re-attach to a batch still running from a prior visit so its
+ // completion still refreshes this view.
+ useEffect(() => {
+ if (!seriesId) { setLoading(false); return; }
+ setLoading(true);
+ reload().finally(() => setLoading(false));
+ getSeriesEditorialStatus(seriesId, { silent: true })
+ .then((s) => { if (s?.active) setAnalysisEnabled(true); })
+ .catch(() => {});
+ }, [seriesId, reload]);
+
+ // Reload when the batch ends. `closed` covers a terminal frame OR a
+ // dropped/404 stream (fast batch pruned before we attached), so the UI never
+ // hangs in "Analyzing…" waiting for a frame that will never arrive.
+ const { latest, closed } = usePipelineEditorialProgress(seriesId, { enabled: analysisEnabled });
+ useEffect(() => {
+ if (closed && analysisEnabled) {
+ setAnalysisEnabled(false);
+ reload();
+ }
+ }, [closed, analysisEnabled, reload]);
+
+ const startAnalysis = useCallback(() => {
+ if (!seriesId) return;
+ setStarting(true);
+ analyzeSeriesEditorial(seriesId, {}, { silent: true })
+ .then(() => setAnalysisEnabled(true))
+ .catch((err) => toast.error(err?.message || 'Failed to start analysis'))
+ .finally(() => setStarting(false));
+ }, [seriesId]);
+
+ const cancelAnalysis = useCallback(() => {
+ if (seriesId) cancelSeriesEditorial(seriesId).catch(() => {});
+ setAnalysisEnabled(false);
+ }, [seriesId]);
+
+ const coverage = aggregate?.coverage || EMPTY_COVERAGE;
+ const roadmap = aggregate?.roadmap || [];
+ const analyzedPoints = projectAnalyzedPoints(roadmap);
+ const running = analysisEnabled;
+ const progressText = running && latest?.total ? `Analyzing ${latest.done || 0}/${latest.total}…` : null;
+
+ return {
+ aggregate,
+ loading,
+ reload,
+ running,
+ starting,
+ startAnalysis,
+ cancelAnalysis,
+ coverage,
+ roadmap,
+ analyzedPoints,
+ progressText,
+ };
+}
diff --git a/client/src/hooks/useSseProgress.js b/client/src/hooks/useSseProgress.js
index 8613e98b0d..614893c37e 100644
--- a/client/src/hooks/useSseProgress.js
+++ b/client/src/hooks/useSseProgress.js
@@ -16,6 +16,12 @@ export function useSseProgress(url, { enabled = true } = {}) {
const [frames, setFrames] = useState([]);
const [latest, setLatest] = useState(null);
const [isOpen, setIsOpen] = useState(false);
+ // `closed` flips true when the stream ends for ANY reason — a terminal frame
+ // OR a connection failure/404 (e.g. the server pruned a fast-completing job
+ // before we attached). Consumers that gate UI on a run being "in flight" use
+ // this to recover instead of hanging forever waiting for a terminal frame
+ // that will never arrive. Reset to false on every (re)subscribe.
+ const [closed, setClosed] = useState(false);
const esRef = useRef(null);
useEffect(() => {
@@ -23,6 +29,7 @@ export function useSseProgress(url, { enabled = true } = {}) {
setFrames([]);
setLatest(null);
setIsOpen(false);
+ setClosed(false);
const es = new EventSource(url);
esRef.current = es;
@@ -39,10 +46,18 @@ export function useSseProgress(url, { enabled = true } = {}) {
setLatest(data);
if (TERMINAL_TYPES.has(data?.type)) {
es.close();
+ setClosed(true);
}
};
es.onerror = () => {
- if (es.readyState === EventSource.CLOSED) setIsOpen(false);
+ // EventSource fails (no auto-retry) on a non-2xx / non-event-stream
+ // response — readyState CLOSED. Surface that as a terminal close so the
+ // consumer stops waiting; transient errors (readyState CONNECTING) are
+ // left alone so the browser's own retry can recover.
+ if (es.readyState === EventSource.CLOSED) {
+ setIsOpen(false);
+ setClosed(true);
+ }
};
return () => {
@@ -51,5 +66,5 @@ export function useSseProgress(url, { enabled = true } = {}) {
};
}, [url, enabled]);
- return { frames, latest, isOpen, close: () => esRef.current?.close() };
+ return { frames, latest, isOpen, closed, close: () => esRef.current?.close() };
}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 3f2659f0bf..a0a705483f 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -31,6 +31,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `sheetPointers.js` | Mirror of the character-sheet pointer helpers from `server/lib/storyBible.js`. `LEGACY_SHEET_VARIANT_ID` + `readSheetPointer` / `listSheetPointers` / `applySheetPointer` for traversing both the legacy `referenceSheetImageRef` field and the `referenceSheets` map. |
| `universeStylePreset.js` | Build the client-side style preset that `composeStyledPrompt` layers on top. |
| `bibleLimits.js` | Mirror of `server/lib/storyBible.js` `BIBLE_LIMITS`. |
+| `editorialRoadmap.js` | `projectAnalyzedPoints` (aggregate roadmap → analyzed chart points with arc-position `frac`) + `dominant` (most-frequent string). Shared by EditorialRoadmapPanel and the Reader Map page. |
| `imageCleaners.js` | Mirror of `resolveCleanersFromConfig` from `server/lib/imageClean.js`. Reads `{cleanC2PA, denoise}` off a per-mode settings record; `cleanC2PA` defaults on, `denoise` defaults off (legacy `autoClean: true` no longer silently enables denoise). |
| `runnerFamilies.js` | Mirror of `server/lib/runners.js`. |
| `issueLength.js` | Mirror of `server/lib/issueLength.js`. |
diff --git a/client/src/lib/editorialRoadmap.js b/client/src/lib/editorialRoadmap.js
new file mode 100644
index 0000000000..06613b34bc
--- /dev/null
+++ b/client/src/lib/editorialRoadmap.js
@@ -0,0 +1,29 @@
+// Pure helpers for the editorial reader-emotion roadmap — shared by the
+// EditorialRoadmapPanel (Series page) and the Reader Map detail page so the
+// chart math and dominant-emotion logic live in exactly one place.
+
+// Most frequent non-empty string in a list (e.g. the dominant reader emotion
+// across analyzed issues). Tie-break is first-to-reach-the-max by insertion
+// order, so the result is deterministic for a given input order.
+export function dominant(values = []) {
+ const counts = new Map();
+ for (const v of values) {
+ if (!v) continue;
+ counts.set(v, (counts.get(v) || 0) + 1);
+ }
+ let best = '';
+ let bestN = 0;
+ for (const [v, n] of counts) if (n > bestN) { best = v; bestN = n; }
+ return best;
+}
+
+// Project the aggregate roadmap into the analyzed-only points the chart draws.
+// Each point's `frac` (0..1) is its position within the FULL ordered issue list
+// so the x-axis reflects arc position; unanalyzed gaps are skipped and the line
+// simply bridges them. `plot != null` (not truthiness) keeps a legitimate 0.
+export function projectAnalyzedPoints(roadmap = []) {
+ const total = roadmap.length;
+ return roadmap
+ .map((r, i) => ({ ...r, frac: total > 1 ? i / (total - 1) : 1 }))
+ .filter((r) => r.analyzed && r.plot != null);
+}
diff --git a/client/src/lib/editorialRoadmap.test.js b/client/src/lib/editorialRoadmap.test.js
new file mode 100644
index 0000000000..87e0ac50a2
--- /dev/null
+++ b/client/src/lib/editorialRoadmap.test.js
@@ -0,0 +1,51 @@
+import { describe, it, expect } from 'vitest';
+import { dominant, projectAnalyzedPoints } from './editorialRoadmap.js';
+
+describe('dominant', () => {
+ it('returns the most frequent non-empty string', () => {
+ expect(dominant(['dread', 'dread', 'hope'])).toBe('dread');
+ });
+
+ it('ignores empty/falsy values and returns "" for an empty list', () => {
+ expect(dominant(['', null, undefined])).toBe('');
+ expect(dominant([])).toBe('');
+ });
+
+ it('breaks ties toward the first to reach the max (insertion order)', () => {
+ // hope and dread both appear twice; hope reaches 2 first → wins deterministically.
+ expect(dominant(['hope', 'dread', 'hope', 'dread'])).toBe('hope');
+ });
+});
+
+describe('projectAnalyzedPoints', () => {
+ it('keeps only analyzed points with a non-null plot (0 is valid)', () => {
+ const roadmap = [
+ { issueId: 'a', analyzed: true, plot: 0 },
+ { issueId: 'b', analyzed: false, plot: null },
+ { issueId: 'c', analyzed: true, plot: 80 },
+ ];
+ const pts = projectAnalyzedPoints(roadmap);
+ expect(pts.map((p) => p.issueId)).toEqual(['a', 'c']);
+ });
+
+ it('positions each point by its index in the FULL roadmap (frac), skipping gaps', () => {
+ const roadmap = [
+ { issueId: 'a', analyzed: true, plot: 10 }, // index 0 → frac 0
+ { issueId: 'b', analyzed: false, plot: null }, // gap
+ { issueId: 'c', analyzed: true, plot: 30 }, // index 2 → frac 1
+ ];
+ const pts = projectAnalyzedPoints(roadmap);
+ expect(pts).toHaveLength(2);
+ expect(pts[0].frac).toBe(0);
+ expect(pts[1].frac).toBe(1);
+ });
+
+ it('places a single analyzed point at frac 1 (no divide-by-zero)', () => {
+ expect(projectAnalyzedPoints([{ analyzed: true, plot: 50 }])[0].frac).toBe(1);
+ });
+
+ it('returns [] for an empty or missing roadmap', () => {
+ expect(projectAnalyzedPoints([])).toEqual([]);
+ expect(projectAnalyzedPoints()).toEqual([]);
+ });
+});
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 58d502c653..35c3511ed6 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -13,6 +13,7 @@ export * from './universeStylePreset.js';
// === Pipeline / image-gen defaults ===
export * from './bibleLimits.js';
+export * from './editorialRoadmap.js';
export * from './imageCleaners.js';
export * from './imageGenBackends.js';
export * from './imageGenDefaults.js';
diff --git a/client/src/pages/PipelineSeriesRoadmap.jsx b/client/src/pages/PipelineSeriesRoadmap.jsx
new file mode 100644
index 0000000000..a16c708388
--- /dev/null
+++ b/client/src/pages/PipelineSeriesRoadmap.jsx
@@ -0,0 +1,318 @@
+/**
+ * Pipeline — Series Reader Map (Editorial Roadmap detail).
+ *
+ * Deep-linkable view (`/pipeline/series/:seriesId/roadmap`) of the editorial
+ * analysis the EditorialRoadmapPanel summarizes: the aggregate Plot / Character
+ * / Reader chart, the detected protagonist + supporting character arcs, and a
+ * per-issue, section-by-section log of the reader's emotional journey.
+ *
+ * Data comes from GET /pipeline/series/:id/editorial (aggregate) and, lazily on
+ * expand, GET /pipeline/issues/:id/editorial (full per-issue snapshot). Analysis
+ * is kicked off via the same batch SSE runner the panel uses.
+ */
+
+import { useCallback, useEffect, useState } from 'react';
+import { Link, useParams, useNavigate } from 'react-router-dom';
+import {
+ ArrowLeft, Loader2, Sparkles, ChevronRight, ChevronDown, AlertTriangle, Crown, ChartSpline,
+} from 'lucide-react';
+import toast from '../components/ui/Toast';
+import { ArcRoadmapChart } from '../components/pipeline/ArcCanvas';
+import {
+ getPipelineSeries, getIssueEditorial, analyzeIssueEditorial,
+} from '../services/api';
+import { useSeriesEditorial } from '../hooks/useSeriesEditorial';
+
+const DIR_TONE = {
+ rising: 'text-emerald-300',
+ falling: 'text-rose-300',
+ complex: 'text-port-accent',
+ flat: 'text-gray-400',
+};
+
+// Reader valence (−100..100) → a tone for the little valence pill.
+function valenceTone(v) {
+ if (v >= 25) return 'bg-emerald-500/20 text-emerald-300';
+ if (v <= -25) return 'bg-rose-500/20 text-rose-300';
+ return 'bg-gray-600/30 text-gray-300';
+}
+
+function MeterBar({ value, tone = 'bg-port-accent' }) {
+ const pct = Math.max(0, Math.min(100, value));
+ return (
+ <div className="h-1.5 w-full rounded-full bg-port-bg overflow-hidden">
+ <div className={`h-full rounded-full ${tone}`} style={{ width: `${pct}%` }} />
+ </div>
+ );
+}
+
+function SectionRow({ section, index }) {
+ return (
+ <li className="border border-port-border rounded p-2.5 bg-port-bg/40 space-y-1.5">
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-xs font-medium text-gray-200">{index + 1}. {section.label}</span>
+ <span className={`text-[10px] px-1.5 py-0.5 rounded ${valenceTone(section.valence)}`}>
+ {section.primaryEmotion || '—'} · {section.valence > 0 ? `+${section.valence}` : section.valence}
+ </span>
+ </div>
+ {section.excerpt ? <p className="text-[11px] text-gray-500 italic line-clamp-2">“{section.excerpt}”</p> : null}
+ <div className="flex items-center gap-2">
+ <span className="text-[10px] uppercase tracking-wider text-gray-600 w-12 shrink-0">tension</span>
+ <MeterBar value={section.tension} tone="bg-port-accent" />
+ <span className="text-[10px] text-gray-500 w-7 text-right">{section.tension}</span>
+ </div>
+ {section.note ? <p className="text-[11px] text-gray-400">{section.note}</p> : null}
+ </li>
+ );
+}
+
+function IssueRow({ entry, onAnalyze, analyzing }) {
+ const [open, setOpen] = useState(false);
+ const [detail, setDetail] = useState(null);
+ const [loadingDetail, setLoadingDetail] = useState(false);
+
+ // Fetch the section detail when the row is open, and REFETCH when the
+ // snapshot identity (`analyzedAt`) changes — so a re-run while the row is
+ // open replaces the cached log instead of showing the pre-re-run analysis.
+ useEffect(() => {
+ if (!open || !entry.analyzed) return undefined;
+ let canceled = false;
+ setLoadingDetail(true);
+ getIssueEditorial(entry.issueId, { silent: true })
+ .then((d) => { if (!canceled) setDetail(d && d.status !== 'none' ? d : null); })
+ .catch(() => { if (!canceled) setDetail(null); })
+ .finally(() => { if (!canceled) setLoadingDetail(false); });
+ return () => { canceled = true; };
+ }, [open, entry.analyzed, entry.analyzedAt, entry.issueId]);
+
+ const toggle = () => setOpen((o) => !o);
+
+ return (
+ <li className="border border-port-border rounded-lg bg-port-card">
+ <div className="flex items-center gap-2 p-2.5">
+ <button type="button" onClick={toggle} className="flex items-center gap-2 flex-1 min-w-0 text-left" disabled={!entry.analyzed}>
+ {entry.analyzed ? (open ? <ChevronDown size={14} className="text-gray-500 shrink-0" /> : <ChevronRight size={14} className="text-gray-500 shrink-0" />) : <span className="w-3.5 shrink-0" />}
+ <span className="text-[10px] font-mono text-gray-500 shrink-0">{entry.label}</span>
+ <span className="text-sm text-gray-200 truncate">{entry.title || 'Untitled'}</span>
+ {entry.stale ? <AlertTriangle size={12} className="text-port-warning shrink-0" title="Content changed since this was analyzed — re-run" /> : null}
+ </button>
+ {entry.analyzed ? (
+ <div className="flex items-center gap-3 shrink-0">
+ <span className="text-[10px] text-gray-500" title="Plot tension / Character progress / Reader valence">
+ P{entry.plot} · C{entry.character} · R{entry.reader}
+ </span>
+ {entry.primaryEmotion ? <span className="text-[10px] text-amber-300">{entry.primaryEmotion}</span> : null}
+ </div>
+ ) : (
+ <span className="text-[10px] text-gray-600 shrink-0">{entry.hasContent ? 'not analyzed' : 'no content'}</span>
+ )}
+ {entry.hasContent ? (
+ <button
+ type="button"
+ onClick={() => onAnalyze(entry.issueId)}
+ disabled={analyzing}
+ className="text-[10px] px-1.5 py-1 rounded border border-port-border text-gray-400 hover:text-port-accent hover:border-port-accent/40 disabled:opacity-40 shrink-0"
+ title={entry.analyzed ? 'Re-analyze this issue' : 'Analyze this issue'}
+ >
+ {analyzing ? <Loader2 size={11} className="animate-spin" /> : (entry.analyzed ? 'Re-run' : 'Analyze')}
+ </button>
+ ) : null}
+ </div>
+ {open && entry.analyzed ? (
+ <div className="border-t border-port-border p-2.5">
+ {loadingDetail ? (
+ <div className="text-xs text-gray-500 flex items-center gap-1.5"><Loader2 size={12} className="animate-spin" /> Loading…</div>
+ ) : detail?.sections?.length ? (
+ <ul className="space-y-1.5">
+ {detail.sections.map((s, i) => <SectionRow key={i} section={s} index={i} />)}
+ </ul>
+ ) : (
+ <p className="text-xs text-gray-500 italic">No section detail available.</p>
+ )}
+ </div>
+ ) : null}
+ </li>
+ );
+}
+
+function CharacterArcs({ protagonist, supportingArcs, protagonistArcText }) {
+ if (!protagonist && (!supportingArcs || supportingArcs.length === 0)) {
+ return <p className="text-xs text-gray-500 italic">No character arcs detected yet — run the analysis.</p>;
+ }
+ return (
+ <div className="space-y-2.5">
+ {protagonist ? (
+ <div className="border border-emerald-500/30 bg-emerald-500/5 rounded-lg p-3">
+ <div className="flex items-center gap-2">
+ <Crown size={14} className="text-emerald-300" />
+ <span className="text-sm font-medium text-emerald-200">{protagonist.name}</span>
+ <span className="text-[10px] uppercase tracking-wider text-emerald-400/70">protagonist · {protagonist.arcDirection}</span>
+ <span className="text-[10px] text-gray-500 ml-auto">{protagonist.issueCount} issue{protagonist.issueCount === 1 ? '' : 's'}</span>
+ </div>
+ {protagonist.arcSummary ? <p className="mt-1.5 text-xs text-gray-300">{protagonist.arcSummary}</p> : null}
+ {protagonistArcText ? <p className="mt-1.5 text-[11px] text-gray-500"><span className="text-gray-600">Intended arc:</span> {protagonistArcText}</p> : null}
+ </div>
+ ) : null}
+ {supportingArcs && supportingArcs.length ? (
+ <div>
+ <h3 className="text-[10px] uppercase tracking-wider text-gray-500 mb-1.5">Other characters with arcs</h3>
+ <ul className="space-y-1.5">
+ {supportingArcs.map((c) => (
+ <li key={c.name} className="border border-port-border rounded p-2 bg-port-bg/40">
+ <div className="flex items-center gap-2">
+ <span className="text-xs font-medium text-gray-200">{c.name}</span>
+ <span className={`text-[10px] ${DIR_TONE[c.arcDirection] || 'text-gray-400'}`}>{c.arcDirection}</span>
+ {c.role ? <span className="text-[10px] text-gray-600">{c.role}</span> : null}
+ <span className="text-[10px] text-gray-600 ml-auto">{c.issueCount} issue{c.issueCount === 1 ? '' : 's'}</span>
+ </div>
+ {c.arcSummary ? <p className="mt-1 text-[11px] text-gray-400">{c.arcSummary}</p> : null}
+ </li>
+ ))}
+ </ul>
+ </div>
+ ) : (
+ <p className="text-xs text-gray-500 italic">No supporting characters with a distinct arc detected.</p>
+ )}
+ </div>
+ );
+}
+
+export default function PipelineSeriesRoadmap() {
+ const { seriesId } = useParams();
+ const navigate = useNavigate();
+ const [series, setSeries] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [perIssueBusy, setPerIssueBusy] = useState(null); // issueId currently analyzing solo
+
+ // Shared editorial-roadmap state + batch lifecycle (load, re-attach, SSE,
+ // start/cancel, reload). The EditorialRoadmapPanel uses the same hook.
+ const {
+ aggregate, reload, running, starting,
+ startAnalysis, cancelAnalysis, coverage, roadmap, analyzedPoints, progressText,
+ } = useSeriesEditorial(seriesId);
+
+ // The series record (title) is this page's own concern; an error here means
+ // the series doesn't exist, so bounce back to the index.
+ useEffect(() => {
+ let canceled = false;
+ setLoading(true);
+ getPipelineSeries(seriesId)
+ .then((s) => { if (!canceled) setSeries(s); })
+ .catch((err) => {
+ if (canceled) return;
+ toast.error(err.message || 'Failed to load series');
+ navigate('/pipeline');
+ })
+ .finally(() => { if (!canceled) setLoading(false); });
+ return () => { canceled = true; };
+ }, [seriesId, navigate]);
+
+ const analyzeOne = useCallback((issueId) => {
+ setPerIssueBusy(issueId);
+ analyzeIssueEditorial(issueId, { force: true }, { silent: true })
+ .then(() => reload())
+ .catch((err) => toast.error(err?.message || 'Analysis failed'))
+ .finally(() => setPerIssueBusy(null));
+ }, [reload]);
+
+ if (loading) {
+ return (
+ <div className="h-full flex items-center justify-center text-gray-500">
+ <Loader2 size={18} className="animate-spin mr-2" /> Loading reader map…
+ </div>
+ );
+ }
+
+ // This route matches Layout's full-width list (startsWith('/pipeline/series/')),
+ // so it gets a bare overflow-hidden <main> — the page owns its own scroll +
+ // padding, matching the standard padded page (overflow-auto p-4 md:p-6).
+ return (
+ <div className="h-full overflow-y-auto p-4 md:p-6 space-y-5">
+ <div className="flex items-center gap-3">
+ <Link to={`/pipeline/series/${seriesId}`} className="text-gray-400 hover:text-port-accent" title="Back to series">
+ <ArrowLeft size={18} />
+ </Link>
+ <div className="min-w-0">
+ <h1 className="text-lg font-semibold text-white flex items-center gap-2">
+ <ChartSpline size={18} className="text-port-accent" /> Reader Map
+ </h1>
+ <p className="text-xs text-gray-500 truncate">{series?.name}</p>
+ </div>
+ <div className="ml-auto flex items-center gap-2">
+ {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>
+ ) : (
+ <button
+ type="button"
+ onClick={startAnalysis}
+ disabled={starting || coverage.withContent === 0}
+ 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"
+ title={coverage.withContent === 0 ? 'No drafted content to analyze yet' : 'Run an LLM pass over each issue with content'}
+ >
+ {starting ? <Loader2 size={13} className="animate-spin" /> : <Sparkles size={13} />}
+ {coverage.analyzed > 0 ? 'Re-run all' : 'Run analysis'}
+ </button>
+ )}
+ </div>
+ </div>
+
+ <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">
+ <h2 className="text-xs uppercase tracking-wider text-gray-500">Arc curves</h2>
+ <p className="text-[11px] text-gray-600">
+ <span className={coverage.stale ? 'text-port-warning' : ''}>
+ {coverage.analyzed}/{coverage.total} analyzed{coverage.stale ? ` · ${coverage.stale} stale` : ''}
+ </span>
+ </p>
+ </div>
+ <div className="h-64 rounded border border-port-border bg-port-bg/70 p-3">
+ {analyzedPoints.length ? (
+ <ArcRoadmapChart points={analyzedPoints} />
+ ) : (
+ <div className="h-full flex items-center justify-center text-center text-xs text-gray-500 italic px-4">
+ {coverage.withContent === 0
+ ? 'No drafted content yet. Write or generate prose/scripts, then run the analysis.'
+ : 'Not analyzed yet. Run the analysis to map the reader’s journey from the content.'}
+ </div>
+ )}
+ </div>
+ <p className="text-[11px] text-gray-600">
+ <span className="text-port-accent">Plot</span> = narrative tension ·{' '}
+ <span className="text-emerald-300">Character</span> = protagonist arc progress ·{' '}
+ <span className="text-amber-300">Reader</span> = emotional journey (0 = bleak, 100 = joyful)
+ </p>
+ </section>
+
+ <section className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">
+ <h2 className="text-xs uppercase tracking-wider text-gray-500">Character arcs</h2>
+ <CharacterArcs
+ protagonist={aggregate?.protagonist}
+ supportingArcs={aggregate?.supportingArcs}
+ protagonistArcText={aggregate?.protagonistArcText}
+ />
+ </section>
+ </div>
+
+ <section className="space-y-2">
+ <h2 className="text-xs uppercase tracking-wider text-gray-500">Per-issue reader journey</h2>
+ {roadmap.length ? (
+ <ul className="space-y-2">
+ {roadmap.map((entry) => (
+ <IssueRow
+ key={entry.issueId}
+ entry={entry}
+ onAnalyze={analyzeOne}
+ analyzing={perIssueBusy === entry.issueId || running}
+ />
+ ))}
+ </ul>
+ ) : (
+ <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 5376ed80b4..0c310393c8 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -411,6 +411,44 @@ export const cancelPipelineAutoRunText = (issueId) =>
export const pipelineAutoRunSseUrl = (issueId) =>
`/api/pipeline/issues/${encodeURIComponent(issueId)}/auto-run-text/progress`;
+// ---- Editorial roadmap / reader-emotion analysis ----
+// Aggregate roadmap: { coverage, roadmap[], characters[], protagonist, supportingArcs, ... }
+export const getSeriesEditorial = (seriesId, options = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/editorial`, options);
+
+// Full per-issue snapshot: { sections[], characters[], rollup, stale, ... } or { status: 'none' }
+export const getIssueEditorial = (issueId, options = {}) =>
+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/editorial`, options);
+
+// Analyze ONE issue (synchronous; returns the finished snapshot)
+export const analyzeIssueEditorial = (issueId, opts = {}, options = {}) =>
+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/editorial/analyze`, {
+ method: 'POST',
+ body: JSON.stringify(opts),
+ ...options,
+ });
+
+// Analyze the whole series (batch). { runId, alreadyRunning, sseUrl } — subscribe
+// via pipelineEditorialSseUrl to stream per-issue progress.
+export const analyzeSeriesEditorial = (seriesId, opts = {}, options = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/editorial/analyze`, {
+ method: 'POST',
+ body: JSON.stringify(opts),
+ ...options,
+ });
+
+export const cancelSeriesEditorial = (seriesId) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/editorial/analyze/cancel`, {
+ method: 'POST',
+ });
+
+// { active: boolean } — lets a (re)mounting view re-attach to an in-flight batch.
+export const getSeriesEditorialStatus = (seriesId, options = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/editorial/analyze/status`, options);
+
+export const pipelineEditorialSseUrl = (seriesId) =>
+ `/api/pipeline/series/${encodeURIComponent(seriesId)}/editorial/analyze/progress`;
+
// ---- Audio stage ----
// Flat list of every voice the active engines expose, namespaced as
// `engine:voiceName` (e.g. `kokoro:af_bella`, `piper:lessac-medium`). The
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index fa0400ecb9..88ca23e030 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -214,6 +214,13 @@
"returnsJson": false,
"variables": []
},
+ "pipeline-editorial-analysis": {
+ "name": "Pipeline — Editorial Reader-Emotion Analysis",
+ "description": "Read one issue's reader-facing content (prose, comic script, or teleplay) and map the reader's emotional journey section by section, plus plot tension, character arcs, and protagonist detection. Feeds the series Editorial Roadmap. Runs at `heavy` tier — analyzes full issue content.",
+ "model": "heavy",
+ "returnsJson": true,
+ "variables": []
+ },
"pipeline-extract-scenes": {
"name": "Pipeline — Extract Scenes from TV Teleplay",
"description": "Parse an already-formatted TV teleplay into a structured scenes[] list (one entry per slugline) the storyboards stage can render. Defers to character / setting bibles for canonical names and slugline reuse.",
diff --git a/data.reference/prompts/stages/pipeline-editorial-analysis.md b/data.reference/prompts/stages/pipeline-editorial-analysis.md
new file mode 100644
index 0000000000..0f69425f94
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-editorial-analysis.md
@@ -0,0 +1,76 @@
+# Pipeline — Editorial Reader-Emotion Analysis
+
+You are a developmental editor mapping the **reader's emotional journey** through one issue of a serialized story, plus its plot tension and character arcs. Read the supplied content closely and return a structured analysis the writer can use to see, section by section, what a reader actually experiences.
+
+## Issue being analyzed
+
+- Series: {{series.name}}
+{{#series.logline}}- Series logline: {{series.logline}}{{/series.logline}}
+- Issue #{{issue.number}}: {{issue.title}}
+{{#issue.arcRole}}- Arc role in the series: {{issue.arcRole}}{{/issue.arcRole}}
+{{#arc.protagonistArc}}- Intended protagonist arc (series-level): {{arc.protagonistArc}}{{/arc.protagonistArc}}
+{{#arc.themesCsv}}- Series themes: {{arc.themesCsv}}{{/arc.themesCsv}}
+{{#knownProtagonist}}- Known protagonist from the series bible: {{knownProtagonist}} (confirm or correct from the text){{/knownProtagonist}}
+{{#knownCharacters}}- Known characters from the series bible: {{knownCharacters}}{{/knownCharacters}}
+
+## Content ({{format}})
+
+```
+{{content}}
+```
+
+## Task
+
+1. **Divide the content into sections** — one section per scene where scene breaks are clear (e.g. H2 `##` markers, comic page/panel breaks, teleplay scene headings). If there are no clear scene breaks, group consecutive paragraphs into 4–12 coherent beats. Label each section so a human can find it (`"Scene 3"`, `"Page 4"`, `"¶ 12–18"`).
+
+2. **For each section, judge the reader's experience** (the reader's felt response, NOT the characters' emotions):
+ - `primaryEmotion`: one lowercase word for the dominant reader feeling (e.g. `curiosity`, `dread`, `relief`, `grief`, `delight`, `tension`, `awe`, `unease`, `hope`).
+ - `emotions`: up to 3 contributing reader emotions.
+ - `tension`: 0–100, how much narrative/plot tension the reader feels here (stakes, danger, uncertainty, pace).
+ - `valence`: −100 (bleak/painful) to +100 (joyful/triumphant) — the emotional "up or down" of the moment.
+ - `excerpt`: a short verbatim quote (≤ 160 chars) anchoring the section.
+ - `note`: 1–2 sentences on what drives that reader response and any pacing concern.
+
+3. **Map character arcs.** For every character with a meaningful presence:
+ - `name`, `role` (e.g. `protagonist`, `antagonist`, `ally`, `mentor`, `minor`).
+ - `isProtagonist`: `true`, `false`, or `null` if genuinely ambiguous.
+ - `arcDirection`: `"rising"` | `"falling"` | `"flat"` | `"complex"` — how the character changes across this issue.
+ - `arcSummary`: 1–2 sentences on their transformation (or lack of one) in this issue.
+ - `beats`: array of `{ "sectionIndex": <int>, "state": "<short phrase>" }` marking where their state shifts.
+
+4. **Roll up the whole issue** for a series-level roadmap:
+ - `plotTension`: 0–100 peak/representative narrative tension of the issue.
+ - `characterProgress`: 0–100 how far the protagonist's arc advances in this issue (0 = no movement, 100 = a complete transformation).
+ - `readerValence`: −100..+100 the reader's net emotional position by the end.
+ - `readerIntensity`: 0–100 overall emotional intensity of the issue.
+ - `primaryEmotion`: the single dominant reader emotion across the issue.
+ - `peakTension`: 0–100 highest tension reached.
+ - `cliffhanger`: `true`/`false` — does it end on an unresolved hook?
+ - `oneLine`: one sentence describing the reader's journey through this issue.
+
+Be specific and ground every judgment in the text. Do not invent content that is not present.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:
+
+```json
+{
+ "sections": [
+ { "label": "string", "excerpt": "string", "primaryEmotion": "string", "emotions": ["string"], "tension": 0, "valence": 0, "note": "string" }
+ ],
+ "characters": [
+ { "name": "string", "role": "string", "isProtagonist": true, "arcDirection": "rising|falling|flat|complex", "arcSummary": "string", "beats": [ { "sectionIndex": 0, "state": "string" } ] }
+ ],
+ "rollup": {
+ "plotTension": 0,
+ "characterProgress": 0,
+ "readerValence": 0,
+ "readerIntensity": 0,
+ "primaryEmotion": "string",
+ "peakTension": 0,
+ "cliffhanger": false,
+ "oneLine": "string"
+ }
+}
+```
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index 03e781cec0..fb82c55f21 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -39,6 +39,8 @@ import * as seasonsSvc from '../services/pipeline/seasons.js';
import * as arcPlanner from '../services/pipeline/arcPlanner.js';
import { generateStage } from '../services/pipeline/textStages.js';
import * as autoRunner from '../services/pipeline/autoRunner.js';
+import * as editorialAnalysis from '../services/pipeline/editorialAnalysis.js';
+import * as editorialRunner from '../services/pipeline/editorialAnalysisRunner.js';
import * as volumeBeatsRunner from '../services/pipeline/volumeBeatsRunner.js';
import {
enqueueVisualImage,
@@ -549,6 +551,14 @@ const autoRunSchema = z.object({
modelId: z.string().trim().max(64).optional(),
});
+// Editorial reader-emotion analysis — provider/model optional (falls through
+// to the active or stage-pinned provider); `force` re-analyzes unchanged issues.
+const editorialAnalyzeSchema = z.object({
+ providerId: z.string().trim().max(80).optional(),
+ model: z.string().trim().max(200).optional(),
+ force: z.boolean().optional(),
+});
+
// Merged voice list across every supported TTS engine (Kokoro + Piper today;
// future ElevenLabs/etc. when added). Each voice is namespaced with
// `engine:voiceName` so the character voice picker shows a single flat list.
@@ -1884,4 +1894,56 @@ router.post('/issues/:id/auto-run-text/cancel', asyncHandler(async (req, res) =>
res.json({ canceled });
}));
+// =====================
+// Editorial roadmap / reader-emotion analysis
+// =====================
+
+// Aggregate roadmap (Plot / Character / Reader curves + character arcs + coverage)
+router.get('/series/:id/editorial', asyncHandler(async (req, res) => {
+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ res.json(await editorialAnalysis.getSeriesEditorial(req.params.id));
+}));
+
+// Full per-issue snapshot (section-by-section emotion log + character arcs)
+router.get('/issues/:id/editorial', asyncHandler(async (req, res) => {
+ await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const analysis = await editorialAnalysis.getIssueAnalysis(req.params.id);
+ res.json(analysis || { issueId: req.params.id, status: 'none' });
+}));
+
+// Analyze ONE issue (synchronous — returns the finished snapshot)
+router.post('/issues/:id/editorial/analyze', asyncHandler(async (req, res) => {
+ const body = validateRequest(editorialAnalyzeSchema, req.body ?? {});
+ await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });
+ res.json(await editorialAnalysis.analyzeIssue(req.params.id, body));
+}));
+
+// Analyze the whole series (batch — progress via SSE)
+router.post('/series/:id/editorial/analyze', asyncHandler(async (req, res) => {
+ const body = validateRequest(editorialAnalyzeSchema, req.body ?? {});
+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const result = await editorialRunner.startSeriesAnalysis(req.params.id, body);
+ res.json({
+ ...result,
+ sseUrl: `/api/pipeline/series/${req.params.id}/editorial/analyze/progress`,
+ });
+}));
+
+router.get('/series/:id/editorial/analyze/progress', (req, res) => {
+ const attached = editorialRunner.attachClient(req.params.id, res);
+ if (!attached) {
+ res.status(404).json({ error: 'No active editorial analysis for this series' });
+ }
+});
+
+// Lightweight probe so a (re)mounting client can re-attach to an in-flight batch.
+router.get('/series/:id/editorial/analyze/status', (req, res) => {
+ res.json({ active: editorialRunner.isSeriesAnalysisActive(req.params.id) });
+});
+
+router.post('/series/:id/editorial/analyze/cancel', asyncHandler(async (req, res) => {
+ const canceled = editorialRunner.cancelSeriesAnalysis(req.params.id);
+ res.json({ canceled });
+}));
+
export default router;
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
index 47a867d0ab..f5bb4ea5c2 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -283,6 +283,24 @@ vi.mock('../services/recordMergeAI.js', async () => {
return { ...actual, mergeFieldsWithAI: (...args) => mergeFieldsWithAIMock(...args) };
});
+// Editorial analysis — spy the service + batch runner so route tests assert
+// dispatch/validation without hitting an LLM provider or the SSE machinery.
+const getSeriesEditorialMock = vi.fn(async () => ({ coverage: { analyzed: 0, total: 0 }, roadmap: [], characters: [], protagonist: null, supportingArcs: [] }));
+const analyzeIssueMock = vi.fn(async () => ({ status: 'complete', sections: [], characters: [], rollup: {} }));
+const getIssueAnalysisMock = vi.fn(async () => null);
+vi.mock('../services/pipeline/editorialAnalysis.js', () => ({
+ getSeriesEditorial: (...a) => getSeriesEditorialMock(...a),
+ analyzeIssue: (...a) => analyzeIssueMock(...a),
+ getIssueAnalysis: (...a) => getIssueAnalysisMock(...a),
+}));
+const startSeriesAnalysisMock = vi.fn(async () => ({ runId: 'ed-run-1', alreadyRunning: false }));
+vi.mock('../services/pipeline/editorialAnalysisRunner.js', () => ({
+ startSeriesAnalysis: (...a) => startSeriesAnalysisMock(...a),
+ attachClient: vi.fn(() => false),
+ cancelSeriesAnalysis: vi.fn(() => true),
+ isSeriesAnalysisActive: vi.fn(() => false),
+}));
+
const pipelineRouter = (await import('./pipeline.js')).default;
const universeSvc = await import('../services/universeBuilder.js');
@@ -2006,3 +2024,71 @@ describe('pipeline routes', () => {
});
});
});
+
+describe('editorial roadmap routes', () => {
+ beforeEach(() => {
+ fileStore.clear();
+ uuidCounter = 0;
+ vi.clearAllMocks();
+ });
+
+ it('GET /series/:id/editorial returns 404 for an unknown series', async () => {
+ const r = await request(makeApp()).get('/api/pipeline/series/ser-nope/editorial');
+ expect(r.status).toBe(404);
+ expect(getSeriesEditorialMock).not.toHaveBeenCalled();
+ });
+
+ it('GET /series/:id/editorial dispatches the aggregate for a known series', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
+ const r = await request(app).get(`/api/pipeline/series/${ser.body.id}/editorial`);
+ expect(r.status).toBe(200);
+ expect(r.body).toHaveProperty('coverage');
+ expect(getSeriesEditorialMock).toHaveBeenCalledWith(ser.body.id);
+ });
+
+ it('POST /issues/:id/editorial/analyze validates body and dispatches', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+
+ const bad = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/editorial/analyze`)
+ .send({ force: 'yes' });
+ expect(bad.status).toBe(400);
+
+ const ok = await request(app)
+ .post(`/api/pipeline/issues/${iss.body.id}/editorial/analyze`)
+ .send({ force: true });
+ expect(ok.status).toBe(200);
+ expect(ok.body.status).toBe('complete');
+ expect(analyzeIssueMock).toHaveBeenCalledWith(iss.body.id, { force: true });
+ });
+
+ it('POST /issues/:id/editorial/analyze returns 404 for an unknown issue', async () => {
+ const r = await request(makeApp())
+ .post('/api/pipeline/issues/iss-nope/editorial/analyze')
+ .send({});
+ expect(r.status).toBe(404);
+ expect(analyzeIssueMock).not.toHaveBeenCalled();
+ });
+
+ it('POST /series/:id/editorial/analyze returns runId + sseUrl', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
+ const r = await request(app).post(`/api/pipeline/series/${ser.body.id}/editorial/analyze`).send({});
+ expect(r.status).toBe(200);
+ expect(r.body.runId).toBe('ed-run-1');
+ expect(r.body.sseUrl).toBe(`/api/pipeline/series/${ser.body.id}/editorial/analyze/progress`);
+ expect(startSeriesAnalysisMock).toHaveBeenCalled();
+ });
+
+ it('GET /issues/:id/editorial returns a none-status stub when never analyzed', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ const r = await request(app).get(`/api/pipeline/issues/${iss.body.id}/editorial`);
+ expect(r.status).toBe(200);
+ expect(r.body.status).toBe('none');
+ });
+});
diff --git a/server/services/pipeline/editorialAnalysis.js b/server/services/pipeline/editorialAnalysis.js
new file mode 100644
index 0000000000..0291cf2769
--- /dev/null
+++ b/server/services/pipeline/editorialAnalysis.js
@@ -0,0 +1,395 @@
+/**
+ * Pipeline — Editorial reader-emotion / plot / character analysis.
+ *
+ * Runs an LLM pass over one issue's reader-facing content (prose, falling back
+ * to comic script / teleplay) and stores a section-by-section emotion log plus
+ * plot tension and character-arc detection. Snapshots persist at
+ * `data/pipeline-editorial/{issueId}.json` and pin a `sourceContentHash` so the
+ * UI can flag stale results when the underlying draft changes.
+ *
+ * The series-level Editorial Roadmap (`getSeriesEditorial`) aggregates every
+ * issue's snapshot into the Plot / Character / Reader curves + character arcs.
+ *
+ * Mirrors the Writers Room evaluator (server/services/writersRoom/evaluator.js)
+ * for the snapshot+staleness pattern. Errors bubble (no try/catch) — the batch
+ * runner in editorialAnalysisRunner.js owns the per-issue boundary.
+ */
+
+import { join } from 'path';
+import { createHash } from 'crypto';
+import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../../lib/fileUtils.js';
+import { runStagedLLM } from '../../lib/stageRunner.js';
+import { getIssue, listIssues } from './issues.js';
+import { getSeries } from './series.js';
+import { getSeriesCanon } from './seriesCanon.js';
+
+const STAGE = 'pipeline-editorial-analysis';
+const ARC_DIRECTIONS = Object.freeze(['rising', 'falling', 'flat', 'complex']);
+
+// Defensive caps on LLM output — never trust raw model JSON.
+const MAX_SECTIONS = 200;
+const MAX_CHARACTERS = 40;
+const MAX_BEATS = 60;
+const LABEL_MAX = 120;
+const EXCERPT_MAX = 200;
+const EMOTION_MAX = 40;
+const NOTE_MAX = 500;
+// Cap the content we send to the model. Prose/script stage output is bounded
+// at STAGE_OUTPUT_MAX (~400KB) which would blow the context window (and the
+// JSON instruction block with it) on a long issue, yielding a truncated /
+// malformed response that sanitizeAnalysis silently degrades to empty. ~48K
+// chars (~12K tokens) leaves ample room for the prompt + a heavy-tier reply.
+const CONTENT_MAX = 48_000;
+
+const nowIso = () => new Date().toISOString();
+
+// Snapshot content hash — sourceContentHash pins the analyzed draft so a later
+// edit flips the issue to `stale`. One-liner (matches writersRoom/local.js's
+// contentHash) — not worth a shared lib module + barrel entry.
+const contentHash = (text) => createHash('sha256').update(text || '').digest('hex');
+
+// Defense-in-depth: refuse path-traversal-shaped ids before interpolating into
+// the on-disk snapshot path. Issue ids are `iss-<uuid>` — restrict to a safe
+// charset.
+function assertValidIssueId(id) {
+ if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(id)) {
+ throw new Error(`Invalid issue id: ${id}`);
+ }
+}
+
+const editorialDir = () => join(PATHS.data, 'pipeline-editorial');
+const snapshotPath = (issueId) => join(editorialDir(), `${issueId}.json`);
+
+// ---------- content selection ----------
+
+// Reader-facing content, preferring prose, then either script form. Returns
+// null when the issue has no drafted content yet (only beats / visual stages).
+export function pickAnalyzableContent(issue) {
+ const stages = issue?.stages || {};
+ for (const sourceStage of ['prose', 'comicScript', 'teleplay']) {
+ const text = (stages[sourceStage]?.output || '').trim();
+ if (text) return { text, sourceStage };
+ }
+ return null;
+}
+
+// ---------- sanitize LLM output ----------
+
+const clampNum = (v, min, max, fallback = 0) => {
+ const n = Number(v);
+ if (!Number.isFinite(n)) return fallback;
+ return Math.max(min, Math.min(max, Math.round(n)));
+};
+
+const str = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
+
+function sanitizeSection(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ return {
+ label: str(raw.label, LABEL_MAX) || 'Section',
+ excerpt: str(raw.excerpt, EXCERPT_MAX),
+ primaryEmotion: str(raw.primaryEmotion, EMOTION_MAX),
+ emotions: Array.isArray(raw.emotions)
+ ? raw.emotions.map((e) => str(e, EMOTION_MAX)).filter(Boolean).slice(0, 5)
+ : [],
+ tension: clampNum(raw.tension, 0, 100),
+ valence: clampNum(raw.valence, -100, 100),
+ note: str(raw.note, NOTE_MAX),
+ };
+}
+
+function sanitizeCharacter(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ const name = str(raw.name, LABEL_MAX);
+ if (!name) return null;
+ return {
+ name,
+ role: str(raw.role, EMOTION_MAX),
+ isProtagonist: raw.isProtagonist === true ? true : raw.isProtagonist === false ? false : null,
+ arcDirection: ARC_DIRECTIONS.includes(raw.arcDirection) ? raw.arcDirection : 'flat',
+ arcSummary: str(raw.arcSummary, NOTE_MAX),
+ beats: Array.isArray(raw.beats)
+ ? raw.beats
+ .map((b) => (b && typeof b === 'object'
+ ? { sectionIndex: clampNum(b.sectionIndex, 0, MAX_SECTIONS), state: str(b.state, LABEL_MAX) }
+ : null))
+ .filter((b) => b && b.state)
+ .slice(0, MAX_BEATS)
+ : [],
+ };
+}
+
+function sanitizeAnalysis(parsed) {
+ const p = parsed && typeof parsed === 'object' ? parsed : {};
+ const rollupRaw = p.rollup && typeof p.rollup === 'object' ? p.rollup : {};
+ return {
+ sections: Array.isArray(p.sections)
+ ? p.sections.map(sanitizeSection).filter(Boolean).slice(0, MAX_SECTIONS)
+ : [],
+ characters: Array.isArray(p.characters)
+ ? p.characters.map(sanitizeCharacter).filter(Boolean).slice(0, MAX_CHARACTERS)
+ : [],
+ rollup: {
+ plotTension: clampNum(rollupRaw.plotTension, 0, 100),
+ characterProgress: clampNum(rollupRaw.characterProgress, 0, 100),
+ readerValence: clampNum(rollupRaw.readerValence, -100, 100),
+ readerIntensity: clampNum(rollupRaw.readerIntensity, 0, 100),
+ primaryEmotion: str(rollupRaw.primaryEmotion, EMOTION_MAX),
+ peakTension: clampNum(rollupRaw.peakTension, 0, 100),
+ cliffhanger: rollupRaw.cliffhanger === true,
+ oneLine: str(rollupRaw.oneLine, NOTE_MAX),
+ },
+ };
+}
+
+// ---------- storage ----------
+
+async function loadSnapshot(issueId) {
+ const content = await tryReadFile(snapshotPath(issueId));
+ if (content === null) return null;
+ return safeJSONParse(content, null, { allowArray: false, logError: true, context: snapshotPath(issueId) });
+}
+
+async function saveSnapshot(snapshot) {
+ await ensureDir(editorialDir());
+ await atomicWrite(snapshotPath(snapshot.issueId), snapshot);
+}
+
+// ---------- analysis ----------
+
+// Best-effort hint: if a canon character's name appears in the series-level
+// protagonist-arc text, pass it so the model confirms rather than guesses.
+function detectKnownProtagonist(arcText, characterNames) {
+ if (!arcText) return '';
+ const lower = arcText.toLowerCase();
+ return characterNames.find((n) => n && lower.includes(n.toLowerCase())) || '';
+}
+
+/**
+ * Analyze a single issue. Returns the stored snapshot, a `{ status:'no-content' }`
+ * marker, or a cached snapshot when the content is unchanged and `!force`.
+ */
+export async function analyzeIssue(issueId, { providerId, model, force = false } = {}) {
+ assertValidIssueId(issueId);
+ const issue = await getIssue(issueId);
+ const picked = pickAnalyzableContent(issue);
+ if (!picked) return { status: 'no-content', issueId, seriesId: issue.seriesId };
+
+ const hash = contentHash(picked.text);
+ const existing = await loadSnapshot(issueId);
+ if (!force && existing && existing.status === 'complete' && existing.sourceContentHash === hash) {
+ return { ...existing, cached: true };
+ }
+
+ const series = await getSeries(issue.seriesId).catch(() => null);
+ const canon = series ? await getSeriesCanon(series) : { characters: [] };
+ const characterNames = (canon.characters || []).map((c) => c?.name).filter(Boolean).slice(0, 40);
+ const arc = series?.arc || null;
+
+ const ctx = {
+ series: { name: series?.name || 'Untitled series', logline: series?.logline || '' },
+ issue: { number: issue.number, title: issue.title, arcRole: issue.arcRole || '' },
+ arc: arc
+ ? {
+ protagonistArc: arc.protagonistArc || '',
+ themesCsv: Array.isArray(arc.themes) ? arc.themes.join(', ') : '',
+ }
+ : { protagonistArc: '', themesCsv: '' },
+ knownProtagonist: detectKnownProtagonist(arc?.protagonistArc, characterNames),
+ knownCharacters: characterNames.join(', '),
+ format: picked.sourceStage === 'comicScript' ? 'comic script'
+ : picked.sourceStage === 'teleplay' ? 'teleplay' : 'prose',
+ content: picked.text.length > CONTENT_MAX
+ ? `${picked.text.slice(0, CONTENT_MAX)}\n\n[content truncated for analysis — ${picked.text.length} chars total]`
+ : picked.text,
+ };
+
+ const result = await runStagedLLM(STAGE, ctx, {
+ returnsJson: true,
+ providerOverride: providerId,
+ modelOverride: model,
+ source: 'pipeline-editorial-analysis',
+ });
+
+ const snapshot = {
+ issueId,
+ seriesId: issue.seriesId,
+ status: 'complete',
+ sourceStage: picked.sourceStage,
+ sourceContentHash: hash,
+ providerId: result.providerId,
+ model: result.model,
+ runId: result.runId,
+ createdAt: nowIso(),
+ completedAt: nowIso(),
+ ...sanitizeAnalysis(result.content),
+ };
+ await saveSnapshot(snapshot);
+ console.log(`📊 editorial: analyzed issue=${issueId.slice(0, 12)} src=${picked.sourceStage} sections=${snapshot.sections.length} chars=${snapshot.characters.length}`);
+ return snapshot;
+}
+
+// Single source of truth for staleness — used by both the per-issue read and
+// the series aggregate so they can never disagree. A complete snapshot is
+// stale when the issue's current content no longer matches the analyzed hash,
+// OR when the content was removed entirely after analysis (phantom point).
+// A legacy snapshot with no stored hash is treated as not-stale (can't tell).
+function isSnapshotStale(snap, issue) {
+ if (!snap || snap.status !== 'complete') return false;
+ const picked = pickAnalyzableContent(issue);
+ if (!picked) return true; // analyzed, but the draft was cleared since
+ if (!snap.sourceContentHash) return false;
+ return snap.sourceContentHash !== contentHash(picked.text);
+}
+
+/**
+ * Load one issue's stored analysis with a `stale` flag (current content hash
+ * differs from the analyzed hash). Returns null when never analyzed.
+ */
+export async function getIssueAnalysis(issueId) {
+ assertValidIssueId(issueId);
+ const snap = await loadSnapshot(issueId);
+ if (!snap) return null;
+ const issue = await getIssue(issueId).catch(() => null);
+ return { ...snap, stale: isSnapshotStale(snap, issue) };
+}
+
+// ---------- series aggregation ----------
+
+const normalizeName = (name) => String(name || '').trim().toLowerCase();
+const valenceToScore = (v) => clampNum((Number(v) + 100) / 2, 0, 100); // −100..100 → 0..100
+
+// Fold one snapshot's character records into the cross-issue accumulator.
+// Votes are counted at most ONCE per issue per character — an LLM that lists
+// the same name twice in one issue's characters[] must not skew the
+// protagonist election, which is decided across issues.
+function foldCharacters(acc, snapshot) {
+ const countedThisIssue = new Set();
+ for (const c of snapshot.characters || []) {
+ const key = normalizeName(c.name);
+ if (!key) continue;
+ let entry = acc.get(key);
+ if (!entry) {
+ entry = { name: c.name, protagonistVotes: 0, falseVotes: 0, directions: new Set(), arcSummary: '', issues: new Set(), roles: new Set() };
+ acc.set(key, entry);
+ }
+ if (!countedThisIssue.has(key)) {
+ countedThisIssue.add(key);
+ if (c.isProtagonist === true) entry.protagonistVotes += 1;
+ else if (c.isProtagonist === false) entry.falseVotes += 1;
+ }
+ if (c.arcDirection && c.arcDirection !== 'flat') entry.directions.add(c.arcDirection);
+ if (c.role) entry.roles.add(c.role);
+ if (c.arcSummary && c.arcSummary.length > entry.arcSummary.length) entry.arcSummary = c.arcSummary;
+ entry.issues.add(snapshot.issueId);
+ }
+}
+
+function resolveDirection(directions) {
+ if (directions.size === 0) return 'flat';
+ if (directions.size === 1) return [...directions][0];
+ return 'complex';
+}
+
+/**
+ * Aggregate every analyzed issue in a series into the Editorial Roadmap:
+ * Plot / Character / Reader curves, character arcs (with protagonist detection),
+ * and coverage stats.
+ */
+export async function getSeriesEditorial(seriesId) {
+ const series = await getSeries(seriesId).catch(() => null);
+ const issues = await listIssues({ seriesId });
+ const ordered = [...issues].sort(
+ (a, b) => (a.arcPosition ?? 9999) - (b.arcPosition ?? 9999) || (a.number || 0) - (b.number || 0)
+ );
+
+ // Snapshot reads are independent file I/O — fan them out in parallel (mirrors
+ // collectionStore.loadAll) rather than awaiting one at a time.
+ const snaps = await Promise.all(ordered.map((issue) => loadSnapshot(issue.id)));
+
+ const charAcc = new Map();
+ let analyzed = 0;
+ let stale = 0;
+ let withContent = 0;
+ let noContent = 0;
+
+ const roadmap = [];
+ ordered.forEach((issue, idx) => {
+ const snap = snaps[idx];
+ const hasContent = !!pickAnalyzableContent(issue);
+ if (hasContent) withContent += 1; else noContent += 1;
+
+ const isComplete = !!(snap && snap.status === 'complete');
+ const isStale = isSnapshotStale(snap, issue);
+ const entry = {
+ issueId: issue.id,
+ number: issue.number,
+ arcPosition: issue.arcPosition ?? null,
+ title: issue.title,
+ label: issue.arcPosition != null ? `E${issue.arcPosition}` : `#${issue.number || ''}`,
+ analyzed: isComplete,
+ hasContent,
+ stale: isStale,
+ // Snapshot identity — changes when an issue is re-analyzed, so the detail
+ // view can invalidate its cached section log.
+ analyzedAt: isComplete ? (snap.completedAt || snap.createdAt || null) : null,
+ plot: null,
+ character: null,
+ reader: null,
+ primaryEmotion: '',
+ };
+ if (isComplete) {
+ analyzed += 1;
+ if (isStale) stale += 1;
+ entry.plot = snap.rollup?.plotTension ?? null;
+ entry.character = snap.rollup?.characterProgress ?? null;
+ entry.reader = valenceToScore(snap.rollup?.readerValence);
+ entry.primaryEmotion = snap.rollup?.primaryEmotion || '';
+ foldCharacters(charAcc, snap);
+ }
+ roadmap.push(entry);
+ });
+
+ // Resolve aggregated characters. isProtagonist uses NET votes across issues:
+ // a clear majority of "yes" → true, a clear majority of "no" → false, a tie
+ // (or no votes) → null (genuinely ambiguous). The protagonist is then the
+ // strongest net-positive candidate, so a character the model mostly tagged
+ // NOT-protagonist can't be crowned on a stray single yes-vote.
+ const characters = [...charAcc.values()]
+ .map((e) => ({
+ name: e.name,
+ isProtagonist: e.protagonistVotes > e.falseVotes ? true : (e.falseVotes > e.protagonistVotes ? false : null),
+ arcDirection: resolveDirection(e.directions),
+ arcSummary: e.arcSummary,
+ role: [...e.roles][0] || '',
+ issueCount: e.issues.size,
+ netProtagonistVotes: e.protagonistVotes - e.falseVotes,
+ }))
+ .sort((a, b) => b.issueCount - a.issueCount || b.netProtagonistVotes - a.netProtagonistVotes);
+
+ let protagonist = characters
+ .filter((c) => c.isProtagonist === true)
+ .sort((a, b) => b.netProtagonistVotes - a.netProtagonistVotes || b.issueCount - a.issueCount)[0] || null;
+ if (!protagonist) {
+ protagonist = characters.find((c) => c.arcDirection !== 'flat') || characters[0] || null;
+ }
+ if (protagonist) protagonist = { ...protagonist, isProtagonist: true };
+
+ const protagonistKey = protagonist ? normalizeName(protagonist.name) : null;
+ const supportingArcs = characters.filter(
+ (c) => normalizeName(c.name) !== protagonistKey && c.arcDirection !== 'flat'
+ );
+
+ return {
+ seriesId,
+ coverage: { analyzed, total: ordered.length, withContent, stale, noContent },
+ roadmap,
+ characters,
+ protagonist,
+ supportingArcs,
+ protagonistArcText: series?.arc?.protagonistArc || null,
+ generatedAt: nowIso(),
+ };
+}
+
+export const __testing = { sanitizeAnalysis, valenceToScore, contentHash };
diff --git a/server/services/pipeline/editorialAnalysis.test.js b/server/services/pipeline/editorialAnalysis.test.js
new file mode 100644
index 0000000000..f396373b24
--- /dev/null
+++ b/server/services/pipeline/editorialAnalysis.test.js
@@ -0,0 +1,250 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// In-memory snapshot store mirroring atomicWrite(JSON.stringify) + tryReadFile(string).
+const fileStore = new Map();
+
+vi.mock('../../lib/fileUtils.js', () => ({
+ PATHS: { data: '/mock/data' },
+ ensureDir: vi.fn(async () => {}),
+ atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, JSON.stringify(data)); }),
+ tryReadFile: vi.fn(async (path) => (fileStore.has(path) ? fileStore.get(path) : null)),
+ safeJSONParse: (str, fallback) => { try { return JSON.parse(str); } catch { return fallback; } },
+}));
+
+// runStagedLLM returns the next queued canned analysis.
+const llmQueue = [];
+const llmCalls = [];
+vi.mock('../../lib/stageRunner.js', () => ({
+ runStagedLLM: vi.fn(async (stage, ctx) => {
+ llmCalls.push({ stage, ctx });
+ const content = llmQueue.shift();
+ return { content, model: 'mock-model', providerId: 'mock-provider', runId: 'run-1' };
+ }),
+}));
+
+// Fixture issue/series stores.
+const issuesFixture = new Map();
+const seriesFixture = new Map();
+
+vi.mock('./issues.js', () => ({
+ getIssue: vi.fn(async (id) => {
+ const i = issuesFixture.get(id);
+ if (!i) throw new Error(`Issue not found: ${id}`);
+ return i;
+ }),
+ listIssues: vi.fn(async ({ seriesId } = {}) =>
+ [...issuesFixture.values()].filter((i) => !seriesId || i.seriesId === seriesId)),
+}));
+
+vi.mock('./series.js', () => ({
+ getSeries: vi.fn(async (id) => {
+ const s = seriesFixture.get(id);
+ if (!s) throw new Error(`Series not found: ${id}`);
+ return s;
+ }),
+}));
+
+const getSeriesCanonMock = vi.fn(async () => ({ characters: [{ name: 'Ada' }, { name: 'Bly' }] }));
+vi.mock('./seriesCanon.js', () => ({
+ getSeriesCanon: (...a) => getSeriesCanonMock(...a),
+}));
+
+const svc = await import('./editorialAnalysis.js');
+
+const makeIssue = (id, { seriesId = 'ser-1', number = 1, arcPosition = 1, title = 'T', prose = 'Some prose.' } = {}) => ({
+ id, seriesId, number, arcPosition, title, arcRole: null,
+ stages: { prose: { output: prose }, comicScript: { output: '' }, teleplay: { output: '' } },
+});
+
+const cannedAnalysis = () => ({
+ sections: [
+ { label: 'Scene 1', excerpt: 'open', primaryEmotion: 'curiosity', emotions: ['curiosity'], tension: 40, valence: 10, note: 'opening' },
+ { label: 'Scene 2', primaryEmotion: 'dread', tension: 150, valence: -200, note: 'turn' },
+ ],
+ characters: [
+ { name: 'Ada', isProtagonist: true, role: 'protagonist', arcDirection: 'rising', arcSummary: 'grows up', beats: [{ sectionIndex: 1, state: 'resolves' }] },
+ { name: 'Bly', isProtagonist: false, arcDirection: 'falling', arcSummary: 'falls apart' },
+ ],
+ rollup: { plotTension: 80, characterProgress: 55, readerValence: -40, readerIntensity: 70, primaryEmotion: 'dread', peakTension: 90, cliffhanger: true, oneLine: 'tense ride' },
+});
+
+beforeEach(() => {
+ fileStore.clear();
+ issuesFixture.clear();
+ seriesFixture.clear();
+ llmQueue.length = 0;
+ llmCalls.length = 0;
+ seriesFixture.set('ser-1', { id: 'ser-1', name: 'Test', logline: 'lg', arc: { protagonistArc: 'Ada must grow', themes: ['loss'] } });
+});
+
+describe('analyzeIssue', () => {
+ it('clamps LLM output, stores a snapshot, and carries run attribution', async () => {
+ issuesFixture.set('iss-1', makeIssue('iss-1'));
+ llmQueue.push(cannedAnalysis());
+
+ const snap = await svc.analyzeIssue('iss-1');
+ expect(snap.status).toBe('complete');
+ expect(snap.sections).toHaveLength(2);
+ // Section 2's tension 150 → 100, valence −200 → −100.
+ expect(snap.sections[1].tension).toBe(100);
+ expect(snap.sections[1].valence).toBe(-100);
+ expect(snap.rollup.cliffhanger).toBe(true);
+ expect(snap.providerId).toBe('mock-provider');
+ expect(snap.runId).toBe('run-1');
+ expect(snap.sourceStage).toBe('prose');
+ expect(snap.sourceContentHash).toBeTruthy();
+ // Canon must be resolved from the SERIES OBJECT (not the seriesId string) —
+ // a regression to getSeriesCanon(issue.seriesId) would silently drop the
+ // character hints in production while a loose mock stayed green.
+ expect(getSeriesCanonMock).toHaveBeenCalledWith(seriesFixture.get('ser-1'));
+ });
+
+ it('returns no-content when the issue has no drafted prose/script', async () => {
+ issuesFixture.set('iss-2', makeIssue('iss-2', { prose: '' }));
+ const res = await svc.analyzeIssue('iss-2');
+ expect(res.status).toBe('no-content');
+ expect(llmCalls).toHaveLength(0);
+ });
+
+ it('returns a cached snapshot when content is unchanged, re-runs on force', async () => {
+ issuesFixture.set('iss-3', makeIssue('iss-3'));
+ llmQueue.push(cannedAnalysis(), cannedAnalysis());
+
+ await svc.analyzeIssue('iss-3');
+ const cached = await svc.analyzeIssue('iss-3');
+ expect(cached.cached).toBe(true);
+ expect(llmCalls).toHaveLength(1);
+
+ await svc.analyzeIssue('iss-3', { force: true });
+ expect(llmCalls).toHaveLength(2);
+ });
+});
+
+describe('getIssueAnalysis', () => {
+ it('flags stale when the content hash changes after analysis', async () => {
+ issuesFixture.set('iss-4', makeIssue('iss-4', { prose: 'original' }));
+ llmQueue.push(cannedAnalysis());
+ await svc.analyzeIssue('iss-4');
+
+ const fresh = await svc.getIssueAnalysis('iss-4');
+ expect(fresh.stale).toBe(false);
+
+ // Edit the prose — the stored snapshot's hash no longer matches.
+ issuesFixture.set('iss-4', makeIssue('iss-4', { prose: 'rewritten' }));
+ const stale = await svc.getIssueAnalysis('iss-4');
+ expect(stale.stale).toBe(true);
+ });
+
+ it('returns null when never analyzed', async () => {
+ issuesFixture.set('iss-5', makeIssue('iss-5'));
+ expect(await svc.getIssueAnalysis('iss-5')).toBeNull();
+ });
+});
+
+describe('getSeriesEditorial', () => {
+ it('aggregates roadmap, coverage, protagonist, and supporting arcs', async () => {
+ issuesFixture.set('iss-a', makeIssue('iss-a', { number: 1, arcPosition: 1 }));
+ issuesFixture.set('iss-b', makeIssue('iss-b', { number: 2, arcPosition: 2, prose: 'more' }));
+ issuesFixture.set('iss-c', makeIssue('iss-c', { number: 3, arcPosition: 3, prose: '' })); // no content
+ llmQueue.push(cannedAnalysis(), cannedAnalysis());
+ await svc.analyzeIssue('iss-a');
+ await svc.analyzeIssue('iss-b');
+
+ const agg = await svc.getSeriesEditorial('ser-1');
+ expect(agg.coverage.total).toBe(3);
+ expect(agg.coverage.analyzed).toBe(2);
+ expect(agg.coverage.noContent).toBe(1);
+ expect(agg.roadmap).toHaveLength(3);
+
+ const analyzed = agg.roadmap.filter((r) => r.analyzed);
+ expect(analyzed).toHaveLength(2);
+ // reader = valenceToScore(−40) = (−40+100)/2 = 30
+ expect(analyzed[0].reader).toBe(30);
+ expect(analyzed[0].plot).toBe(80);
+
+ expect(agg.protagonist?.name).toBe('Ada');
+ expect(agg.protagonist.isProtagonist).toBe(true);
+ const supportingNames = agg.supportingArcs.map((c) => c.name);
+ expect(supportingNames).toContain('Bly');
+ expect(supportingNames).not.toContain('Ada');
+ });
+
+ it('reports zero coverage with empty roadmap entries when nothing is analyzed', async () => {
+ issuesFixture.set('iss-x', makeIssue('iss-x'));
+ const agg = await svc.getSeriesEditorial('ser-1');
+ expect(agg.coverage.analyzed).toBe(0);
+ expect(agg.coverage.withContent).toBe(1);
+ expect(agg.roadmap[0].analyzed).toBe(false);
+ expect(agg.protagonist).toBeNull();
+ });
+
+ it('does not crown a character the LLM mostly marked NOT protagonist (net votes)', async () => {
+ const cannedWith = (characters) => ({
+ sections: [{ label: 'S', primaryEmotion: 'x', tension: 50, valence: 0 }],
+ characters,
+ rollup: { plotTension: 50, characterProgress: 50, readerValence: 0, readerIntensity: 50, primaryEmotion: 'x', peakTension: 50, cliffhanger: false, oneLine: 'o' },
+ });
+ issuesFixture.set('iss-1', makeIssue('iss-1', { number: 1, arcPosition: 1 }));
+ issuesFixture.set('iss-2', makeIssue('iss-2', { number: 2, arcPosition: 2 }));
+ issuesFixture.set('iss-3', makeIssue('iss-3', { number: 3, arcPosition: 3 }));
+ issuesFixture.set('iss-4', makeIssue('iss-4', { number: 4, arcPosition: 4 }));
+ // Noisy: 1 yes + 2 no (net negative) → must NOT be crowned despite having a yes-vote.
+ llmQueue.push(cannedWith([{ name: 'Noisy', isProtagonist: true, arcDirection: 'flat' }]));
+ llmQueue.push(cannedWith([{ name: 'Noisy', isProtagonist: false, arcDirection: 'flat' }]));
+ llmQueue.push(cannedWith([{ name: 'Noisy', isProtagonist: false, arcDirection: 'flat' }]));
+ llmQueue.push(cannedWith([{ name: 'Quiet', isProtagonist: null, arcDirection: 'rising', arcSummary: 'grows' }]));
+ await svc.analyzeIssue('iss-1');
+ await svc.analyzeIssue('iss-2');
+ await svc.analyzeIssue('iss-3');
+ await svc.analyzeIssue('iss-4');
+
+ const agg = await svc.getSeriesEditorial('ser-1');
+ expect(agg.protagonist?.name).not.toBe('Noisy');
+ expect(agg.protagonist?.name).toBe('Quiet'); // falls back to the character with a real arc
+ });
+
+ it('counts protagonist votes at most once per issue (no skew from duplicated names)', async () => {
+ const cannedWith = (characters) => ({
+ sections: [{ label: 'S', primaryEmotion: 'x', tension: 50, valence: 0 }],
+ characters,
+ rollup: { plotTension: 50, characterProgress: 50, readerValence: 0, readerIntensity: 50, primaryEmotion: 'x', peakTension: 50, cliffhanger: false, oneLine: 'o' },
+ });
+ issuesFixture.set('iss-1', makeIssue('iss-1', { number: 1, arcPosition: 1 }));
+ issuesFixture.set('iss-2', makeIssue('iss-2', { number: 2, arcPosition: 2 }));
+ // Dup listed 3× in ONE issue would beat Real (2 issues) if votes weren't deduped.
+ llmQueue.push(cannedWith([
+ { name: 'Dup', isProtagonist: true, arcDirection: 'rising' },
+ { name: 'Dup', isProtagonist: true },
+ { name: 'Dup', isProtagonist: true },
+ { name: 'Real', isProtagonist: true, arcDirection: 'rising' },
+ ]));
+ llmQueue.push(cannedWith([{ name: 'Real', isProtagonist: true, arcDirection: 'rising' }]));
+ await svc.analyzeIssue('iss-1');
+ await svc.analyzeIssue('iss-2');
+
+ const agg = await svc.getSeriesEditorial('ser-1');
+ expect(agg.protagonist?.name).toBe('Real');
+ });
+
+ it('marks an analyzed issue stale when its content was removed afterward', async () => {
+ issuesFixture.set('iss-d', makeIssue('iss-d', { prose: 'draft' }));
+ llmQueue.push(cannedAnalysis());
+ await svc.analyzeIssue('iss-d');
+ // Clear the prose — the snapshot now describes content that no longer exists.
+ issuesFixture.set('iss-d', makeIssue('iss-d', { prose: '' }));
+
+ const agg = await svc.getSeriesEditorial('ser-1');
+ const entry = agg.roadmap.find((r) => r.issueId === 'iss-d');
+ expect(entry.analyzed).toBe(true);
+ expect(entry.stale).toBe(true);
+ expect(agg.coverage.stale).toBe(1);
+ });
+});
+
+describe('__testing.valenceToScore', () => {
+ it('maps −100..100 to 0..100', () => {
+ expect(svc.__testing.valenceToScore(-100)).toBe(0);
+ expect(svc.__testing.valenceToScore(0)).toBe(50);
+ expect(svc.__testing.valenceToScore(100)).toBe(100);
+ });
+});
diff --git a/server/services/pipeline/editorialAnalysisRunner.js b/server/services/pipeline/editorialAnalysisRunner.js
new file mode 100644
index 0000000000..d19b03e3db
--- /dev/null
+++ b/server/services/pipeline/editorialAnalysisRunner.js
@@ -0,0 +1,120 @@
+/**
+ * Pipeline — Batch runner for series-wide editorial analysis.
+ *
+ * Analyzes every issue in a series that has reader-facing content, streaming
+ * per-issue progress to attached SSE clients. Mirrors autoRunner.js: a single
+ * in-memory `runs` map keyed by `seriesId`, with replay for late-connecting
+ * clients via lib/sseUtils.js.
+ *
+ * analyzeIssue() short-circuits to a cached snapshot when the content is
+ * unchanged, so a re-run only spends LLM calls on new / edited / stale issues
+ * (or all of them when `force: true`).
+ */
+
+import { randomUUID } from 'crypto';
+import { broadcastSse, attachSseClient, closeJobAfterDelay } from '../../lib/sseUtils.js';
+import { listIssues } from './issues.js';
+import { analyzeIssue, pickAnalyzableContent } from './editorialAnalysis.js';
+
+// runs: Map<seriesId, { runId, clients[], lastPayload, cancelRequested, startedAt }>
+const runs = new Map();
+
+export function isSeriesAnalysisActive(seriesId) {
+ return runs.has(seriesId);
+}
+
+export function attachClient(seriesId, res) {
+ return attachSseClient(runs, seriesId, res);
+}
+
+export function cancelSeriesAnalysis(seriesId) {
+ const run = runs.get(seriesId);
+ if (!run) return false;
+ run.cancelRequested = true;
+ return true;
+}
+
+function broadcast(seriesId, payload) {
+ const run = runs.get(seriesId);
+ if (!run) return;
+ broadcastSse(run, payload);
+}
+
+/**
+ * Kick off the series editorial-analysis batch. Returns the runId immediately;
+ * progress lands via SSE. Re-calling while a run is in flight resolves to the
+ * existing runId.
+ */
+export async function startSeriesAnalysis(seriesId, options = {}) {
+ if (runs.has(seriesId)) return { runId: runs.get(seriesId).runId, alreadyRunning: true };
+ const runId = randomUUID();
+ const record = {
+ runId,
+ clients: [],
+ lastPayload: null,
+ cancelRequested: false,
+ startedAt: new Date().toISOString(),
+ };
+ runs.set(seriesId, record);
+
+ // Fire-and-forget coordinator. The try/catch is the permitted boundary use:
+ // an unhandled LLM rejection here would crash the process on Node ≥15.
+ (async () => {
+ try {
+ const issues = await listIssues({ seriesId });
+ const analyzable = issues.filter((i) => pickAnalyzableContent(i));
+ const ordered = analyzable.sort(
+ (a, b) => (a.arcPosition ?? 9999) - (b.arcPosition ?? 9999) || (a.number || 0) - (b.number || 0)
+ );
+ broadcast(seriesId, { type: 'start', runId, total: ordered.length });
+
+ let done = 0;
+ for (const issue of ordered) {
+ if (record.cancelRequested) break;
+ broadcast(seriesId, {
+ type: 'issue:start',
+ issueId: issue.id,
+ number: issue.number,
+ title: issue.title,
+ done,
+ total: ordered.length,
+ });
+ const result = await analyzeIssue(issue.id, {
+ providerId: options.providerId,
+ model: options.model,
+ force: !!options.force,
+ }).catch((err) => ({ status: 'error', error: (err?.message || String(err)).slice(0, 500) }));
+ done += 1;
+ broadcast(seriesId, {
+ type: result?.status === 'error' ? 'issue:error' : 'issue:complete',
+ issueId: issue.id,
+ number: issue.number,
+ done,
+ total: ordered.length,
+ cached: !!result?.cached,
+ sections: result?.sections?.length || 0,
+ error: result?.status === 'error' ? result.error : undefined,
+ });
+ }
+
+ broadcast(seriesId, {
+ type: record.cancelRequested ? 'canceled' : 'complete',
+ runId,
+ analyzed: done,
+ completedAt: new Date().toISOString(),
+ });
+ console.log(`📊 editorial batch ${record.cancelRequested ? 'canceled' : 'complete'} — series=${seriesId.slice(0, 12)} analyzed=${done}/${ordered.length}`);
+ } catch (err) {
+ const message = (err?.message || String(err)).slice(0, 1000);
+ console.error(`❌ editorial batch failed — series=${seriesId.slice(0, 12)} ${message}`);
+ broadcast(seriesId, { type: 'error', runId, error: message, failedAt: new Date().toISOString() });
+ } finally {
+ closeJobAfterDelay(runs, seriesId);
+ }
+ })();
+
+ return { runId, alreadyRunning: false };
+}
+
+// Export internals for tests.
+export const __testing = { runs };