Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-1286]): reverse outline — scene segmentation + plotline tagging view
[._.]/ Adam Eivy1d441efad6cb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 4d056ce05a..3b48941a67 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **Reverse Outline — a color-coded scene map of your drafted manuscript.** A new **Reverse Outline** view (linked from the series page) reads the finished/drafted manuscript and lays out what's *actually on the page*: it identifies the recurring plotlines (A-plot, subplots, POV threads) and segments the prose into scenes, each tagged to the plotline it advances — then shows them as a grid (rows = plotlines, columns = scenes in reading order) so you can see thread cadence, gaps, and tangles at a glance. Click any scene marker to read its summary, POV, setting, character list, and narrative/action/dialogue mix, and jump straight into the manuscript editor at that scene's issue. Generation streams live progress; the outline flags itself **stale** once the manuscript changes so you know to regenerate. This scene segmentation is the shared substrate upcoming editorial checks (scene balance, POV justification, cliffhangers, arc transitions) will read rather than re-deriving. (#1286)+- **Editorial checks — an extensible editorial-review system for the series pipeline.** Editorial rules (name confusability, exposition dumps, and more to come) previously had no shared home — each was a one-off. A new **editorial check registry + runner** lets each rule plug in, declare what it examines, and emit findings into the same manuscript-review comment set you already work through in the editor (jump-to, AI fix, accept/dismiss). This first release ships two reference checks: **Character name dissimilarity** (flags character names a reader could confuse — sharing a first letter, length, vowel pattern, opening, or ending) and **Info-dumping** (flags "as-you-know-Bob" exposition — backstory bricks, maid-and-butler dialogue, front-loaded world rules — with a suggestion to dramatize or trim each). Each check can be enabled/disabled and configured, and runs on demand for a series (with live progress) or automatically as part of Series Autopilot's editorial pass. Findings are tagged by which check raised them, so re-running never duplicates them and a dismissal stays dismissed for that check. New endpoints: `GET/PATCH /api/pipeline/editorial/checks` (catalog + enable/config) and `POST /api/pipeline/series/:id/editorial/checks/run` (run + SSE progress). (#1284)- **Series Autopilot — drive a whole series end-to-end autonomously.** A new `POST /api/pipeline/series/:id/autopilot/start` runs a *conductor* that inspects the series' current state and walks every missing step in order — generate arc → generate episodes per volume → verify arc → per-issue beat sheets → per-issue text stages (prose + scripts) → structural comic-script gate → series-level editorial review → **canon descriptive-integrity gate** → **draft cover + back cover + all interior comic pages** — by composing the existing pipeline service functions (it never re-implements generation). The "what's next" decision is a **pure resolver over the canonical records**, so it is non-destructive and resumable: anything already `ready`/`edited`/rendered is skipped (every pass runs `force:false`), and on restart you just start again and it picks up at the first still-missing step (a partially-built series is never clobbered). Progress streams over SSE (`/autopilot/progress`); `/autopilot/cancel` stops it (propagating to the active child runner); `/autopilot/status` exposes a thin persisted `series.autopilot` marker for resume/paused UI. Gated on the **cos** autonomy domain: `off` rejects the start (409), `dry-run` emits a no-side-effect `plan` of what it would do, `execute` runs and meters the daily cos action budget (pausing when exhausted — every draft render is one budget-gated action, since a comic is many GPU jobs). The arc-verify and editorial loops are **bounded** and **pause for human review** when they can't converge (arc verification can surface fresh findings every pass) — the residual findings are persisted on the marker. Draft renders are fire-and-forget proof-quality jobs whose in-flight job ids are persisted onto each cover/page slot (so a resumed run never re-renders an already-queued slot). Boot recovery demotes a marker stuck at `running` to `paused`. With opt-in `fileGaps`, capability/quality gaps the run can't resolve on its own — an unparseable script, a failing render, a stalled verify/editorial gate, a run-ending error — are filed as **deduped CoS tasks** (scoped to the pipeline app) so they're tracked rather than silently swallowed. The per-issue script gate runs two checks: a structural parse gate (does the script become pages/panels) and a craft-level LLM verify (`pipeline-script-verify` — un-renderable panels, panel-to-panel flow, dialogue/art balance, within-issue continuity, page-turn placement); the craft gate is advisory (surfaces + files blocking findings without hard-pausing, since the gating quality pass is the series-level editorial review). Before any visual production it also runs a **canon descriptive-integrity gate**: every canon noun (character/place/object) that appears where it would be *drawn* — the comic-script panel descriptions, not prose narration — must have a description, or the run **pauses for human review** (an artist can't render a name). The visual-source distinction is deliberate: an off-page character named only in narration is never drawn, so it's a Nouns-stage quality note, not a production blocker. The same check is exposed for the pipeline UI via `GET /api/pipeline/issues/:id/canon-readiness` and `GET /api/pipeline/series/:id/canon-readiness` (read-only, deterministic — reuses the committed canon name-matchers and `getSeriesCanon`). The whole feature is surfaced in the UI by an **Autonomous mode panel** on the series page (`AutopilotPanel`): a Run/Resume button with a run-options popover (draft visuals, file-gaps), live SSE step progress (with the dry-run plan when the cos domain is in dry-run), a Stop control, a paused/done/error banner driven by the persisted marker that lists the residual findings, and a one-click "production readiness" canon check that links each undescribed drawn noun to its issue's Nouns stage. (`server/services/pipeline/seriesAutopilot.js`, `server/services/pipeline/scriptVerify.js`, `server/services/pipeline/canonReadiness.js`, `server/routes/pipeline/canon.js`, `data.reference/prompts/stages/pipeline-script-verify.md`, `scripts/migrations/090-script-verify-stage.js`, `server/routes/pipeline/autopilot.js`, `server/routes/pipeline/index.js`, `server/services/pipeline/series.js`, `server/index.js`, `client/src/components/pipeline/AutopilotPanel.jsx`, `client/src/pages/PipelineSeries.jsx`, `client/src/services/apiPipeline.js`)diff --git a/client/src/App.jsx b/client/src/App.jsxindex 06825fc968..70f460ddd7 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -91,6 +91,7 @@ const Importer = lazyWithReload(() => import('./pages/Importer'));const StoryBuilder = lazyWithReload(() => import('./pages/StoryBuilder'));const PipelineSeries = lazyWithReload(() => import('./pages/PipelineSeries'));const PipelineSeriesRoadmap = lazyWithReload(() => import('./pages/PipelineSeriesRoadmap'));+const PipelineReverseOutline = lazyWithReload(() => import('./pages/PipelineReverseOutline'));const PipelineManuscriptEditor = lazyWithReload(() => import('./pages/PipelineManuscriptEditor'));const PipelineIssue = lazyWithReload(() => import('./pages/PipelineIssue'));const Login = lazyWithReload(() => import('./pages/Login'));@@ -311,6 +312,7 @@ export default function App() {<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/reverse-outline" element={<PipelineReverseOutline />} />{/* Splat (not a :param route) so navigating between issues reuses thesame component instance instead of remounting + refetching. */}<Route path="pipeline/series/:seriesId/manuscript/*" element={<PipelineManuscriptEditor />} />diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex cea1a08b5d..6488e25711 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -44,6 +44,7 @@ grep -i "what you want to do" client/src/lib/README.md| Module | Purpose ||---|---|| `pipelineImageDefaults.js` | Pipeline comic-page image-gen defaults + settings reader. |+| `reverseOutlineGrid.js` | `buildPlotlineGrid` (reverse-outline scenes + plotlines → plotline-by-sequence grid rows/cells) + `sceneComponentCount`. Used by the Reverse Outline page. || `wrImageDefaults.js` | Writers Room per-scene image-gen defaults + style discriminators. || `imageGenBackends.js` | `IMAGE_GEN_MODE` enum (local / codex / external) + metadata; `deriveAvailableBackends`; `I2I_CAPABLE_MODES` / `isI2iCapableMode(mode)` / `pickI2iMode(backends)` — image-to-image capability gating + best-backend selection. || `imageGenDefaults.js` | Shared `DEFAULT_NEGATIVE_PROMPT` used by the Image Gen form and quick-submit entry points. Mirrors server-side default. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex c70f783b89..73a97e809b 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -24,6 +24,7 @@ export * from './imageGenResolutions.js';export * from './importerDeepLink.js';export * from './issueLength.js';export * from './pipelineImageDefaults.js';+export * from './reverseOutlineGrid.js';export * from './runnerFamilies.js';export * from './videoGenResolutions.js';export * from './videoTilingOptions.js';diff --git a/client/src/lib/reverseOutlineGrid.js b/client/src/lib/reverseOutlineGrid.jsnew file mode 100644index 0000000000..4183ed3c50--- /dev/null+++ b/client/src/lib/reverseOutlineGrid.js@@ -0,0 +1,40 @@+/**+ * Reverse Outline grid layout (#1286) — pure view helper.+ *+ * Turns the flat `scenes[]` + `plotlines[]` from the reverse-outline artifact+ * into a plotline-by-sequence grid: rows = plotlines, columns = scenes in+ * reading order. Each cell tells the renderer whether the scene is on this+ * plotline as its `primary` thread, only `secondary`, or absent (`null`). This+ * is what surfaces thread cadence, gaps, and tangles at a glance.+ *+ * Pure + side-effect-free so it unit-tests without React.+ */++/**+ * @param {Array} scenes - ordered scene objects ({ id, plotlineId, secondaryPlotlineId, ... })+ * @param {Array} plotlines - ordered plotline objects ({ id, label, color, ... })+ * @returns {{ columns: Array, rows: Array<{ plotline, cells: Array<{ scene, role }|null>, count: number }> }}+ */+export function buildPlotlineGrid(scenes, plotlines) {+ const columns = Array.isArray(scenes) ? scenes : [];+ const rows = (Array.isArray(plotlines) ? plotlines : []).map((plotline) => {+ let count = 0;+ const cells = columns.map((scene) => {+ const role = scene?.plotlineId === plotline.id+ ? 'primary'+ : scene?.secondaryPlotlineId === plotline.id+ ? 'secondary'+ : null;+ if (role === 'primary') count += 1;+ return role ? { scene, role } : null;+ });+ return { plotline, cells, count };+ });+ return { columns, rows };+}++/** Count of the three prose modes materially present in a scene (0–3). */+export function sceneComponentCount(scene) {+ const c = scene?.components || {};+ return (c.narrative ? 1 : 0) + (c.action ? 1 : 0) + (c.dialogue ? 1 : 0);+}diff --git a/client/src/lib/reverseOutlineGrid.test.js b/client/src/lib/reverseOutlineGrid.test.jsnew file mode 100644index 0000000000..f8c4a80c58--- /dev/null+++ b/client/src/lib/reverseOutlineGrid.test.js@@ -0,0 +1,54 @@+import { describe, it, expect } from 'vitest';+import { buildPlotlineGrid, sceneComponentCount } from './reverseOutlineGrid.js';++const plotlines = [+ { id: 'A', label: 'Main', color: '#f00' },+ { id: 'B', label: 'Sub', color: '#0f0' },+];++const scenes = [+ { id: 'scene-001', plotlineId: 'A', secondaryPlotlineId: 'B' },+ { id: 'scene-002', plotlineId: 'B', secondaryPlotlineId: null },+ { id: 'scene-003', plotlineId: 'A', secondaryPlotlineId: null },+];++describe('buildPlotlineGrid', () => {+ it('returns one column per scene and one row per plotline', () => {+ const { columns, rows } = buildPlotlineGrid(scenes, plotlines);+ expect(columns).toHaveLength(3);+ expect(rows).toHaveLength(2);+ expect(rows.every((r) => r.cells.length === 3)).toBe(true);+ });++ it('marks primary vs secondary vs absent per cell', () => {+ const { rows } = buildPlotlineGrid(scenes, plotlines);+ const rowA = rows.find((r) => r.plotline.id === 'A');+ const rowB = rows.find((r) => r.plotline.id === 'B');++ expect(rowA.cells[0].role).toBe('primary'); // scene-001 primary A+ expect(rowB.cells[0].role).toBe('secondary'); // scene-001 secondary B+ expect(rowA.cells[1]).toBeNull(); // scene-002 not on A+ expect(rowB.cells[1].role).toBe('primary'); // scene-002 primary B+ });++ it('counts only primary scenes per plotline', () => {+ const { rows } = buildPlotlineGrid(scenes, plotlines);+ expect(rows.find((r) => r.plotline.id === 'A').count).toBe(2);+ expect(rows.find((r) => r.plotline.id === 'B').count).toBe(1);+ });++ it('tolerates empty / non-array inputs', () => {+ expect(buildPlotlineGrid(null, null)).toEqual({ columns: [], rows: [] });+ expect(buildPlotlineGrid([], plotlines).rows.every((r) => r.cells.length === 0)).toBe(true);+ });+});++describe('sceneComponentCount', () => {+ it('counts the present prose modes (0–3)', () => {+ expect(sceneComponentCount({ components: { narrative: true, action: true, dialogue: true } })).toBe(3);+ expect(sceneComponentCount({ components: { narrative: true, action: false, dialogue: true } })).toBe(2);+ expect(sceneComponentCount({ components: {} })).toBe(0);+ expect(sceneComponentCount({})).toBe(0);+ expect(sceneComponentCount(null)).toBe(0);+ });+});diff --git a/client/src/pages/PipelineReverseOutline.jsx b/client/src/pages/PipelineReverseOutline.jsxnew file mode 100644index 0000000000..81c578f539--- /dev/null+++ b/client/src/pages/PipelineReverseOutline.jsx@@ -0,0 +1,307 @@+/**+ * Pipeline — Reverse Outline (#1286).+ *+ * A color-coded scene map of the drafted manuscript: rows = plotlines, columns+ * = scenes in reading order. Each filled cell is a scene on that plotline+ * (primary = solid, secondary = ring); clicking jumps into the manuscript+ * editor at that scene's issue. Surfaces thread cadence, gaps, and tangles at a+ * glance. Generation streams progress over SSE.+ */++import { useEffect, useRef, useState } from 'react';+import { Link, useParams, useNavigate } from 'react-router-dom';+import { Loader2, RefreshCw, X, ArrowLeft, BookOpen, AlertTriangle, Compass } from 'lucide-react';+import toast from '../components/ui/Toast';+import {+ getPipelineSeries,+ getReverseOutline,+ generateReverseOutline,+ cancelReverseOutline,+ getReverseOutlineStatus,+ pipelineReverseOutlineSseUrl,+} from '../services/api';+import { usePipelineProgress } from '../hooks/usePipelineProgress';+import { buildPlotlineGrid, sceneComponentCount } from '../lib/reverseOutlineGrid.js';++const RUN_ENDED = new Set(['complete', 'canceled', 'cancelled', 'error']);++export default function PipelineReverseOutline() {+ const { seriesId } = useParams();+ const navigate = useNavigate();+ const [series, setSeries] = useState(null);+ const [outline, setOutline] = useState(null);+ const [loading, setLoading] = useState(true);+ const [active, setActive] = useState(false);+ const [starting, setStarting] = useState(false);+ const [selected, setSelected] = useState(null); // selected scene (detail panel)+ const activeRunIdRef = useRef(null);++ // Load series + outline, and re-attach to an in-flight run on (re)mount.+ useEffect(() => {+ let canceled = false;+ setLoading(true);+ Promise.all([+ getPipelineSeries(seriesId),+ getReverseOutline(seriesId),+ getReverseOutlineStatus(seriesId).catch(() => ({ active: false })),+ ])+ .then(([s, o, status]) => {+ if (canceled) return;+ setSeries(s);+ setOutline(o);+ if (status?.active) setActive(true);+ })+ .catch((err) => {+ if (canceled) return;+ toast.error(err.message || 'Failed to load reverse outline');+ navigate('/pipeline');+ })+ .finally(() => { if (!canceled) setLoading(false); });+ return () => { canceled = true; };+ }, [seriesId, navigate]);++ const { latest } = usePipelineProgress(pipelineReverseOutlineSseUrl, [seriesId], { enabled: active });++ // React to the terminal frame: refetch the outline, drop the busy state.+ useEffect(() => {+ if (!active || !latest || !RUN_ENDED.has(latest.type)) return;+ if (activeRunIdRef.current && latest.runId && latest.runId !== activeRunIdRef.current) return;+ setActive(false);+ activeRunIdRef.current = null;+ if (latest.type === 'complete') {+ getReverseOutline(seriesId).then((o) => setOutline(o)).catch(() => {});+ if (latest.status === 'no-content') toast.warning('Nothing drafted yet — write or import a manuscript first');+ else toast.success(`Reverse outline ready — ${latest.sceneCount || 0} scenes`);+ } else if (latest.type === 'canceled') {+ toast.success('Reverse outline canceled');+ } else {+ toast.error(latest.error || 'Reverse outline failed');+ }+ }, [active, latest, seriesId]);++ const handleGenerate = async (force) => {+ setStarting(true);+ setSelected(null);+ // Await the POST so the run is registered server-side BEFORE the SSE+ // subscription connects — otherwise the progress stream 404s on attach.+ const res = await generateReverseOutline(seriesId, { force }, { silent: true }).catch((err) => {+ toast.error(err.message || 'Failed to start reverse outline');+ return null;+ });+ setStarting(false);+ if (!res?.runId) return;+ activeRunIdRef.current = res.runId;+ setActive(true);+ };++ const handleCancel = () => {+ cancelReverseOutline(seriesId).catch(() => {});+ };++ if (loading) {+ return (+ <div className="h-full flex items-center justify-center text-gray-400">+ <Loader2 className="animate-spin" size={20} />+ </div>+ );+ }++ const scenes = outline?.scenes || [];+ const plotlines = outline?.plotlines || [];+ const hasOutline = outline?.status === 'complete' && scenes.length > 0;+ const busy = active || starting;+ const { rows } = buildPlotlineGrid(scenes, plotlines);++ return (+ <div className="h-full overflow-y-auto p-4 md:p-6">+ <header className="flex flex-wrap items-center gap-2 mb-4">+ <Link+ to={`/pipeline/series/${seriesId}`}+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-400 hover:text-white border border-port-border bg-port-card"+ title="Back to series"+ >+ <ArrowLeft size={12} /> Series+ </Link>+ <h1 className="text-lg font-semibold text-white flex items-center gap-2">+ <Compass size={18} className="text-port-accent" /> Reverse Outline+ </h1>+ {series?.name ? <span className="text-sm text-gray-400 truncate">— {series.name}</span> : null}+ <div className="ml-auto flex items-center gap-2">+ {active ? (+ <button+ type="button"+ onClick={handleCancel}+ className="inline-flex items-center gap-1 px-3 py-2 rounded-lg border border-port-border bg-port-card text-sm text-gray-300 hover:text-white"+ >+ <X size={14} /> Cancel+ </button>+ ) : null}+ <button+ type="button"+ onClick={() => handleGenerate(hasOutline)}+ disabled={busy}+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"+ title={hasOutline ? 'Re-segment the current manuscript' : 'Segment the manuscript into a reverse outline'}+ >+ {busy ? <Loader2 size={14} className="animate-spin" /> : <RefreshCw size={14} />}+ {busy ? 'Generating…' : hasOutline ? 'Regenerate' : 'Generate outline'}+ </button>+ </div>+ </header>++ {outline?.stale && hasOutline ? (+ <div className="mb-4 flex items-center gap-2 px-3 py-2 rounded-lg border border-port-warning/40 bg-port-warning/10 text-port-warning text-sm">+ <AlertTriangle size={14} />+ The manuscript changed since this outline was generated — regenerate to refresh.+ </div>+ ) : null}++ {!hasOutline ? (+ <EmptyState status={outline?.status} active={busy} />+ ) : (+ <div className="flex flex-col gap-4">+ <PlotlineLegend rows={rows} />+ <PlotlineGrid rows={rows} scenes={scenes} selected={selected} onSelect={setSelected} />+ <SceneDetail scene={selected} plotlines={plotlines} seriesId={seriesId} navigate={navigate} />+ <p className="text-xs text-gray-500">+ {scenes.length} scenes · {plotlines.length} plotlines+ {outline?.truncated ? ' · manuscript truncated for analysis (long series)' : ''}+ </p>+ </div>+ )}+ </div>+ );+}++function EmptyState({ status, active }) {+ if (active) {+ return (+ <div className="text-center text-gray-400 py-16">+ <Loader2 className="animate-spin mx-auto mb-3" size={24} />+ Segmenting the manuscript into scenes…+ </div>+ );+ }+ if (status === 'no-content') {+ return (+ <div className="text-center text-gray-400 py-16">+ <BookOpen className="mx-auto mb-3 opacity-40" size={28} />+ Nothing is drafted yet. Write or import a manuscript, then generate the reverse outline.+ </div>+ );+ }+ return (+ <div className="text-center text-gray-400 py-16">+ <Compass className="mx-auto mb-3 opacity-40" size={28} />+ No reverse outline yet. Generate one to map your scenes by plotline.+ </div>+ );+}++function PlotlineLegend({ rows }) {+ return (+ <div className="flex flex-wrap gap-3">+ {rows.map(({ plotline, count }) => (+ <span key={plotline.id} className="inline-flex items-center gap-1.5 text-xs text-gray-300">+ <span className="w-3 h-3 rounded-sm shrink-0" style={{ backgroundColor: plotline.color }} />+ <span className="font-medium">{plotline.label}</span>+ <span className="text-gray-500">· {plotline.kind} · {count}</span>+ </span>+ ))}+ </div>+ );+}++function PlotlineGrid({ rows, scenes, selected, onSelect }) {+ return (+ <div className="overflow-x-auto border border-port-border rounded-lg">+ <table className="border-collapse">+ <thead>+ <tr>+ <th className="sticky left-0 z-10 bg-port-card text-left text-xs text-gray-500 font-normal px-3 py-2 min-w-[10rem]">+ Plotline+ </th>+ {scenes.map((scene) => (+ <th key={scene.id} className="px-0.5 py-2 text-[10px] text-gray-600 font-normal align-bottom">+ {scene.issueNumber != null ? scene.issueNumber : ''}+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {rows.map(({ plotline, cells }) => (+ <tr key={plotline.id} className="border-t border-port-border/50">+ <td className="sticky left-0 z-10 bg-port-card px-3 py-1.5 min-w-[10rem]">+ <span className="inline-flex items-center gap-1.5 text-xs text-gray-300">+ <span className="w-2.5 h-2.5 rounded-sm shrink-0" style={{ backgroundColor: plotline.color }} />+ <span className="truncate max-w-[8rem]" title={plotline.label}>{plotline.label}</span>+ </span>+ </td>+ {cells.map((cell, i) => (+ <td key={scenes[i].id} className="px-0.5 py-1.5 text-center">+ {cell ? (+ <button+ type="button"+ onClick={() => onSelect(cell.scene)}+ title={`${scenes[i].heading || 'Scene'}${cell.role === 'secondary' ? ' (secondary)' : ''}`}+ className={`w-3.5 h-3.5 rounded-full inline-block align-middle transition-transform hover:scale-125 ${selected?.id === cell.scene.id ? 'ring-2 ring-white' : ''}`}+ style={cell.role === 'primary'+ ? { backgroundColor: plotline.color }+ : { boxShadow: `inset 0 0 0 2px ${plotline.color}` }}+ />+ ) : (+ <span className="w-3.5 h-3.5 inline-block align-middle" />+ )}+ </td>+ ))}+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}++function SceneDetail({ scene, plotlines, seriesId, navigate }) {+ if (!scene) {+ return <p className="text-xs text-gray-500">Click a scene marker to see its detail.</p>;+ }+ const plotline = plotlines.find((p) => p.id === scene.plotlineId);+ const componentLabels = ['narrative', 'action', 'dialogue'].filter((k) => scene.components?.[k]);+ return (+ <div className="border border-port-border rounded-lg p-4 bg-port-card flex flex-col gap-2">+ <div className="flex items-center gap-2">+ {plotline ? <span className="w-3 h-3 rounded-sm shrink-0" style={{ backgroundColor: plotline.color }} /> : null}+ <h3 className="text-sm font-semibold text-white">{scene.heading || 'Scene'}</h3>+ <span className="text-xs text-gray-500">+ {plotline?.label || 'Unassigned'}+ {scene.issueNumber != null ? ` · Issue ${scene.issueNumber}` : ''}+ </span>+ {scene.issueNumber != null ? (+ <button+ type="button"+ onClick={() => navigate(`/pipeline/series/${seriesId}/manuscript/${scene.issueNumber}`)}+ className="ml-auto inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-400 hover:text-white border border-port-border"+ title="Open this scene's issue in the manuscript editor"+ >+ <BookOpen size={12} /> Open in editor+ </button>+ ) : null}+ </div>+ {scene.summary ? <p className="text-sm text-gray-300">{scene.summary}</p> : null}+ <div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-gray-500">+ {scene.povCharacter ? <span>POV: <span className="text-gray-300">{scene.povCharacter}</span></span> : null}+ {scene.setting ? <span>Setting: <span className="text-gray-300">{scene.setting}</span></span> : null}+ <span>+ Components: <span className={sceneComponentCount(scene) >= 2 ? 'text-port-success' : 'text-port-warning'}>+ {componentLabels.length ? componentLabels.join(' · ') : 'none detected'}+ </span>+ </span>+ {scene.charactersPresent?.length ? (+ <span>Present: <span className="text-gray-300">{scene.charactersPresent.join(', ')}</span></span>+ ) : null}+ </div>+ {scene.anchorQuote ? <p className="text-xs italic text-gray-500">“{scene.anchorQuote}”</p> : null}+ </div>+ );+}diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsxindex d08acb203e..01d7fa4fad 100644--- a/client/src/pages/PipelineSeries.jsx+++ b/client/src/pages/PipelineSeries.jsx@@ -14,7 +14,7 @@ import { useEffect, useState } from 'react';import { Link, useParams, useNavigate } from 'react-router-dom';import {ArrowLeft, Save, Loader2, Workflow as WorkflowIcon, Globe, NotebookPen,- PanelLeftClose, PanelLeftOpen, Sparkles, BookOpen, FileInput,+ PanelLeftClose, PanelLeftOpen, Sparkles, BookOpen, FileInput, Compass,} from 'lucide-react';import toast from '../components/ui/Toast';import ArcCanvas from '../components/pipeline/ArcCanvas';@@ -188,6 +188,13 @@ export default function PipelineSeries() {><BookOpen size={12} /> Manuscript</Link>+ <Link+ to={`/pipeline/series/${series.id}/reverse-outline`}+ className="ml-2 inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-400 hover:text-white border border-port-border bg-port-card"+ title="Map the drafted manuscript into a color-coded scene-by-plotline reverse outline"+ >+ <Compass size={12} /> Reverse Outline+ </Link><Linkto={buildImporterLink({ universeId: series.universeId, seriesId: series.id })}className="ml-2 inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-400 hover:text-white border border-port-border bg-port-card"diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex 4be72ecb20..47219e9a33 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -595,6 +595,33 @@ export const getSeriesEditorialStatus = (seriesId, options = {}) =>export const pipelineEditorialSseUrl = (seriesId) =>`/api/pipeline/series/${encodeURIComponent(seriesId)}/editorial/analyze/progress`;+// ---- Reverse Outline (scene segmentation + plotline tagging) ----+// The stored outline: { plotlines, scenes, stale, status }. `status:'none'`+// when never generated, `'no-content'` shell while nothing is drafted yet.+export const getReverseOutline = (seriesId, options = {}) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/reverse-outline`, options);++// Kick off a (re)generation. { runId, alreadyRunning, sseUrl } — subscribe via+// pipelineReverseOutlineSseUrl to stream progress, then re-fetch on `complete`.+export const generateReverseOutline = (seriesId, opts = {}, options = {}) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/reverse-outline/generate`, {+ method: 'POST',+ body: JSON.stringify(opts),+ ...options,+ });++export const cancelReverseOutline = (seriesId) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/reverse-outline/generate/cancel`, {+ method: 'POST',+ });++// { active: boolean } — lets a (re)mounting view re-attach to an in-flight run.+export const getReverseOutlineStatus = (seriesId, options = {}) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/reverse-outline/generate/status`, options);++export const pipelineReverseOutlineSseUrl = (seriesId) =>+ `/api/pipeline/series/${encodeURIComponent(seriesId)}/reverse-outline/generate/progress`;+// ---- Series Autopilot (full autonomous mode) ----// Drives a series from its current state to story-ready (+ draft visuals) by// composing every pipeline pass. SSE-backed; gated on the cos autonomy domaindiff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex 0da26433d3..a1c1733930 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -289,6 +289,13 @@"returnsJson": true,"variables": []},+ "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.",+ "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-reverse-outline.md b/data.reference/prompts/stages/pipeline-reverse-outline.mdnew file mode 100644index 0000000000..5e71d9b24a--- /dev/null+++ b/data.reference/prompts/stages/pipeline-reverse-outline.md@@ -0,0 +1,74 @@+# Pipeline — Reverse Outline (scene segmentation + plotline tagging)++You are a developmental editor building a **reverse outline** of an already-drafted manuscript — a scene-by-scene map of what is *actually on the page* (not what was planned), with each scene tagged to the plotline it advances. This is a revision tool: it lets the author see thread cadence, gaps, and tangles at a glance.++You are NOT rewriting or improving the manuscript. You are reading it and reporting its structure.++## Series++- **Title:** {{series.name}}+- **Tone / style:** {{series.styleNotes}}++## Known characters (for POV attribution)++{{knownCharacters}}++## Source manuscript (stitched, in story order)++Each issue/episode is delimited by a `# Issue N — Title (stage)` header.++```+{{manuscript}}+```++## Step 1 — Identify plotlines++Read the whole manuscript and identify the **recurring plotlines / narrative threads** that run through it — the A-plot (main external conflict), B-plots / subplots, romance threads, mystery threads, distinct POV throughlines, or a strong thematic thread. Most works have **2–6** plotlines; never invent more than **10**. A one-off scene that belongs to no recurring thread is fine — tag it to the closest plotline, or to a catch-all you label clearly (e.g. "Standalone / connective tissue").++Give each plotline:+- **`id`** — a short stable token, uppercase letters preferred (`A`, `B`, `ROMANCE`, `MYSTERY`). Must be unique.+- **`label`** — a 2–5 word human name for the thread.+- **`kind`** — one of `main` | `subplot` | `pov` | `thematic` | `other`.++## Step 2 — Segment into scenes++Walk the manuscript top to bottom and break it into **scenes** — a scene is a continuous unit of action in one place/time with a stable POV. A chapter may contain several scenes (a scene break, time jump, or location/POV change starts a new scene). Keep scenes in **reading order**.++For each scene write:+- **`issueNumber`** — the number from the nearest `# Issue N` header above this scene. Required so the scene links back to the right episode.+- **`heading`** — a short noun phrase for the scene's visual/dramatic moment (e.g. `The confession on the pier`).+- **`summary`** — 1–2 sentences on what *happens* in the scene (events, not prose quality).+- **`anchorQuote`** — a short **verbatim** quote (5–12 words) copied exactly from the manuscript at the scene's opening, so the editor can jump to it. Do not paraphrase — copy the text character-for-character.+- **`povCharacter`** — the name of the POV/focal character if clear (match the known-characters list when possible), else `null`.+- **`plotlineId`** — the `id` of the plotline this scene PRIMARILY advances. Must be one of the ids from Step 1.+- **`secondaryPlotlineId`** — a second plotline the scene also touches, or `null`.+- **`components`** — which of the three prose modes are materially present in the scene, as booleans: `{ "narrative": bool, "action": bool, "dialogue": bool }` (narrative = description/interiority/summary, action = physical events, dialogue = spoken lines). A balanced scene has at least two of the three.+- **`setting`** — a short place/time phrase (e.g. `Harbor pier, dusk`), or empty string.+- **`charactersPresent`** — names of characters on-page in the scene (prefer known-character names).++## Output contract++Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:++```json+{+ "plotlines": [+ { "id": "A", "label": "The heist", "kind": "main" },+ { "id": "B", "label": "Mara and Dov", "kind": "subplot" }+ ],+ "scenes": [+ {+ "issueNumber": 1,+ "heading": "string",+ "summary": "string",+ "anchorQuote": "verbatim opening words",+ "povCharacter": "Mara",+ "plotlineId": "A",+ "secondaryPlotlineId": null,+ "components": { "narrative": true, "action": false, "dialogue": true },+ "setting": "string",+ "charactersPresent": ["Mara", "Dov"]+ }+ ]+}+```diff --git a/scripts/migrations/093-reverse-outline-stage.js b/scripts/migrations/093-reverse-outline-stage.jsnew file mode 100644index 0000000000..d9059092bf--- /dev/null+++ b/scripts/migrations/093-reverse-outline-stage.js@@ -0,0 +1,75 @@+/**+ * Seed the `pipeline-reverse-outline` stage into existing installs (#1286).+ *+ * Mirrors `092-editorial-info-dumping-stage.js`: copies the `.md` template from+ * `data.reference/prompts/stages/` and merges the 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 Reverse Outline stage+ * unseeded and `buildPrompt('pipeline-reverse-outline')` would throw "Stage not+ * found" the first time a user generates a reverse outline.+ */++import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';+import { dirname, join } from 'path';++const FILENAME = 'pipeline-reverse-outline.md';+const STAGE_KEY = 'pipeline-reverse-outline';++export default {+ async up({ rootDir }) {+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');+ await mkdir(stagesDir, { recursive: true });++ const dataPath = join(stagesDir, FILENAME);+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', FILENAME);++ const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);+ if (exists) {+ console.log(`📝 pipeline-reverse-outline prompt: already present`);+ } else {+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);+ if (!sampleExists) {+ console.warn(`⚠️ pipeline-reverse-outline: sample missing for ${FILENAME} — skipping copy`);+ } else {+ try {+ await copyFile(samplePath, dataPath);+ console.log(`✅ seeded ${FILENAME}`);+ } catch (err) {+ console.warn(`⚠️ pipeline-reverse-outline: copy failed for ${FILENAME}: ${err.message}`);+ }+ }+ }++ const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');+ const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');+ const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);+ if (!sampleConfigExists) {+ console.warn('⚠️ pipeline-reverse-outline: data.reference stage-config.json missing — cannot resolve entry; skipping config write');+ return;+ }+ try {+ const sample = JSON.parse(await readFile(sampleConfigPath, 'utf8'));+ const installedExists = await access(installedConfigPath, constants.F_OK).then(() => true, () => false);+ const installed = installedExists+ ? JSON.parse(await readFile(installedConfigPath, 'utf8'))+ : { stages: {} };+ installed.stages = installed.stages || {};+ if (installed.stages[STAGE_KEY]) {+ console.log(`📝 pipeline-reverse-outline stage-config: already present`);+ return;+ }+ if (!sample?.stages?.[STAGE_KEY]) {+ console.warn(`⚠️ pipeline-reverse-outline: sample stage-config missing ${STAGE_KEY} — skipping`);+ return;+ }+ installed.stages[STAGE_KEY] = sample.stages[STAGE_KEY];+ await mkdir(dirname(installedConfigPath), { recursive: true });+ await writeFile(installedConfigPath, JSON.stringify(installed, null, 2) + '\n', 'utf8');+ const action = installedExists ? 'merged' : 'created';+ console.log(`📝 pipeline-reverse-outline stage-config (${action}): 1 added`);+ } catch (err) {+ console.warn(`⚠️ pipeline-reverse-outline: stage-config merge failed: ${err.message}`);+ }+ },+};diff --git a/server/routes/pipeline/index.js b/server/routes/pipeline/index.jsindex cdd10ed45c..aa4a369643 100644--- a/server/routes/pipeline/index.js+++ b/server/routes/pipeline/index.js@@ -26,6 +26,10 @@* GET /series/:id/autopilot/status → { autopilot, active }* GET /issues/:id/canon-readiness → { referenced, none, thin, ready }* GET /series/:id/canon-readiness → { ready, issues, blockingIssues, undescribed }+ * GET /series/:id/reverse-outline → { plotlines, scenes, stale, status }+ * POST /series/:id/reverse-outline/generate → { runId, alreadyRunning, sseUrl }+ * GET /series/:id/reverse-outline/generate/progress → SSE (text/event-stream)+ * POST /series/:id/reverse-outline/generate/cancel → { canceled }** Assembled from domain sub-routers (mirrors the cos.js pattern). Mount* order preserves the original single-file registration order; the only@@ -42,6 +46,7 @@ import manuscriptRoutes from './manuscript.js';import coverRoutes from './covers.js';import issueRoutes from './issues.js';import editorialRoutes from './editorial.js';+import reverseOutlineRoutes from './reverseOutline.js';import autopilotRoutes from './autopilot.js';import canonRoutes from './canon.js';@@ -54,6 +59,7 @@ router.use(manuscriptRoutes);router.use(coverRoutes);router.use(issueRoutes);router.use(editorialRoutes);+router.use(reverseOutlineRoutes);router.use(autopilotRoutes);router.use(canonRoutes);diff --git a/server/routes/pipeline/reverseOutline.js b/server/routes/pipeline/reverseOutline.jsnew file mode 100644index 0000000000..292d068059--- /dev/null+++ b/server/routes/pipeline/reverseOutline.js@@ -0,0 +1,59 @@+/**+ * Pipeline reverse-outline routes (#1286) — scene segmentation + plotline+ * tagging for a series' drafted manuscript. Read the stored outline, kick off a+ * (re)generation with SSE progress, probe/cancel an in-flight run.+ */++import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler, ServerError } from '../../lib/errorHandler.js';+import { validateRequest } from '../../lib/validation.js';+import * as seriesSvc from '../../services/pipeline/series.js';+import * as reverseOutline from '../../services/pipeline/reverseOutline.js';+import { mapServiceError } from './shared.js';++const router = Router();++// Generation params — provider/model optional (falls through to the active or+// stage-pinned provider); `force` re-segments even when the manuscript is+// unchanged. Mirrors the editorial-analyze schema.+const reverseOutlineGenerateSchema = z.object({+ providerId: z.string().trim().max(80).optional(),+ model: z.string().trim().max(200).optional(),+ force: z.boolean().optional(),+});++// The stored outline (scenes + plotlines) with a `stale` flag.+router.get('/series/:id/reverse-outline', asyncHandler(async (req, res) => {+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });+ res.json(await reverseOutline.getReverseOutline(req.params.id));+}));++// (Re)generate — batch over the whole manuscript, progress via SSE.+router.post('/series/:id/reverse-outline/generate', asyncHandler(async (req, res) => {+ const body = validateRequest(reverseOutlineGenerateSchema, req.body ?? {});+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });+ const result = reverseOutline.startReverseOutlineRun(req.params.id, body);+ res.json({+ ...result,+ sseUrl: `/api/pipeline/series/${req.params.id}/reverse-outline/generate/progress`,+ });+}));++router.get('/series/:id/reverse-outline/generate/progress', (req, res) => {+ const attached = reverseOutline.attachClient(req.params.id, res);+ if (!attached) {+ throw new ServerError('No active reverse-outline 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/reverse-outline/generate/status', (req, res) => {+ res.json({ active: reverseOutline.isReverseOutlineActive(req.params.id) });+});++router.post('/series/:id/reverse-outline/generate/cancel', asyncHandler(async (req, res) => {+ res.json({ canceled: reverseOutline.cancelReverseOutline(req.params.id) });+}));++export default router;diff --git a/server/services/pipeline/reverseOutline.js b/server/services/pipeline/reverseOutline.jsnew file mode 100644index 0000000000..4a0e42bd58--- /dev/null+++ b/server/services/pipeline/reverseOutline.js@@ -0,0 +1,382 @@+/**+ * Pipeline — Reverse Outline (#1286).+ *+ * Generates a scene-by-scene map of the *drafted* manuscript — what is actually+ * on the page — with each scene tagged to the plotline it advances (A-plot,+ * subplots, POV threads). This is the canonical **scene-segmentation producer**:+ * other editorial checks (scene-balance, POV-justification, cliffhanger, arc+ * transitions) read the cached segmentation via `getSceneSegmentation` instead+ * of re-segmenting.+ *+ * Stored as a sibling of the series record at+ * `data/pipeline-series/{id}/reverse-outline.json` (same pattern as+ * `manuscript-review.json`) so it travels with the series folder without+ * bloating the LWW-merged series `index.json`. A `sourceContentHash` pins the+ * analyzed manuscript so the UI flags the outline as stale once the draft+ * changes. Writes serialize on a per-series tail (single tail per shared file,+ * per CLAUDE.md).+ *+ * The SSE wrapper at the bottom mirrors editorial/checkRunner.js: a single+ * in-memory runs map keyed by seriesId via lib/sseUtils.js.+ */++import { join } from 'path';+import { createHash } from 'crypto';+import { atomicWrite, readJSONFile } from '../../lib/fileUtils.js';+import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';+import { createSseRunner } from '../../lib/sseUtils.js';+import { runStagedLLM, resolveStageContext } from '../../lib/stageRunner.js';+import { usableInputTokens, estimateTokens, CHARS_PER_TOKEN } from '../../lib/contextBudget.js';+import { seriesStore, getSeries } from './series.js';+import { getSeriesCanon } from './seriesCanon.js';+import { collectManuscriptSections, sectionsCorpus } from './arcPlanner.js';++const STAGE = 'pipeline-reverse-outline';++// Storage-layout version for the outline document. Bump + migrate if the scene+// shape changes in a way an older reader can't tolerate.+const SCHEMA_VERSION = 1;++const OUTLINE_FILE = 'reverse-outline.json';+const outlinePath = (seriesId) => join(seriesStore().recordDir(seriesId), OUTLINE_FILE);++// Defensive caps on LLM output — never trust raw model JSON.+const MAX_PLOTLINES = 10;+const MAX_SCENES = 600;+const MAX_CHARS_PRESENT = 24;+const LABEL_MAX = 120;+const SUMMARY_MAX = 600;+const ANCHOR_MAX = 240;+const NAME_MAX = 80;+const SETTING_MAX = 120;+const PLOTLINE_ID_MAX = 40;++// Floor on manuscript chars sent to the model — scaled UP to the target model's+// context window in generateReverseOutline (mirrors editorialAnalysis), so a+// big-context model segments the whole manuscript rather than a 60K slice.+const CONTENT_MAX = 60_000;+const OUTLINE_OUTPUT_RESERVE_TOKENS = 6_000;++const PLOTLINE_KINDS = Object.freeze(['main', 'subplot', 'pov', 'thematic', 'other']);++// Stable plotline color palette — assigned by plotline index server-side rather+// than trusting model-supplied colors, so colors stay consistent across re-runs+// and the view never renders an unreadable/duplicate hue.+const PLOTLINE_COLORS = Object.freeze([+ '#3b82f6', // accent blue (main)+ '#ef4444', // red+ '#22c55e', // green+ '#f59e0b', // amber+ '#a855f7', // purple+ '#ec4899', // pink+ '#14b8a6', // teal+ '#eab308', // yellow+ '#6366f1', // indigo+ '#f97316', // orange+]);+const UNASSIGNED_PLOTLINE = Object.freeze({ id: '_unassigned', label: 'Unassigned', kind: 'other', color: '#6b7280' });++const nowIso = () => new Date().toISOString();+const clampStr = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');+const colorForIndex = (i) => PLOTLINE_COLORS[i % PLOTLINE_COLORS.length];++// Content hash — pins the analyzed manuscript so a later edit flips the outline+// to `stale`. One-liner matching editorialAnalysis.contentHash.+const contentHash = (text) => createHash('sha256').update(text || '').digest('hex');++// Defense-in-depth: refuse path-traversal-shaped ids before they reach the+// on-disk outline path. Series ids are `ser-<uuid>` — restrict to a safe charset.+function assertValidSeriesId(id) {+ if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(id)) {+ throw new Error(`Invalid series id: ${id}`);+ }+}++// ---------- per-series write tail ----------++const outlineQueues = new Map();+function queueOutlineWrite(seriesId, fn) {+ const key = typeof seriesId === 'string' && seriesId ? seriesId : '__unknown__';+ let q = outlineQueues.get(key);+ if (!q) { q = createFileWriteQueue(); outlineQueues.set(key, q); }+ return q(fn);+}++// ---------- sanitize LLM output ----------++function sanitizePlotlines(rawList) {+ const seen = new Set();+ const out = [];+ for (const raw of Array.isArray(rawList) ? rawList : []) {+ if (out.length >= MAX_PLOTLINES) break;+ if (!raw || typeof raw !== 'object') continue;+ const id = clampStr(raw.id, PLOTLINE_ID_MAX);+ const label = clampStr(raw.label, LABEL_MAX);+ if (!id || !label || seen.has(id)) continue;+ seen.add(id);+ out.push({+ id,+ label,+ kind: PLOTLINE_KINDS.includes(raw.kind) ? raw.kind : 'other',+ color: colorForIndex(out.length),+ });+ }+ return out;+}++function sanitizeComponents(raw) {+ const c = raw && typeof raw === 'object' ? raw : {};+ return {+ narrative: c.narrative === true,+ action: c.action === true,+ dialogue: c.dialogue === true,+ };+}++// Shape one scene. `byNumber` resolves issueId/title from the model-reported+// issueNumber; `plotlineIds` is the valid set (unknown ids fall back to the+// synthetic '_unassigned' plotline so the grid never references a missing row).+function sanitizeScene(raw, idx, { byNumber, plotlineIds }) {+ if (!raw || typeof raw !== 'object') return null;+ const summary = clampStr(raw.summary, SUMMARY_MAX);+ const heading = clampStr(raw.heading, LABEL_MAX);+ if (!summary && !heading) return null;+ const issueNumber = Number.isInteger(raw.issueNumber) ? raw.issueNumber : null;+ const section = issueNumber != null ? byNumber.get(issueNumber) : null;+ const primary = clampStr(raw.plotlineId, PLOTLINE_ID_MAX);+ const secondary = clampStr(raw.secondaryPlotlineId, PLOTLINE_ID_MAX);+ return {+ id: `scene-${String(idx + 1).padStart(3, '0')}`,+ sequence: idx,+ issueNumber,+ issueId: section ? section.issueId : null,+ issueTitle: section ? section.title : '',+ heading: heading || summary.slice(0, LABEL_MAX),+ summary,+ anchorQuote: clampStr(raw.anchorQuote, ANCHOR_MAX),+ povCharacter: clampStr(raw.povCharacter, NAME_MAX) || null,+ plotlineId: plotlineIds.has(primary) ? primary : UNASSIGNED_PLOTLINE.id,+ secondaryPlotlineId: secondary && plotlineIds.has(secondary) && secondary !== primary ? secondary : null,+ components: sanitizeComponents(raw.components),+ setting: clampStr(raw.setting, SETTING_MAX),+ charactersPresent: Array.isArray(raw.charactersPresent)+ ? raw.charactersPresent.map((n) => clampStr(n, NAME_MAX)).filter(Boolean).slice(0, MAX_CHARS_PRESENT)+ : [],+ };+}++/**+ * Shape a raw model response into a stored outline body. Exported via __testing.+ * `byNumber` maps issueNumber → manuscript section (for issueId backfill).+ */+function sanitizeOutline(parsed, { byNumber = new Map() } = {}) {+ const p = parsed && typeof parsed === 'object' ? parsed : {};+ const plotlines = sanitizePlotlines(p.plotlines);+ const plotlineIds = new Set(plotlines.map((pl) => pl.id));+ const scenes = (Array.isArray(p.scenes) ? p.scenes : [])+ .slice(0, MAX_SCENES)+ .map((raw, idx) => sanitizeScene(raw, idx, { byNumber, plotlineIds }))+ .filter(Boolean);+ // Append the synthetic catch-all only when a scene actually landed on it, so a+ // clean run doesn't show an empty "Unassigned" row.+ if (scenes.some((s) => s.plotlineId === UNASSIGNED_PLOTLINE.id)) {+ plotlines.push({ ...UNASSIGNED_PLOTLINE });+ }+ return { plotlines, scenes };+}++// ---------- storage ----------++const emptyOutline = () => ({ schemaVersion: SCHEMA_VERSION, status: 'none', plotlines: [], scenes: [] });++async function readOutline(seriesId) {+ // `null` = file absent (distinct from a present-but-empty outline).+ const raw = await readJSONFile(outlinePath(seriesId), null);+ if (raw == null || typeof raw !== 'object') return null;+ return raw;+}++async function writeOutline(seriesId, outline) {+ await atomicWrite(outlinePath(seriesId), outline);+}++// ---------- manuscript corpus ----------++// Stitch the drafted manuscript into one corpus + the number→section map used+// for issueId backfill and staleness. Returns `{ corpus, byNumber, sections }`.+async function buildManuscriptCorpus(seriesId) {+ const sections = await collectManuscriptSections(seriesId);+ const byNumber = new Map(sections.map((s) => [s.number, s]));+ return { corpus: sectionsCorpus(sections), byNumber, sections };+}++// ---------- generation ----------++/**+ * Generate (or refresh) the reverse outline for a series. Returns the stored+ * outline, a `{ status:'no-content' }` marker when nothing is drafted yet, or+ * the cached outline when the manuscript is unchanged and `!force`.+ *+ * @param {string} seriesId+ * @param {object} [options]+ * - providerId / model — forwarded to the LLM stage (autopilot/manual override)+ * - force — re-segment even when the manuscript hash is unchanged+ * - signal — AbortSignal checked before the persist+ */+export async function generateReverseOutline(seriesId, { providerId, model, force = false, signal } = {}) {+ assertValidSeriesId(seriesId);+ const { corpus, byNumber } = await buildManuscriptCorpus(seriesId);+ if (!corpus.trim()) return { seriesId, status: 'no-content' };++ const hash = contentHash(corpus);+ const existing = await readOutline(seriesId);+ if (!force && existing && existing.status === 'complete' && existing.sourceContentHash === hash) {+ return { ...existing, stale: false, cached: true };+ }++ const series = await getSeries(seriesId).catch(() => null);+ const canon = series ? await getSeriesCanon(series).catch(() => ({ characters: [] })) : { characters: [] };+ const characterNames = (canon.characters || []).map((c) => c?.name).filter(Boolean).slice(0, 60);++ // Scale the content cap to the model's context window — never below CONTENT_MAX.+ const { contextWindow } = await resolveStageContext(STAGE, { providerOverride: providerId, modelOverride: model });+ const overheadTokens = 1_500 + estimateTokens([series?.name || '', series?.styleNotes || '', characterNames.join(', ')].join(' '));+ const budgetChars = usableInputTokens({+ contextWindow,+ overheadTokens,+ outputReserveTokens: OUTLINE_OUTPUT_RESERVE_TOKENS,+ }) * CHARS_PER_TOKEN;+ const contentMax = Math.max(CONTENT_MAX, budgetChars);+ const truncated = corpus.length > contentMax;++ const vars = {+ series: { name: series?.name || 'Untitled series', styleNotes: series?.styleNotes || '' },+ knownCharacters: characterNames.length ? characterNames.join(', ') : '(none on record)',+ manuscript: truncated+ ? `${corpus.slice(0, contentMax)}\n\n[manuscript truncated for analysis — ${corpus.length} chars total]`+ : corpus,+ };++ const result = await runStagedLLM(STAGE, vars, {+ returnsJson: true,+ providerOverride: providerId,+ modelOverride: model,+ source: 'pipeline-reverse-outline',+ });++ if (signal?.aborted) return { seriesId, status: 'canceled' };++ const body = sanitizeOutline(result.content, { byNumber });+ const outline = {+ seriesId,+ schemaVersion: SCHEMA_VERSION,+ status: 'complete',+ sourceContentHash: hash,+ truncated,+ providerId: result.providerId,+ model: result.model,+ runId: result.runId,+ generatedAt: nowIso(),+ ...body,+ };+ await queueOutlineWrite(seriesId, () => writeOutline(seriesId, outline));+ console.log(`🧭 reverse outline: series=${String(seriesId).slice(0, 12)} plotlines=${body.plotlines.length} scenes=${body.scenes.length}${truncated ? ' (truncated)' : ''}`);+ return { ...outline, stale: false };+}++// Single source of truth for staleness — the stored hash no longer matches the+// current manuscript (or the manuscript was cleared after generation). A legacy+// outline with no stored hash is treated as not-stale (can't tell).+function isOutlineStale(outline, corpus) {+ if (!outline || outline.status !== 'complete') return false;+ if (!corpus.trim()) return true; // outlined, but the draft was cleared since+ if (!outline.sourceContentHash) return false;+ return outline.sourceContentHash !== contentHash(corpus);+}++/**+ * Read the stored reverse outline with a `stale` flag. Returns a+ * `{ status:'none' }` shell (never null) when one has never been generated, so+ * the route/UI has a consistent shape to render.+ */+export async function getReverseOutline(seriesId) {+ assertValidSeriesId(seriesId);+ const outline = await readOutline(seriesId);+ if (!outline) return { ...emptyOutline(), seriesId };+ const { corpus } = await buildManuscriptCorpus(seriesId);+ return { ...outline, seriesId, stale: isOutlineStale(outline, corpus) };+}++/**+ * Canonical scene-segmentation accessor for downstream editorial checks+ * (scene-balance, POV-justification, cliffhanger, arc transitions). Returns the+ * stored scenes + plotlines (empty when never generated) plus a `stale` flag so+ * a consumer can decide whether to trust or regenerate. Build the segmentation+ * once here; other checks read it rather than re-segmenting.+ */+export async function getSceneSegmentation(seriesId) {+ const outline = await getReverseOutline(seriesId);+ return {+ seriesId,+ scenes: outline.scenes || [],+ plotlines: outline.plotlines || [],+ status: outline.status || 'none',+ stale: outline.stale === true,+ };+}++// ---------------------------------------------------------------------------+// SSE run-tracking — shared lifecycle via createSseRunner (server/lib/sseUtils.js),+// the same factory backing manuscriptCompletenessRunner + editorial/checkRunner.+// ---------------------------------------------------------------------------++const runner = createSseRunner({ logLabel: 'reverse outline' });++export function isReverseOutlineActive(seriesId) {+ return runner.isActive(seriesId);+}++export function attachClient(seriesId, res) {+ return runner.attachClient(seriesId, res);+}++export function cancelReverseOutline(seriesId) {+ return runner.cancel(seriesId);+}++/**+ * Kick off a streamed reverse-outline generation. Returns the runId+ * immediately; progress + the terminal frame land via SSE. Re-calling while a+ * run is in flight resolves to the existing runId.+ */+export function startReverseOutlineRun(seriesId, options = {}) {+ return runner.start(seriesId, async ({ runId, signal, record, broadcast }) => {+ broadcast({ type: 'start', runId });+ const result = await generateReverseOutline(seriesId, {+ providerId: options.providerId,+ model: options.model,+ force: options.force,+ signal,+ });+ if (record.cancelRequested || result.status === 'canceled') {+ broadcast({ type: 'canceled', runId, canceledAt: nowIso() });+ console.log(`🧭 reverse outline canceled — series=${String(seriesId).slice(0, 12)}`);+ return;+ }+ if (result.status === 'no-content') {+ broadcast({ type: 'complete', runId, status: 'no-content', sceneCount: 0, completedAt: nowIso() });+ return;+ }+ broadcast({+ type: 'complete',+ runId,+ status: 'complete',+ sceneCount: result.scenes?.length || 0,+ plotlineCount: result.plotlines?.length || 0,+ completedAt: nowIso(),+ });+ });+}++// Export internals for tests.+export const __testing = { sanitizeOutline, sanitizePlotlines, sanitizeScene, isOutlineStale, contentHash, runs: runner.runs };diff --git a/server/services/pipeline/reverseOutline.test.js b/server/services/pipeline/reverseOutline.test.jsnew file mode 100644index 0000000000..39236a7d20--- /dev/null+++ b/server/services/pipeline/reverseOutline.test.js@@ -0,0 +1,180 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// In-memory outline store mirroring atomicWrite(object) + readJSONFile(object|fallback).+const fileStore = new Map();++vi.mock('../../lib/fileUtils.js', () => ({+ atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, JSON.parse(JSON.stringify(data))); }),+ readJSONFile: vi.fn(async (path, fallback = null) => (fileStore.has(path) ? fileStore.get(path) : fallback)),+}));++// runStagedLLM returns the next queued canned outline.+const llmQueue = [];+const llmCalls = [];+vi.mock('../../lib/stageRunner.js', () => ({+ runStagedLLM: vi.fn(async (stage, vars) => {+ llmCalls.push({ stage, vars });+ const content = llmQueue.shift();+ return { content, model: 'mock-model', providerId: 'mock-provider', runId: 'run-1' };+ }),+ // Large window so the content cap stays at its CONTENT_MAX floor in tests.+ resolveStageContext: vi.fn(async () => ({ provider: { id: 'mock-provider' }, model: 'mock-model', contextWindow: 1_000_000 })),+}));++vi.mock('../../lib/contextBudget.js', () => ({+ usableInputTokens: vi.fn(() => 100_000),+ estimateTokens: vi.fn(() => 100),+ CHARS_PER_TOKEN: 4,+}));++// Series store (recordDir for the sibling path) + getSeries.+const seriesFixture = new Map();+vi.mock('./series.js', () => ({+ seriesStore: () => ({ recordDir: (id) => `/mock/series/${id}` }),+ getSeries: vi.fn(async (id) => seriesFixture.get(id) || null),+}));++vi.mock('./seriesCanon.js', () => ({+ getSeriesCanon: vi.fn(async () => ({ characters: [{ name: 'Ada' }, { name: 'Bly' }] })),+}));++// Manuscript corpus — driven per-test.+let sectionsFixture = [];+vi.mock('./arcPlanner.js', () => ({+ collectManuscriptSections: vi.fn(async () => sectionsFixture),+ sectionsCorpus: (sections) => sections.map((s) => `# Issue ${s.number}\n\n${s.content}`).join('\n\n---\n\n'),+}));++const svc = await import('./reverseOutline.js');++const SERIES_ID = 'ser-abc';++function cannedOutline() {+ return {+ plotlines: [+ { id: 'A', label: 'The heist', kind: 'main' },+ { id: 'B', label: 'Mara & Dov', kind: 'subplot' },+ { id: 'A', label: 'dup id dropped', kind: 'main' }, // duplicate id+ ],+ scenes: [+ {+ issueNumber: 1, heading: 'Opening', summary: 'They meet.', anchorQuote: 'It was dusk',+ povCharacter: 'Ada', plotlineId: 'A', secondaryPlotlineId: 'B',+ components: { narrative: true, action: false, dialogue: true }, setting: 'Pier', charactersPresent: ['Ada', 'Dov'],+ },+ { issueNumber: 1, summary: 'Side beat.', plotlineId: 'Z' }, // unknown plotline → _unassigned+ { nonsense: true }, // dropped (no heading/summary)+ ],+ };+}++beforeEach(() => {+ fileStore.clear();+ llmQueue.length = 0;+ llmCalls.length = 0;+ sectionsFixture = [{ issueId: 'iss-1', number: 1, title: 'One', stageId: 'prose', content: 'It was dusk on the pier.' }];+ seriesFixture.clear();+ seriesFixture.set(SERIES_ID, { id: SERIES_ID, name: 'Test Series', styleNotes: 'noir' });+});++describe('generateReverseOutline', () => {+ it('segments, assigns plotline colors, backfills issueId, and routes unknown plotlines to _unassigned', async () => {+ llmQueue.push(cannedOutline());+ const out = await svc.generateReverseOutline(SERIES_ID, {});++ expect(out.status).toBe('complete');+ expect(out.sourceContentHash).toBeTruthy();++ // Duplicate plotline id dropped; colors assigned by index; _unassigned appended.+ const ids = out.plotlines.map((p) => p.id);+ expect(ids).toContain('A');+ expect(ids).toContain('B');+ expect(ids).toContain('_unassigned');+ expect(out.plotlines.find((p) => p.id === 'A').color).toBeTruthy();+ expect(out.plotlines.find((p) => p.id === 'A').color).not.toBe(out.plotlines.find((p) => p.id === 'B').color);++ // Two valid scenes survive; nonsense dropped.+ expect(out.scenes).toHaveLength(2);+ expect(out.scenes[0].id).toBe('scene-001');+ expect(out.scenes[0].issueId).toBe('iss-1'); // backfilled from issueNumber+ expect(out.scenes[0].secondaryPlotlineId).toBe('B');+ expect(out.scenes[1].plotlineId).toBe('_unassigned'); // unknown 'Z' remapped+ });++ it('returns a no-content marker when nothing is drafted', async () => {+ sectionsFixture = [];+ const out = await svc.generateReverseOutline(SERIES_ID, {});+ expect(out.status).toBe('no-content');+ expect(llmCalls).toHaveLength(0);+ });++ it('returns the cached outline when the manuscript is unchanged and not forced', async () => {+ llmQueue.push(cannedOutline());+ await svc.generateReverseOutline(SERIES_ID, {});+ const again = await svc.generateReverseOutline(SERIES_ID, {});+ expect(again.cached).toBe(true);+ expect(llmCalls).toHaveLength(1); // LLM not re-invoked+ });++ it('re-segments when forced even if the manuscript is unchanged', async () => {+ llmQueue.push(cannedOutline(), cannedOutline());+ await svc.generateReverseOutline(SERIES_ID, {});+ await svc.generateReverseOutline(SERIES_ID, { force: true });+ expect(llmCalls).toHaveLength(2);+ });+});++describe('getReverseOutline + staleness', () => {+ it('returns a none shell when never generated', async () => {+ const out = await svc.getReverseOutline(SERIES_ID);+ expect(out.status).toBe('none');+ expect(out.scenes).toEqual([]);+ });++ it('flags stale when the manuscript changes after generation', async () => {+ llmQueue.push(cannedOutline());+ await svc.generateReverseOutline(SERIES_ID, {});++ const fresh = await svc.getReverseOutline(SERIES_ID);+ expect(fresh.stale).toBe(false);++ sectionsFixture = [{ issueId: 'iss-1', number: 1, title: 'One', stageId: 'prose', content: 'A completely rewritten draft.' }];+ const stale = await svc.getReverseOutline(SERIES_ID);+ expect(stale.stale).toBe(true);+ });+});++describe('getSceneSegmentation', () => {+ it('exposes the stored scenes + plotlines for downstream checks', async () => {+ llmQueue.push(cannedOutline());+ await svc.generateReverseOutline(SERIES_ID, {});+ const seg = await svc.getSceneSegmentation(SERIES_ID);+ expect(seg.status).toBe('complete');+ expect(seg.scenes).toHaveLength(2);+ expect(seg.plotlines.length).toBeGreaterThan(0);+ });++ it('returns empty when never generated', async () => {+ const seg = await svc.getSceneSegmentation(SERIES_ID);+ expect(seg.status).toBe('none');+ expect(seg.scenes).toEqual([]);+ });+});++describe('sanitizeOutline (pure)', () => {+ const { sanitizeOutline } = svc.__testing;++ it('caps plotlines and clamps strings', () => {+ const many = Array.from({ length: 20 }, (_, i) => ({ id: `P${i}`, label: `Plot ${i}`, kind: 'main' }));+ const { plotlines } = sanitizeOutline({ plotlines: many, scenes: [] });+ expect(plotlines.length).toBeLessThanOrEqual(10);+ });++ it('does not append _unassigned when every scene maps cleanly', () => {+ const { plotlines } = sanitizeOutline({+ plotlines: [{ id: 'A', label: 'Main', kind: 'main' }],+ scenes: [{ summary: 'x', plotlineId: 'A' }],+ });+ expect(plotlines.map((p) => p.id)).not.toContain('_unassigned');+ });+});