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
Add manuscript editor with inline editorial comments, AI fixes, multi-format editing, and version history
[._.]/ Adam Eivyff232377bf55
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 2feb098b09..3ed54beeaf 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -18,6 +18,7 @@## Added+- **[manuscript-editor] New full-page Manuscript Editor with inline editorial comments, AI fixes, multi-format editing, and version history.** "Finish the draft" findings are no longer a flat advisory list — they now **persist** as Word-style comments anchored to exact spots in the manuscript, so they survive a reload and stay until you accept, dismiss, or regenerate them (re-running augments the list without wiping in-progress work). A new full-bleed editor (`/pipeline/series/:id/manuscript`, reachable from the "Finish the draft" results and the series bible) shows the whole series manuscript in story order, one editable section per issue, with the comments in a sidebar. Click a comment to jump to (and highlight) its anchor; **Generate fix** proposes a surgical `find`/`replace` edit you can modify before **Accept**ing it into the manuscript, or **Dismiss**. Every section is also freely editable. **Versioning:** every accepted fix and every saved free-text edit snapshots the prior text into the stage's history — each section shows a "History (N)" panel with one-click **Revert** to any prior version (reversible), including the original imported text. The editor **spans all three formats** — a Comic / Teleplay / Prose switcher loads the full story in any format, and you can pin the **primary manuscript format** (the source of truth the others are generated from) in the series bible or from the editor. The completeness pass now anchors each finding with a structured `issueNumber` + verbatim `anchorQuote` (migration 056 upgrades the `pipeline-manuscript-completeness` prompt on existing installs; customized prompts are left intact and warned). New routes under `…/series/:id/manuscript`, a `pipeline-manuscript-fix` prompt, a per-series `manuscript-review.json`, a `primaryManuscriptType` series field, and an opt-in `snapshotPrior` on the stage-write path so edits are versioned without faking a run. Also fixes a bug where switching series left the prior series' "Finish the draft" (and verify/derive) results rendered on the new one.- **[pipeline-derive-from-manuscript + manuscript-completeness] Reconstruct a series arc/bible from an imported manuscript, and get editor feedback on what's left to finish.** Two new series-level actions on the Arc Canvas. **Derive from manuscript** reads the comic-script / prose / teleplay you already drafted across the issues and proposes — in a review-and-confirm preview — a series arc, the bible fields (logline, premise, issue-count target), and a single graphic-novel volume holding every issue as a chapter/act; confirming collapses any stray extra volumes into one, reassigns the issues, fills the bible, and seeds each issue's synopsis so the synopsis-level **Verify Arc** pass becomes useful — without ever touching your verbatim scripts. (Reuses the existing `importer-arc-extract` back-derivation that previously lived only inside the Story Builder; `collectIssueSourceText` is now shared.) **Finish the draft** is a separate developmental-editor pass that reads the *actual drafted manuscript* (not synopses, which Verify Arc/Volume are limited to) and returns categorized suggestions — missing content, arc gaps, character-development gaps, pacing, continuity — for rounding out a near-complete draft before you generate every per-issue stage. New routes `POST /api/pipeline/series/:id/arc/derive-from-manuscript(/commit)` and `…/manuscript/completeness`, a new `pipeline-manuscript-completeness` stage prompt (auto-installed via the stage-config merge — no migration), and Zod-validated inputs.- **[importer-single-volume-choice] The importer lets you choose how a finished work is split — one graphic-novel volume of chapters, or a multi-volume series — and no longer leaves the bible blank.** Importing a comic script used to create the LLM's multi-volume breakdown (often 3–4 "volumes") regardless of intent, with no choice offered, *and* wrote only `series.arc` + seasons — leaving the bible sidebar (logline, premise, issue-count target) empty after a successful import. The Review step now has a **Structure** control: comic scripts default to a single volume holding every issue as a chapter/act (the extracted volume descriptions fold into the issue synopses — "the volume descriptions read better as issue descriptions"), with one click to switch back to multi-volume. On commit, the bible's logline / premise / issue-count are populated from the extracted arc + issue count (additive imports only fill empty fields; Replace overwrites).- **[catalog-character-sheet-enrichment] Catalog and Universe Builder are now the same durable record, and the catalog's color palette / stats / aliases are editable inline.** Editing a character/place/object on the Catalog detail page and editing it on the Universe Builder canon surface used to write two parallel copies (the `catalog_ingredients` row and the embedded `universe.characters[]` entry) that silently drifted apart. They're now kept in lockstep by a bidirectional projection (`server/services/catalogCanonProjection.js`): a Catalog edit fans into every linked universe's embedded canon entry (best-effort, after the response), and a canon edit projects back into the catalog row synchronously inside `updateUniverse` so the embedded copy is a never-lagging cache of the one store of record. Conflicts resolve last-writer-wins on `updatedAt`; an in-flight re-entrancy guard breaks the catalog→canon→catalog loop so each side is written exactly once per edit. A one-time boot reconciliation (`reconcileCanonCatalog.js`, marker `data/catalog-canon-reconcile.applied.json`, registered as migration `055`) collapses any pre-existing divergence on first upgrade. Separately, the catalog character/place/object detail page now edits the enriched array fields inline — Aliases (string chips), Color Palette (`{ name, hex, role }` swatch rows with a native color picker), and Stats (`{ label, value }` rows) — instead of rendering them read-only; add-buttons disable at the storyBible caps (12 colors, 30 stats, 12 aliases). Bible-type payloads are now run through their storyBible sanitizer (`sanitizeCharacter`/`sanitizePlace`/`sanitizeObject`) on every catalog create/update so the array editors can't land malformed rows; idea/scene/concept and user-defined types are untouched. (Builds on the editable grouped sheet + reference-sheet panel + friendly-tag repair that shipped earlier as a slice.)diff --git a/PLAN.md b/PLAN.mdindex f491d57f88..ec2031075e 100644--- a/PLAN.md+++ b/PLAN.md@@ -209,6 +209,7 @@ The first slice shipped a working **seed-mode** conductor (`/story-builder`): cr- [ ] [hidream-requires-hf-token-fail-fast] **Probe HF token upfront for HiDream gated-encoder downloads.** `data.reference/media-models.json`'s HiDream entries carry `requiresHfToken: true` + a `licenseUrl` pointing at `meta-llama/Meta-Llama-3.1-8B-Instruct`, but `scripts/z_image_turbo.py` `load_external_text_encoder()` does NOT call `probe_hf_auth()` the way `flux2_macos.py:265` does for the base FLUX repo. A user without a valid HF token currently sees a multi-GB download attempt that fails with a 401 deep inside transformers instead of a clean upfront error. Mirror the FLUX.2 probe before invoking `transformers.from_pretrained()` on the gated encoder repo. Surfaced by /do:review of PR #516 (2026-05-28).- [ ] [flux2-bf16-kv-multi-reference-support] **Lift the multi-reference gate on `flux2-klein-9b-bf16`.** `scripts/flux2_macos.py` (~line 280) refuses `--reference-images` on `quantization='none'` because the bf16 entry's `repo` is `black-forest-labs/FLUX.2-klein-9B` (the base 9B, not kv) — `Flux2KleinKVPipeline` would load fine (component init signatures match) but run K/V-cached reference attention against a transformer not tuned for the reference-editing task, producing off-task output. Either swap the bf16 entry's `repo` to `black-forest-labs/FLUX.2-klein-9B-kv` (which carries `flux-2-klein-9b-kv.safetensors` for the reference-tuned transformer) and ship a migration for existing installs, or thread an explicit `kvRepo` field through the runner so single-image and multi-reference renders can pull from different repos for the same logical model. Quality validation requires a 64+ GB machine to host the bf16 weights. Surfaced by gemini review of `[flux2-multi-reference-python-runner]` PR #524 (2026-05-28).- [ ] [flux2-runner-sidecar-tests] **Test coverage for `generateImage`'s sidecar `meta` payload.** `server/services/imageGen/local.test.js` exercises `buildArgs` (CLI emission) but never asserts on the sidecar `meta` object built inside `generateImage` — including the `referenceImageFilenames` + `referenceImageStrengths` fields added by `[flux2-multi-reference-python-runner]` (the field was `referenceImageStrengthsRequested` before per-ref weighting was honored end-to-end on 2026-05-29). A focused test would need to either factor the meta-builder out of `generateImage` so it's callable without spawning Python, or stub the spawn + assert on the persisted sidecar JSON. Surfaced by gemini review of PR #524 (2026-05-28).+- [ ] [manuscript-review-sync] **Wire the manuscript-review comment set into cross-install sync.** `data/pipeline-series/{id}/manuscript-review.json` (the "Finish the draft" comments + their status/fix) is written as a sibling of the series record but is NOT carried by `exportSeries`/`importSeries` (server/services/sharing/exporter.js) or the peer-sync path — series sync serializes the record + issues structurally, not the folder. `manuscriptReview.mergeReviewFromSync(seriesId, remoteReview)` (LWW-per-comment) already exists for this; what's missing is (a) including the review document in the series export bundle, (b) a wire-schema-version gate in `server/lib/schemaVersions.js`, and (c) calling `mergeReviewFromSync` on the receiving side. Note accepted *fixes* already sync (they write to issue stage outputs); only the comment list/status/dismissals don't propagate yet. Deferred from the manuscript-editor PR (2026-05-30) to keep that change scoped — the editor is single-install-correct without it. Skipped: defending review state against the multi-install federation is a meaningful exporter/importer surface of its own.- [ ] [reference-watch-default-prompt-version-bump-check] **Re-audit `DEFAULT_TASK_INTERVALS['reference-watch'].taskMetadata` whenever `PROMPT_VERSIONS['reference-watch']` changes.** The schedule default was flipped from `readOnly: true` → `false` on 2026-05-28 because the v2 prompt instructs the agent to append `[ref-watch-…]` items to PLAN.md and commit them — the read-only guard silently defeated that on every weekly cron firing (the on-commit `triggerReferenceAnalysis` path was already correct). A future v3 of the prompt that returns to a propose-only flow would need to flip the default back. Pin: `server/services/taskSchedule.js#DEFAULT_TASK_INTERVALS` reference-watch entry must stay in sync with the prompt's behavior; tests in `taskSchedule.test.js` and `referenceRepos.test.js` pin the current contract.## Future Ideasdiff --git a/client/src/App.jsx b/client/src/App.jsxindex efa746380d..7990555b6d 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -84,6 +84,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 PipelineManuscriptEditor = lazyWithReload(() => import('./pages/PipelineManuscriptEditor'));const PipelineIssue = lazyWithReload(() => import('./pages/PipelineIssue'));// Loading fallback for lazy-loaded pages@@ -281,6 +282,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/manuscript" element={<PipelineManuscriptEditor />} /><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.jsxindex 7949b29884..8c79361ec3 100644--- a/client/src/components/pipeline/ArcCanvas.jsx+++ b/client/src/components/pipeline/ArcCanvas.jsx@@ -28,7 +28,7 @@ import { Link } from 'react-router-dom';import {Plus, Trash2, Loader2, Sparkles, ShieldCheck, ChevronRight, ChevronDown,ChevronsUpDown, AlertCircle, Wand2, Info, ListChecks, X, Lock, Unlock,- ImageIcon, Layers, FileDown, BookOpen, ChartSpline, FileSearch, BookText,+ ImageIcon, Layers, FileDown, BookOpen, ChartSpline, FileSearch, BookText, FileText,} from 'lucide-react';import toast from '../ui/Toast';import { timeAgo } from '../../utils/formatters';@@ -530,6 +530,19 @@ function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {// show its own spinner without blocking the rest of the page.const [resolvingIdx, setResolvingIdx] = useState(new Set());const [confirmingRegen, setConfirmingRegen] = useState(false);++ // Switching series must not leak the prior series' advisory results. These+ // are all ephemeral (never persisted) — reset on id change. `running` is+ // intentionally excluded: it's bound to an in-flight call whose+ // setRunning(null) must still fire on completion.+ useEffect(() => {+ setVerifyIssues(null);+ setDerivePreview(null);+ setCompleteness(null);+ setConfirmingRegen(false);+ setResolvingIdx(new Set());+ }, [series.id]);+const { busy: lockBusy, toggle: toggleArcLock } = useLockToggle({patchFn: (next) => updatePipelineSeries(series.id, {locked: { ...(series.locked || {}), arc: next },@@ -850,6 +863,7 @@ function ArcHeader({ series, onSeriesUpdate, onIssuesUpdate, onFlushPending }) {{completeness ? (<CompletenessResultsissues={completeness}+ seriesId={series.id}onDismiss={() => setCompleteness(null)}/>) : null}@@ -1010,7 +1024,7 @@ const COMPLETENESS_CATEGORY_ORDER = ['missing-content', 'arc-gap', 'character-ga// Advisory findings panel for "finish the draft" — grouped by category, no// resolve buttons (the suggestions guide manual authoring, not an LLM rewrite).-function CompletenessResults({ issues, onDismiss }) {+function CompletenessResults({ issues, onDismiss, seriesId }) {const grouped = useMemo(() => {const byCat = new Map();for (const iss of issues) {@@ -1028,7 +1042,18 @@ function CompletenessResults({ issues, onDismiss }) {<FileSearch size={14} className="text-port-accent" />Finish the draft — {issues.length} suggestion{issues.length === 1 ? '' : 's'}</h3>- <button type="button" onClick={onDismiss} className="text-gray-500 hover:text-white"><X size={16} /></button>+ <div className="flex items-center gap-3">+ {issues.length > 0 && seriesId ? (+ <Link+ to={`/pipeline/series/${seriesId}/manuscript`}+ className="text-xs text-port-accent hover:underline inline-flex items-center gap-1"+ title="Open the manuscript editor to act on these comments inline"+ >+ <FileText size={12} /> Open editor+ </Link>+ ) : null}+ <button type="button" onClick={onDismiss} className="text-gray-500 hover:text-white"><X size={16} /></button>+ </div></div>{issues.length === 0 ? (<p className="text-xs text-gray-400">The manuscript reads as complete — no gaps found.</p>diff --git a/client/src/pages/PipelineManuscriptEditor.jsx b/client/src/pages/PipelineManuscriptEditor.jsxnew file mode 100644index 0000000000..76bed5bf92--- /dev/null+++ b/client/src/pages/PipelineManuscriptEditor.jsx@@ -0,0 +1,575 @@+/**+ * Pipeline — Manuscript Editor.+ *+ * Full-bleed two-pane workspace (`/pipeline/series/:seriesId/manuscript`) that+ * makes the "Finish the draft" pass actionable:+ * - Left : the whole series manuscript, one editable section per issue in+ * story order. The series "manuscript" is virtual — one chosen+ * stage per issue (comicScript ▸ teleplay ▸ prose). Each section is+ * a free-text editor that saves back to that issue's stage on blur.+ * - Right : Word-style editorial comments from the completeness pass. Click a+ * comment to jump to (and select) its anchor in the manuscript,+ * generate an AI find/replace fix, edit it, and accept it into the+ * manuscript — or dismiss it.+ *+ * Data: GET /pipeline/series/:id/manuscript (sections) + .../manuscript/review+ * (comments). Section saves reuse PATCH /pipeline/issues/:id; fixes go through+ * the manuscript-review fix/accept routes.+ */++import { useEffect, useMemo, useRef, useState } from 'react';+import { Link, useParams, useNavigate } from 'react-router-dom';+import {+ ArrowLeft, Loader2, Sparkles, Check, X, CornerDownRight, FileText, ChevronDown, ChevronRight, Star, History, RotateCcw,+} from 'lucide-react';+import toast from '../components/ui/Toast';+import { useAsyncAction } from '../hooks/useAsyncAction';+import { timeAgo } from '../utils/formatters';+import {+ getPipelineSeries, updatePipelineSeries, getPipelineManuscript, getPipelineManuscriptReview,+ patchPipelineManuscriptComment, savePipelineManuscriptSection, restorePipelineStageVersion,+ generatePipelineManuscriptFix, acceptPipelineManuscriptFix,+} from '../services/api';++const STAGE_LABEL = { comicScript: 'comic script', teleplay: 'teleplay', prose: 'prose', idea: 'outline' };+// Format switcher: the three manuscript formats the editor can span the full+// story in. Order mirrors the server's MANUSCRIPT_STAGES precedence.+const MANUSCRIPT_TYPES = [+ { id: 'comicScript', label: 'Comic' },+ { id: 'teleplay', label: 'Teleplay' },+ { id: 'prose', label: 'Prose' },+];++const SEVERITY_TONE = {+ high: 'bg-port-error/15 text-port-error border-port-error/40',+ medium: 'bg-port-warning/15 text-port-warning border-port-warning/40',+ low: 'bg-gray-600/20 text-gray-300 border-port-border',+};++const CATEGORY_LABEL = {+ 'missing-content': 'Missing content',+ 'arc-gap': 'Arc gap',+ 'character-gap': 'Character gap',+ pacing: 'Pacing',+ continuity: 'Continuity',+ other: 'Note',+};++// Approximate the textarea height to its content so the manuscript reads as one+// continuous scroll (lets jump-to-anchor scroll the page, not an inner box).+const rowsFor = (text) => Math.min(400, Math.max(8, (text || '').split('\n').length + 1));++export default function PipelineManuscriptEditor() {+ const { seriesId } = useParams();+ const navigate = useNavigate();+ const [series, setSeries] = useState(null);+ const [sections, setSections] = useState([]);+ const [viewType, setViewType] = useState(null); // format currently shown+ const [pinnedPrimary, setPinnedPrimary] = useState(null); // explicit bible value (may be null)+ const [availableTypes, setAvailableTypes] = useState([]); // formats with ≥1 drafted issue+ const [comments, setComments] = useState([]);+ const [loading, setLoading] = useState(true);+ const [switching, setSwitching] = useState(false);+ const [pinning, setPinning] = useState(false);+ // Per-issue free-text save state: 'saving' | 'saved' | undefined.+ const [saveState, setSaveState] = useState({});+ // textarea elements keyed by issue number, for jump-to-anchor.+ const sectionRefs = useRef(new Map());+ // Last-saved content per `${issueId}:${stageId}`, so a blur with no change+ // doesn't create a spurious version.+ const baselineRef = useRef(new Map());+ const seedBaselines = (list) => {+ baselineRef.current = new Map((list || []).map((s) => [`${s.issueId}:${s.stageId}`, s.content]));+ };++ // Patch one section's fields (content/versions) in place after a save/revert.+ const patchSection = (issueId, fields) =>+ setSections((prev) => prev.map((s) => (s.issueId === issueId ? { ...s, ...fields } : s)));++ useEffect(() => {+ let canceled = false;+ Promise.all([+ getPipelineSeries(seriesId),+ getPipelineManuscript(seriesId),+ getPipelineManuscriptReview(seriesId).catch(() => ({ comments: [] })),+ ])+ .then(([s, manuscript, review]) => {+ if (canceled) return;+ setSeries(s);+ const initialSections = Array.isArray(manuscript?.sections) ? manuscript.sections : [];+ setSections(initialSections);+ seedBaselines(initialSections);+ setViewType(manuscript?.viewType || null);+ setPinnedPrimary(manuscript?.pinnedPrimary || null);+ setAvailableTypes(Array.isArray(manuscript?.availableTypes) ? manuscript.availableTypes : []);+ setComments(Array.isArray(review?.comments) ? review.comments : []);+ })+ .catch((err) => {+ if (canceled) return;+ toast.error(err.message || 'Failed to load manuscript');+ navigate(`/pipeline/series/${seriesId}`);+ })+ .finally(() => { if (!canceled) setLoading(false); });+ return () => { canceled = true; };+ }, [seriesId, navigate]);++ // Switch which format the editor spans. Refetches that format's full-story+ // sections (every issue, empty where undrafted).+ const changeView = async (type) => {+ if (type === viewType || switching) return;+ setSwitching(true);+ const manuscript = await getPipelineManuscript(seriesId, type).catch((err) => {+ toast.error(err.message || 'Failed to load that format');+ return null;+ });+ setSwitching(false);+ if (!manuscript) return;+ const nextSections = Array.isArray(manuscript.sections) ? manuscript.sections : [];+ setSections(nextSections);+ seedBaselines(nextSections);+ setViewType(manuscript.viewType || type);+ setAvailableTypes(Array.isArray(manuscript.availableTypes) ? manuscript.availableTypes : availableTypes);+ setSaveState({});+ };++ // Pin the format currently being viewed as the series' source of truth.+ const pinPrimary = async () => {+ if (!viewType || pinning) return;+ setPinning(true);+ const updated = await updatePipelineSeries(seriesId, { primaryManuscriptType: viewType }, { silent: true })+ .catch((err) => { toast.error(err.message || 'Failed to set primary format'); return null; });+ setPinning(false);+ if (!updated) return;+ setPinnedPrimary(updated.primaryManuscriptType || viewType);+ toast.success(`${STAGE_LABEL[viewType] || viewType} set as the primary manuscript`);+ };++ const setSectionContent = (issueId, content) => patchSection(issueId, { content });++ // Save a section's edited text back to its issue stage (versioned — snapshots+ // the prior text so the edit is revertible). Skips no-op blurs so we don't+ // mint a version for an unchanged section. Server serializes the write, so a+ // blur-save can't clobber a concurrent accept on the same stage.+ const saveSection = async (section) => {+ const key = `${section.issueId}:${section.stageId}`;+ if (baselineRef.current.get(key) === section.content) return; // unchanged — nothing to version+ setSaveState((prev) => ({ ...prev, [section.issueId]: 'saving' }));+ const result = await savePipelineManuscriptSection(+ seriesId,+ section.issueId,+ { stageId: section.stageId, output: section.content },+ { silent: true },+ ).catch((err) => {+ toast.error(err.message || 'Failed to save manuscript edit');+ return null;+ });+ if (result?.section) {+ baselineRef.current.set(key, result.section.content);+ patchSection(section.issueId, { versions: result.section.versions });+ }+ setSaveState((prev) => ({ ...prev, [section.issueId]: result ? 'saved' : undefined }));+ };++ // Revert a section to a prior version (runId from its history). The restore+ // route snapshots the now-displaced text first, so revert is itself+ // reversible. Updates content + versions in place.+ const revertSection = async (section, runId) => {+ const result = await restorePipelineStageVersion(section.issueId, section.stageId, runId, { silent: true })+ .catch((err) => { toast.error(err.message || 'Failed to revert'); return null; });+ if (!result?.stage) return null;+ const content = result.stage.output || '';+ const versions = (result.stage.runHistory || []).map((h) => ({ runId: h.runId, createdAt: h.createdAt }));+ baselineRef.current.set(`${section.issueId}:${section.stageId}`, content);+ patchSection(section.issueId, { content, versions });+ setSaveState((prev) => ({ ...prev, [section.issueId]: 'saved' }));+ toast.success('Reverted to the selected version');+ return result;+ };++ // Jump to a comment's anchor: focus the issue's textarea, select the verbatim+ // quote (native selection highlights it), and scroll it into view.+ const jumpToComment = (comment) => {+ const ta = comment.issueNumber != null ? sectionRefs.current.get(comment.issueNumber) : null;+ if (!ta) {+ toast('This comment is not anchored to a specific issue');+ return;+ }+ ta.scrollIntoView({ behavior: 'smooth', block: 'start' });+ const quote = comment.anchorQuote || '';+ const idx = quote ? ta.value.indexOf(quote) : -1;+ ta.focus();+ if (idx !== -1) ta.setSelectionRange(idx, idx + quote.length);+ else ta.setSelectionRange(0, 0);+ };++ const updateCommentLocal = (next) =>+ setComments((prev) => prev.map((c) => (c.id === next.id ? next : c)));++ // After an accepted fix the server returns the rewritten section — reflect it+ // in the manuscript pane so the edit shows without a reload.+ const applyAccepted = ({ comment, section }) => {+ if (section?.issueId) {+ patchSection(section.issueId, { content: section.content, versions: section.versions });+ baselineRef.current.set(`${section.issueId}:${section.stageId}`, section.content);+ setSaveState((prev) => ({ ...prev, [section.issueId]: 'saved' }));+ }+ if (comment) updateCommentLocal(comment);+ };++ const grouped = useMemo(() => ({+ open: comments.filter((c) => c.status === 'open'),+ accepted: comments.filter((c) => c.status === 'accepted'),+ dismissed: comments.filter((c) => c.status === 'dismissed'),+ }), [comments]);++ if (loading) return <div className="p-6 text-gray-500 text-sm">Loading manuscript…</div>;++ return (+ <div className="flex flex-col h-full">+ <div className="flex-1 flex flex-col lg:grid min-h-0" style={{ gridTemplateColumns: 'minmax(0, 1fr) 380px' }}>+ {/* Manuscript pane */}+ <section className="flex flex-col min-h-0 lg:overflow-y-auto p-4 md:p-6 space-y-5">+ <header className="flex items-center gap-3 flex-wrap">+ <Link to={`/pipeline/series/${seriesId}`} className="inline-flex items-center gap-1 text-sm text-gray-400 hover:text-white">+ <ArrowLeft size={14} /> Series+ </Link>+ <FileText className="w-5 h-5 text-port-accent ml-2" />+ <h1 className="text-xl font-bold text-white truncate">{series?.name || 'Manuscript'}</h1>++ <div className="ml-auto flex items-center gap-2 flex-wrap">+ {/* Format switcher — span the full story in any of the three formats. */}+ <div className="inline-flex rounded-lg border border-port-border overflow-hidden">+ {MANUSCRIPT_TYPES.map((t) => {+ const active = t.id === viewType;+ const has = availableTypes.includes(t.id);+ return (+ <button+ key={t.id}+ type="button"+ onClick={() => changeView(t.id)}+ disabled={switching}+ title={has ? `View the ${t.label.toLowerCase()} manuscript` : `No ${t.label.toLowerCase()} drafted yet — open to start one`}+ className={`px-3 py-1.5 text-sm font-medium transition-colors disabled:opacity-50 ${+ active ? 'bg-port-accent text-white' : 'bg-port-bg text-gray-400 hover:text-white'+ }`}+ >+ {t.label}+ {t.id === pinnedPrimary ? <span className="ml-1 text-[10px]" title="Primary source format">★</span> : null}+ {!has ? <span className="ml-1 text-[10px] opacity-60">·</span> : null}+ </button>+ );+ })}+ </div>+ {switching ? <Loader2 size={14} className="animate-spin text-gray-500" /> : null}+ {/* Pin the viewed format as the source of truth (stored in the bible). */}+ {viewType && viewType !== pinnedPrimary ? (+ <button+ type="button"+ onClick={pinPrimary}+ disabled={pinning}+ title="Mark this format as the series' primary manuscript — the source the other formats are generated from"+ className="inline-flex items-center gap-1 px-2.5 py-1.5 rounded text-xs font-medium border bg-port-bg text-gray-300 border-port-border hover:border-port-accent/40 disabled:opacity-50"+ >+ {pinning ? <Loader2 size={12} className="animate-spin" /> : <Star size={12} />}+ Set as primary+ </button>+ ) : (+ <span className="text-[11px] uppercase tracking-wider text-gray-500 inline-flex items-center gap-1">+ <Star size={11} className="text-port-warning" /> primary+ </span>+ )}+ </div>+ </header>++ {sections.length === 0 ? (+ <p className="text-sm text-gray-500 italic">+ No drafted manuscript yet — write a comic script, prose, or teleplay on at least one issue, then run “Finish the draft” from the series arc.+ </p>+ ) : (+ sections.map((section) => (+ <ManuscriptSection+ key={section.issueId}+ section={section}+ saveState={saveState[section.issueId]}+ onContentChange={(content) => setSectionContent(section.issueId, content)}+ onBlurSave={() => saveSection(section)}+ onRevert={(runId) => revertSection(section, runId)}+ registerRef={(el) => {+ if (el) sectionRefs.current.set(section.number, el);+ else sectionRefs.current.delete(section.number);+ }}+ />+ ))+ )}+ </section>++ {/* Comments sidebar */}+ <aside className="border-t lg:border-t-0 lg:border-l border-port-border bg-port-card/40 lg:overflow-y-auto p-3 space-y-3">+ <h2 className="text-xs uppercase tracking-wider text-gray-500 flex items-center justify-between">+ <span>Editorial comments</span>+ <span className="text-gray-600">{grouped.open.length} open</span>+ </h2>++ {comments.length === 0 ? (+ <p className="text-xs text-gray-500 italic">+ No comments yet. Run “Finish the draft” from the series arc to generate editorial feedback here.+ </p>+ ) : null}++ {grouped.open.map((comment) => (+ <CommentCard+ key={comment.id}+ comment={comment}+ seriesId={seriesId}+ onJump={jumpToComment}+ onCommentChange={updateCommentLocal}+ onAccepted={applyAccepted}+ />+ ))}++ <ResolvedGroup label="Accepted" icon={Check} items={grouped.accepted} onJump={jumpToComment} />+ <ResolvedGroup label="Dismissed" icon={X} items={grouped.dismissed} onJump={jumpToComment} />+ </aside>+ </div>+ </div>+ );+}++// One issue's manuscript section: an auto-sized free-text editor plus a+// collapsible version history with one-click revert.+function ManuscriptSection({ section, saveState, onContentChange, onBlurSave, onRevert, registerRef }) {+ const [showVersions, setShowVersions] = useState(false);+ const [revertingId, setRevertingId] = useState(null);+ const versions = section.versions || [];++ const revert = async (runId) => {+ setRevertingId(runId);+ await onRevert(runId);+ setRevertingId(null);+ };++ return (+ <article className="space-y-1.5">+ <div className="flex items-center justify-between gap-2 sticky top-0 bg-port-bg/95 backdrop-blur py-1 z-10">+ <h2 className="text-sm font-semibold text-gray-200">+ Issue {section.number}{section.title ? ` — ${section.title}` : ''}+ <span className="ml-2 text-[10px] uppercase tracking-wider text-gray-500">{STAGE_LABEL[section.stageId] || section.stageId}</span>+ </h2>+ <div className="flex items-center gap-2">+ <SaveBadge state={saveState} />+ {versions.length > 0 ? (+ <button+ type="button"+ onClick={() => setShowVersions((v) => !v)}+ className="inline-flex items-center gap-1 text-[11px] text-gray-400 hover:text-white"+ title="Show prior saved versions"+ >+ <History size={12} /> {versions.length}+ </button>+ ) : null}+ </div>+ </div>++ {showVersions && versions.length > 0 ? (+ <div className="border border-port-border rounded bg-port-bg/40 p-2 space-y-1">+ <p className="text-[10px] uppercase tracking-wider text-gray-500">Version history (newest first)</p>+ {versions.map((v) => (+ <div key={v.runId} className="flex items-center justify-between gap-2 text-[11px]">+ <span className="text-gray-400">{v.createdAt ? timeAgo(v.createdAt) : v.runId}</span>+ <button+ type="button"+ onClick={() => revert(v.runId)}+ disabled={revertingId === v.runId}+ className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-gray-300 hover:text-white border border-port-border hover:border-port-accent/40 disabled:opacity-40"+ title="Revert this section to that version (reversible)"+ >+ {revertingId === v.runId ? <Loader2 size={11} className="animate-spin" /> : <RotateCcw size={11} />}+ Revert+ </button>+ </div>+ ))}+ </div>+ ) : null}++ <textarea+ ref={registerRef}+ value={section.content}+ onChange={(e) => onContentChange(e.target.value)}+ onBlur={onBlurSave}+ rows={rowsFor(section.content)}+ spellCheck+ className="w-full px-3 py-2 bg-port-card border border-port-border rounded text-sm text-gray-100 font-mono leading-relaxed resize-y focus:border-port-accent/50 focus:outline-none"+ />+ </article>+ );+}++function SaveBadge({ state }) {+ if (state === 'saving') return <span className="text-[10px] text-gray-500 inline-flex items-center gap-1"><Loader2 size={10} className="animate-spin" /> saving</span>;+ if (state === 'saved') return <span className="text-[10px] text-port-success">saved</span>;+ return null;+}++function Badge({ comment }) {+ return (+ <span className="flex items-center gap-1.5">+ <span className={`text-[10px] px-1.5 py-0.5 rounded border ${SEVERITY_TONE[comment.severity] || SEVERITY_TONE.low}`}>+ {comment.severity}+ </span>+ <span className="text-[10px] uppercase tracking-wider text-gray-500">{CATEGORY_LABEL[comment.category] || comment.category}</span>+ </span>+ );+}++function CommentCard({ comment, seriesId, onJump, onCommentChange, onAccepted }) {+ const [replaceText, setReplaceText] = useState(comment.fix?.replace || '');+ const hasFix = !!comment.fix;++ const [runGenerate, generating] = useAsyncAction(+ () => generatePipelineManuscriptFix(seriesId, comment.id),+ { errorMessage: 'Failed to generate fix' },+ );+ const [runAccept, accepting] = useAsyncAction(+ () => acceptPipelineManuscriptFix(seriesId, comment.id, { find: comment.fix.find, replace: replaceText }),+ { errorMessage: 'Failed to apply fix' },+ );++ const generate = async () => {+ const result = await runGenerate();+ if (!result) return;+ setReplaceText(result.fix?.replace || '');+ if (result.comment) onCommentChange(result.comment);+ if (result.fix?.fuzzy) toast('The suggested anchor was not found verbatim — edit the manuscript directly, or adjust the replacement.');+ };++ const accept = async () => {+ if (!comment.fix) return;+ const result = await runAccept();+ if (!result) return;+ onAccepted(result);+ toast.success('Fix applied to the manuscript');+ };++ const dismiss = async () => {+ const result = await patchPipelineManuscriptComment(seriesId, comment.id, { status: 'dismissed' }, { silent: true })+ .catch((err) => { toast.error(err.message || 'Failed to dismiss'); return null; });+ if (result?.comment) onCommentChange(result.comment);+ };++ const fuzzy = comment.fix?.fuzzy;++ return (+ <div className="border border-port-border rounded-lg bg-port-bg/40 p-2.5 space-y-2">+ <div className="flex items-center justify-between gap-2">+ <Badge comment={comment} />+ <button+ type="button"+ onClick={() => onJump(comment)}+ className="text-[11px] text-port-accent hover:underline inline-flex items-center gap-1"+ title="Jump to this spot in the manuscript"+ >+ <CornerDownRight size={11} />+ {comment.issueNumber != null ? `Issue ${comment.issueNumber}` : 'Jump'}+ </button>+ </div>++ <p className="text-xs text-gray-200">{comment.problem}</p>+ {comment.suggestion ? <p className="text-[11px] text-gray-400"><span className="text-gray-500">Fix: </span>{comment.suggestion}</p> : null}+ {comment.anchorQuote ? <p className="text-[11px] text-gray-500 italic line-clamp-2">“{comment.anchorQuote}”</p> : null}++ {hasFix ? (+ <div className="space-y-1.5">+ {comment.fix.find ? (+ <details className="text-[11px]">+ <summary className="text-gray-500 cursor-pointer">Replacing…</summary>+ <pre className="mt-1 whitespace-pre-wrap text-gray-500 bg-port-card border border-port-border rounded p-1.5 max-h-24 overflow-y-auto">{comment.fix.find}</pre>+ </details>+ ) : null}+ <label className="block text-[10px] uppercase tracking-wider text-gray-500">Suggested replacement (editable)</label>+ <textarea+ value={replaceText}+ onChange={(e) => setReplaceText(e.target.value)}+ rows={Math.min(16, Math.max(3, replaceText.split('\n').length + 1))}+ className="w-full px-2 py-1.5 bg-port-card border border-port-border rounded text-[12px] text-gray-100 font-mono resize-y focus:border-port-accent/50 focus:outline-none"+ />+ {fuzzy ? (+ <p className="text-[10px] text-port-warning">Anchor not found verbatim — accepting may fail; edit the manuscript directly if so.</p>+ ) : null}+ </div>+ ) : null}++ <div className="flex items-center gap-2 pt-0.5">+ {!hasFix ? (+ <button+ type="button"+ onClick={generate}+ disabled={generating}+ className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-[12px] font-medium border bg-port-bg text-port-accent border-port-border hover:border-port-accent/40 disabled:opacity-40"+ >+ {generating ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}+ Generate fix+ </button>+ ) : (+ <>+ <button+ type="button"+ onClick={accept}+ disabled={accepting || !replaceText.trim()}+ className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-[12px] font-medium bg-port-success/20 text-port-success border border-port-success/40 hover:bg-port-success/30 disabled:opacity-40"+ >+ {accepting ? <Loader2 size={12} className="animate-spin" /> : <Check size={12} />}+ Accept+ </button>+ <button+ type="button"+ onClick={generate}+ disabled={generating || accepting}+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-[12px] text-gray-400 hover:text-white disabled:opacity-40"+ title="Regenerate the suggested fix"+ >+ {generating ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}+ </button>+ </>+ )}+ <button+ type="button"+ onClick={dismiss}+ className="ml-auto inline-flex items-center gap-1 px-2 py-1 rounded text-[12px] text-gray-500 hover:text-white"+ >+ <X size={12} /> Dismiss+ </button>+ </div>+ </div>+ );+}++function ResolvedGroup({ label, icon: Icon, items, onJump }) {+ const [open, setOpen] = useState(false);+ if (items.length === 0) return null;+ return (+ <div className="pt-1">+ <button+ type="button"+ onClick={() => setOpen((o) => !o)}+ className="w-full flex items-center gap-1.5 text-[11px] uppercase tracking-wider text-gray-500 hover:text-gray-300"+ >+ {open ? <ChevronDown size={12} /> : <ChevronRight size={12} />}+ <Icon size={12} /> {label} ({items.length})+ </button>+ {open ? (+ <div className="mt-1.5 space-y-1.5">+ {items.map((c) => (+ <button+ key={c.id}+ type="button"+ onClick={() => onJump(c)}+ className="block w-full text-left border border-port-border rounded p-2 bg-port-bg/30 hover:border-port-accent/30"+ >+ <span className="text-[11px] text-gray-400 line-clamp-2">{c.problem}</span>+ </button>+ ))}+ </div>+ ) : null}+ </div>+ );+}diff --git a/client/src/pages/PipelineManuscriptEditor.test.jsx b/client/src/pages/PipelineManuscriptEditor.test.jsxnew file mode 100644index 0000000000..cb52eb658e--- /dev/null+++ b/client/src/pages/PipelineManuscriptEditor.test.jsx@@ -0,0 +1,125 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, waitFor, fireEvent } from '@testing-library/react';+import { MemoryRouter, Routes, Route } from 'react-router-dom';++const api = vi.hoisted(() => ({+ getPipelineSeries: vi.fn(),+ updatePipelineSeries: vi.fn(),+ getPipelineManuscript: vi.fn(),+ getPipelineManuscriptReview: vi.fn(),+ savePipelineManuscriptSection: vi.fn(),+ restorePipelineStageVersion: vi.fn(),+ patchPipelineManuscriptComment: vi.fn(),+ generatePipelineManuscriptFix: vi.fn(),+ acceptPipelineManuscriptFix: vi.fn(),+}));+vi.mock('../services/api', () => api);+vi.mock('../components/ui/Toast', () => ({ default: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }) }));++import PipelineManuscriptEditor from './PipelineManuscriptEditor';++const comment = {+ id: 'mrc-1', issueNumber: 1, issueId: 'iss-1', stageId: 'prose',+ severity: 'high', category: 'arc-gap', location: 'Issue 1',+ problem: 'The ending is abrupt', suggestion: 'add a beat', anchorQuote: 'She left.',+ status: 'open', fix: null, createdAt: 't', updatedAt: 't',+};++const renderEditor = () => render(+ <MemoryRouter initialEntries={['/pipeline/series/ser-1/manuscript']}>+ <Routes>+ <Route path="/pipeline/series/:seriesId/manuscript" element={<PipelineManuscriptEditor />} />+ <Route path="/pipeline/series/:seriesId" element={<div>series page</div>} />+ </Routes>+ </MemoryRouter>,+);++beforeEach(() => {+ vi.clearAllMocks();+ api.getPipelineSeries.mockResolvedValue({ id: 'ser-1', name: 'My Series', primaryManuscriptType: 'prose' });+ api.getPipelineManuscript.mockResolvedValue({+ sections: [{ issueId: 'iss-1', number: 1, title: 'One', stageId: 'prose', content: 'The hero walked in. She left.' }],+ viewType: 'prose',+ primaryStageId: 'prose',+ pinnedPrimary: 'prose',+ availableTypes: ['prose'],+ });+ api.getPipelineManuscriptReview.mockResolvedValue({ schemaVersion: 1, comments: [comment] });+});++describe('PipelineManuscriptEditor', () => {+ it('renders the manuscript section and an open editorial comment', async () => {+ renderEditor();+ expect(await screen.findByText('My Series')).toBeInTheDocument();+ expect(screen.getByText('The ending is abrupt')).toBeInTheDocument();+ expect(screen.getByDisplayValue('The hero walked in. She left.')).toBeInTheDocument();+ expect(screen.getByText(/1 open/)).toBeInTheDocument();+ });++ it('generates a fix, then accepts it — moving the comment to Accepted and updating the section', async () => {+ api.generatePipelineManuscriptFix.mockResolvedValue({+ fix: { find: 'She left.', replace: 'She left, but paused.' },+ comment: { ...comment, fix: { find: 'She left.', replace: 'She left, but paused.' } },+ });+ api.acceptPipelineManuscriptFix.mockResolvedValue({+ comment: { ...comment, status: 'accepted', fix: { find: 'She left.', replace: 'She left, but paused.' } },+ section: { issueId: 'iss-1', number: 1, title: 'One', stageId: 'prose', content: 'The hero walked in. She left, but paused.' },+ });++ renderEditor();+ fireEvent.click(await screen.findByText('Generate fix'));++ // The editable replacement appears.+ expect(await screen.findByDisplayValue('She left, but paused.')).toBeInTheDocument();+ expect(api.generatePipelineManuscriptFix).toHaveBeenCalledWith('ser-1', 'mrc-1');++ fireEvent.click(screen.getByText('Accept'));++ // Section text updates and the open count drops to 0.+ expect(await screen.findByDisplayValue('The hero walked in. She left, but paused.')).toBeInTheDocument();+ await waitFor(() => expect(screen.getByText(/0 open/)).toBeInTheDocument());+ expect(api.acceptPipelineManuscriptFix).toHaveBeenCalledWith('ser-1', 'mrc-1', { find: 'She left.', replace: 'She left, but paused.' });+ });++ it('switches manuscript format on demand', async () => {+ api.getPipelineManuscript.mockImplementation((_id, type) => {+ if (type === 'teleplay') return Promise.resolve({+ sections: [{ issueId: 'iss-1', number: 1, title: 'One', stageId: 'teleplay', content: 'INT. ROOM - DAY' }],+ viewType: 'teleplay', primaryStageId: 'prose', pinnedPrimary: 'prose', availableTypes: ['prose', 'teleplay'],+ });+ return Promise.resolve({+ sections: [{ issueId: 'iss-1', number: 1, title: 'One', stageId: 'prose', content: 'The hero walked in. She left.' }],+ viewType: 'prose', primaryStageId: 'prose', pinnedPrimary: 'prose', availableTypes: ['prose', 'teleplay'],+ });+ });+ renderEditor();+ await screen.findByText('My Series');+ fireEvent.click(screen.getByText('Teleplay'));+ expect(await screen.findByDisplayValue('INT. ROOM - DAY')).toBeInTheDocument();+ expect(api.getPipelineManuscript).toHaveBeenCalledWith('ser-1', 'teleplay');+ });++ it('saves a changed free-text section edit on blur (versioned), and skips no-op blurs', async () => {+ api.savePipelineManuscriptSection.mockResolvedValue({+ section: { issueId: 'iss-1', number: 1, title: 'One', stageId: 'prose', content: 'The hero walked in. She stayed.', versions: [{ runId: 'v1', createdAt: 't' }] },+ });+ renderEditor();+ const ta = await screen.findByDisplayValue('The hero walked in. She left.');++ // No-op blur (unchanged) must not save.+ fireEvent.blur(ta);+ expect(api.savePipelineManuscriptSection).not.toHaveBeenCalled();++ // Changed blur saves with the versioned section endpoint.+ fireEvent.change(ta, { target: { value: 'The hero walked in. She stayed.' } });+ fireEvent.blur(ta);+ await waitFor(() => expect(api.savePipelineManuscriptSection).toHaveBeenCalledWith(+ 'ser-1',+ 'iss-1',+ { stageId: 'prose', output: 'The hero walked in. She stayed.' },+ { silent: true },+ ));+ // Version history surfaces after the save.+ expect(await screen.findByTitle('Show prior saved versions')).toBeInTheDocument();+ });+});diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsxindex 88f8b83fe5..61a2bc7bcc 100644--- a/client/src/pages/PipelineSeries.jsx+++ b/client/src/pages/PipelineSeries.jsx@@ -302,6 +302,38 @@ function BibleSidebar({ series, universes, patchSeries, onSeriesUpdate, onFlushP</div></Field>+ <Field label="Primary manuscript format (source of truth)">+ <div className="flex items-center gap-2">+ <select+ id="series-primary-manuscript"+ value={series.primaryManuscriptType || ''}+ onChange={async (e) => {+ const value = e.target.value || null;+ patchSeries({ primaryManuscriptType: value });+ const updated = await updatePipelineSeries(series.id, { primaryManuscriptType: value }, { silent: true })+ .catch((err) => { toast.error(err.message || 'Failed to set primary format'); return null; });+ if (updated) onSeriesUpdate?.(updated);+ }}+ className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ >+ <option value="">— Auto-detect —</option>+ <option value="comicScript">Comic</option>+ <option value="teleplay">Teleplay</option>+ <option value="prose">Prose</option>+ </select>+ <Link+ to={`/pipeline/series/${series.id}/manuscript`}+ className="inline-flex items-center gap-1 text-xs text-port-accent hover:underline whitespace-nowrap"+ title="Open the full manuscript editor"+ >+ <NotebookPen size={12} /> Editor+ </Link>+ </div>+ <p className="text-[11px] text-gray-500 mt-1">+ The format you finalize first — the other two are generated from it. The manuscript editor opens this format by default.+ </p>+ </Field>+<Field label="Premise (the bible — fed into every stage's prompt context)"><textareavalue={series.premise || ''}diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex af39ec68dc..7455c67fa6 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -418,6 +418,50 @@ export const analyzePipelineManuscriptCompleteness = (seriesId, { providerOverribody: JSON.stringify({ providerOverride, modelOverride }),});+// ---- Manuscript editor ----+// Full series manuscript in one format. `type` (comicScript|teleplay|prose)+// selects the format; omit to get the series' primary/source format. Returns+// { sections, viewType, primaryStageId, pinnedPrimary, availableTypes }.+export const getPipelineManuscript = (seriesId, type) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/manuscript${type ? `?type=${encodeURIComponent(type)}` : ''}`);++// The persisted "finish the draft" comment set ({ schemaVersion, comments }).+export const getPipelineManuscriptReview = (seriesId) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/manuscript/review`);++// Patch one comment: { status } flip and/or { fix } attach/clear. Returns { comment }.+export const patchPipelineManuscriptComment = (seriesId, commentId, patch, options = {}) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/manuscript/review/comments/${encodeURIComponent(commentId)}`, {+ method: 'PATCH',+ body: JSON.stringify(patch),+ ...options,+ });++// Generate an anchored find/replace fix for a comment (does not apply it).+export const generatePipelineManuscriptFix = (seriesId, commentId, { providerOverride, modelOverride } = {}) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/manuscript/review/comments/${encodeURIComponent(commentId)}/fix`, {+ method: 'POST',+ body: JSON.stringify({ providerOverride, modelOverride }),+ });++// Apply an (optionally edited) fix into the issue's stage output + mark accepted.+// Returns { comment, section }.+export const acceptPipelineManuscriptFix = (seriesId, commentId, { find, replace }) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/manuscript/review/comments/${encodeURIComponent(commentId)}/accept`, {+ method: 'POST',+ body: JSON.stringify({ find, replace }),+ });++// Versioned free-text save of one manuscript section. Snapshots the prior text+// into history (revert via restorePipelineStageVersion). Returns { section }+// where section.versions is the updated [{ runId, createdAt }] list.+export const savePipelineManuscriptSection = (seriesId, issueId, { stageId, output }, options = {}) =>+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/manuscript/sections/${encodeURIComponent(issueId)}`, {+ method: 'PUT',+ body: JSON.stringify({ stageId, output }),+ ...options,+ });+// ---- Volume beat-sheet bulk generator ----// Sequential idea-stage run across every issue in a volume. `mode` is// 'skip-existing' (default) or 'regenerate-all'. Returnsdiff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex b7f05cb1ea..090e80c85d 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -286,7 +286,14 @@},"pipeline-manuscript-completeness": {"name": "Pipeline — Manuscript Completeness",- "description": "Developmental editor pass over the ACTUAL drafted manuscript (comic script / prose / teleplay across all issues), not synopses. Surfaces what's missing to FINISH a near-complete draft: missing-content (beats/pages/scenes), arc-gap (themes/protagonist turns the draft doesn't yet deliver), character-gap (under-developed cast), pacing, and continuity. Returns categorized { severity, category, location, problem, suggestion } findings — empty list means complete.",+ "description": "Developmental editor pass over the ACTUAL drafted manuscript (comic script / prose / teleplay across all issues), not synopses. Surfaces what's missing to FINISH a near-complete draft: missing-content (beats/pages/scenes), arc-gap (themes/protagonist turns the draft doesn't yet deliver), character-gap (under-developed cast), pacing, and continuity. Returns categorized { severity, category, issueNumber, anchorQuote, location, problem, suggestion } findings — issueNumber + anchorQuote anchor each finding to a manuscript spot so the editor can jump to it; empty list means complete.",+ "model": "heavy",+ "returnsJson": true,+ "variables": []+ },+ "pipeline-manuscript-fix": {+ "name": "Pipeline — Manuscript Fix",+ "description": "Generate a surgical, anchored edit that closes one 'Finish the draft' editorial gap in a single issue's drafted text. Given the issue's manuscript + the finding (category/severity/problem/suggestion/anchorQuote), returns a { find, replace } JSON pair where `find` is a verbatim excerpt of the manuscript to locate and `replace` is that excerpt rewritten to close the gap — preserving the author's voice. The user can edit `replace` before accepting it into the manuscript.","model": "heavy","returnsJson": true,"variables": []diff --git a/data.reference/prompts/stages/pipeline-manuscript-completeness.md b/data.reference/prompts/stages/pipeline-manuscript-completeness.mdindex 4ca655947d..03d5544cad 100644--- a/data.reference/prompts/stages/pipeline-manuscript-completeness.md+++ b/data.reference/prompts/stages/pipeline-manuscript-completeness.md@@ -80,6 +80,8 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c{"severity": "high","category": "missing-content",+ "issueNumber": 2,+ "anchorQuote": "a short verbatim excerpt copied EXACTLY from the manuscript above, at the spot the gap occurs","location": "Issue 2, around the castle-escape page","problem": "string (what is missing or under-developed, with specific evidence from the script)","suggestion": "string (the smallest concrete addition — a beat, a page, a scene, a line of motivation — that closes the gap)"@@ -88,6 +90,8 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c}```+- `issueNumber` must be the integer `N` from the `# Issue N` header of the issue the gap belongs to (omit or use `null` if the gap spans the whole series and no single issue applies).+- `anchorQuote` must be a short excerpt (one sentence or a few words, ≤ 400 chars) **copied verbatim** from the manuscript text above, marking where the gap is — the exact spot a transition is missing, where a payoff should land, etc. Copy it character-for-character so an editor can locate it; do not paraphrase. Use the empty string only when the gap is an absence with no nearby text to point at (e.g. a missing ending after the final line — then quote that final line).- `category` must be one of `missing-content` / `arc-gap` / `character-gap` / `pacing` / `continuity`.- `severity` must be one of `high` / `medium` / `low`:- **`high`** — the draft cannot be considered finished without this (a missing climax, an unresolved central arc).diff --git a/data.reference/prompts/stages/pipeline-manuscript-fix.md b/data.reference/prompts/stages/pipeline-manuscript-fix.mdnew file mode 100644index 0000000000..1c0d2d0e2c--- /dev/null+++ b/data.reference/prompts/stages/pipeline-manuscript-fix.md@@ -0,0 +1,66 @@+# Pipeline — Manuscript Fix++You are a developmental editor making **one surgical edit** to a drafted manuscript to close a specific gap an editorial pass already identified. You are NOT rewriting the issue or changing the author's voice — you are making the smallest precise change that resolves the noted problem.++## Series bible++- **Name:** {{series.name}}+- **Logline:** {{series.logline}}+- **Premise:**++```+{{series.premise}}+```++## Intended arc++- **Whole-story logline:** {{arc.logline}}+- **Themes:** {{arc.themesCsv}}++## The editorial finding to address++- **Category:** {{finding.category}}+- **Severity:** {{finding.severity}}+- **Problem:** {{finding.problem}}+- **Suggested fix:** {{finding.suggestion}}+{{#finding.anchorQuote}}+- **Anchor (where in the text):**++```+{{finding.anchorQuote}}+```+{{/finding.anchorQuote}}++## The issue's drafted manuscript++This is the full text of the one issue you are editing. The script may use page/panel markers, prose, or screenplay form — match whichever it is.++```+{{manuscript}}+```++## What to do++Produce the smallest edit that closes the gap described above, in the author's existing voice and format:++- For a **missing transition / beat / line**, expand the smallest span that should carry it.+- For a **payoff or setup that's absent**, add the minimal connective text where it belongs.+- For an **under-developed character moment**, enrich the existing nearby lines rather than inventing a new scene unless the gap genuinely requires one.++Do not touch anything beyond what the finding calls for. Preserve formatting markers (page/panel headers, sluglines, speaker tags) exactly.++## Output contract++Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:++```json+{+ "find": "a verbatim excerpt copied EXACTLY from the manuscript above — the span you are replacing",+ "replace": "that same span rewritten to close the gap"+}+```++- `find` MUST be copied **character-for-character** from the manuscript text above (including punctuation, line breaks, and formatting markers). Keep it as **small as possible** while still being uniquely locatable — a sentence or a short paragraph, not a whole page. The system locates your edit by an exact substring match on `find`, so any paraphrase will fail.+- `replace` is `find` rewritten to incorporate the fix. To **insert** new material without deleting anything, set `replace` to the original `find` text followed by the new content.+- If the gap is a pure absence at the very end (e.g. a missing ending), set `find` to the manuscript's final sentence and append the new ending in `replace`.+- Keep the edit tight and in-voice. Do not rewrite unrelated passages.diff --git a/docs/plans/2026-05-30-manuscript-editor.md b/docs/plans/2026-05-30-manuscript-editor.mdnew file mode 100644index 0000000000..19b77c9c08--- /dev/null+++ b/docs/plans/2026-05-30-manuscript-editor.md@@ -0,0 +1,253 @@+# Finish The Draft → Actionable Manuscript Editor++## Context++The "Finish the Draft" feature (manuscript-completeness pass) reads a series' drafted+scripts and returns editorial findings, but it isn't yet *actionable*:++1. **Bug:** The findings (and the sibling verify/derive results) live in component-local+ state in `ArcHeader` (`client/src/components/pipeline/ArcCanvas.jsx`) with **no reset+ when `series.id` changes** — so switching series leaves the prior series' suggestions+ rendered on the new one.+2. **Missing workspace:** Findings render as a flat advisory list with no way to act on+ them. The user wants a **dedicated full-page manuscript editor** that shows the whole+ series manuscript (all issues in story order) with editorial feedback as a **Word-style+ comments sidebar** — click a comment to jump to the relevant spot, generate an AI fix,+ modify it, and save it into the manuscript. It must work for all three manuscript types+ (prose, teleplay, comic), auto-detecting which type each issue uses.++**Confirmed product decisions:**+- **Surface:** dedicated full-page editor at `/pipeline/series/:seriesId/manuscript`.+- **Editing scope:** AI-comment-driven fixes **AND** full free-text editing of each+ issue section (live save per section through the serialized stage-write path).+- **Fix application:** surgical anchored **find/replace** (editable before accept), not+ full-issue rewrite.++The series manuscript is *virtual*: it's the concatenation of one chosen stage per issue+(`comicScript` ▸ `teleplay` ▸ `prose` precedence). Edits target a specific issue+stage.++---++## Change 1 — Bug fix: reset ArcHeader ephemeral state on series switch++**File:** `client/src/components/pipeline/ArcCanvas.jsx` — `ArcHeader` (component starts+line 520). Add one effect right after the `useState` block (after line 532), before+`useLockToggle`:++```jsx+// Switching series must not leak the prior series' advisory results. These are+// all ephemeral (never persisted) — reset on id change.+useEffect(() => {+ setVerifyIssues(null);+ setDerivePreview(null);+ setCompleteness(null);+ setConfirmingRegen(false);+ setResolvingIdx(new Set());+}, [series.id]);+```++`running` is intentionally excluded (it's bound to an in-flight async call whose+`setRunning(null)` must still fire). `useEffect` is already imported in this file.++---++## Change 2 — Manuscript editor with anchored, persisted, AI-fixable comments++### 2.1 Server — structured manuscript collection+**File:** `server/services/pipeline/arcPlanner.js`+- Add exported `collectManuscriptSections(seriesId, { stageOrder = MANUSCRIPT_STAGES } = {})`+ returning `[{ issueId, number, title, stageId, content }]` in `arcPosition` order. Reuse+ the existing `listIssues` + `compareIssuesByPosition` + `stageTextOf` + precedence-pick+ logic from `collectIssueSourceText` (line 195).+- **Refactor `collectIssueSourceText` to call `collectManuscriptSections` and join** the+ sections (`# Issue N — Title (stageId)\n\n{content}` joined by `\n\n---\n\n`, sliced to+ `BACKFILL_SOURCE_MAX`). The corpus the LLM sees and the sections the client renders MUST+ stay byte-identical — `anchorQuote`/`find` matching depends on it. A `primaryStageId`+ (most common `stageId`) is the editor's display "mode"; per-issue `stageId` is+ authoritative for writes.++### 2.2 Server — anchored findings+**File:** `server/services/pipeline/arcPlanner.js` — extend `shapeCompletenessFindings`+(line 594) to also carry:+```js+issueNumber: Number.isInteger(raw?.issueNumber) ? raw.issueNumber : null,+anchorQuote: typeof raw?.anchorQuote === 'string' ? raw.anchorQuote.trim().slice(0, 400) : '',+```+Keep `location` (fuzzy fallback). Findings without anchors still render (no click-to-jump).++**File:** `data.reference/prompts/stages/pipeline-manuscript-completeness.md` — add+`issueNumber` (integer matching the `# Issue N` headers) and `anchorQuote` (a short+**verbatim** excerpt copied from the manuscript at the gap) to the output contract ++field rules. This is an **edit to a shipped prompt → needs a migration.**++**File:** `scripts/migrations/056-manuscript-anchored-findings-prompt.js` (+ `.test.js`) —+use `makePromptReplaceMigration` from `./_lib.js` exactly like+`054-source-agnostic-stage-prompts.js`. Set `ACCEPTED_OLD_MD5` to the current shipped+`pipeline-manuscript-completeness.md` hash and `NEW_SHIPPED_MD5` to the post-edit hash+(via the repo's normalized `md5()` helper). Mirror the new hash into `scripts/setup-data.js`'s+drift table. (The new fix prompt below is a *new* file — no migration; `setup-data.js`+copies missing prompts.)++### 2.3 Server — review persistence+**File (new):** `server/services/pipeline/manuscriptReview.js`+- Storage: sibling file `data/pipeline-series/{id}/manuscript-review.json` (kept in the+ series folder so existing share/sync of that folder carries it; do NOT bloat the+ LWW-merged series `index.json`). Serialize writes on a per-series tail (single tail per+ shared file, per CLAUDE.md).+- `getReview(seriesId)` → `{ schemaVersion: 1, comments: [] }` when absent (distinguish+ absent vs empty).+- `seedReviewFromFindings(seriesId, findings, { runId })` → map shaped findings → comment+ records (status `open`), resolving `issueId`/`stageId` from `collectManuscriptSections`+ by `issueNumber`. **Preserve** existing `accepted`/`dismissed` comments; dedupe still-open+ comments by `(issueNumber, anchorQuote, problem)`.+- `updateComment(seriesId, commentId, patch)` — status/fix edits; LWW on `updatedAt`.+- `mergeReviewFromSync(seriesId, remoteReview)` — LWW-by-`updatedAt` per comment, mirroring+ `mergeIssuesFromSync` (issues.js:1039) so the review participates in series-folder sync.++**Comment shape:**+```js+{ id, issueNumber, issueId|null, stageId|null,+ severity, category, location, problem, suggestion, anchorQuote,+ status: 'open'|'accepted'|'dismissed',+ fix: { find, replace, fuzzy? } | null,+ sourceRunId, createdAt, updatedAt }+```++### 2.4 Server — fix generation + accept+**File (new):** `server/services/pipeline/manuscriptFix.js`+- `generateManuscriptFix(seriesId, { commentId, providerOverride, modelOverride })` —+ resolve the comment's `issueId`+`stageId`, load that issue's stage text (`getIssue` →+ `stages[stageId]`, `stageTextOf`), call+ `runStagedLLM('pipeline-manuscript-fix', ctx, { returnsJson: true, source: 'pipeline-manuscript-fix', ... })`.+ Persist `fix: { find, replace }` on the comment (status stays `open`). Validate that+ `find` occurs in the current stage text; if not, set `fix.fuzzy = true` so the client+ falls back to manual editing instead of failing silently.+- `acceptManuscriptFix(seriesId, { commentId, find, replace })` — apply through the+ serialized `updateStageWithLatest(issueId, stageId, computeFn)` (issues.js:974):+ ```js+ const text = stageTextOf(cur);+ const idx = text.indexOf(find);+ if (idx === -1) throw makeErr('Anchor text no longer present — regenerate the fix', ERR_VALIDATION);+ return { output: text.slice(0, idx) + replace + text.slice(idx + find.length),+ lastRunId: makeRunId('manuscript-fix') }; // fresh runId → snapshotRunHistory keeps prior text+ ```+ Then `updateComment(... status: 'accepted')`. Return the refreshed section content so the+ client re-renders without a full reload.++**File (new):** `data.reference/prompts/stages/pipeline-manuscript-fix.md` — context = series+bible block + the single issue's stage text + `category`/`severity`/`problem`/`suggestion`/+`anchorQuote`. Output JSON `{ find, replace }`: `find` MUST be copied verbatim from the+provided text, as small as possible while uniquely locatable; `replace` is the surgical+edit preserving the author's voice. Add a matching `pipeline-manuscript-fix` entry to+`data.reference/prompts/stage-config.json` with `returnsJson: true`.++### 2.5 Server — free-text section save+Reuse the **existing** issue stage PATCH path for free-text edits (no new endpoint needed):+each editable section saves via the existing `PATCH /pipeline/issues/:id` → `updateIssue`+stage write (serialized). The editor sends `{ stages: { [stageId]: { output } } }` for the+edited issue. Confirm the existing issue patch schema permits a stage `output` write; if it+routes through `updateStageWithLatest`, prefer that for serialization.++### 2.6 Server — routes+**File:** `server/routes/pipeline.js` (near the completeness route ~line 1293, using+`asyncHandler` + `validateRequest` + `mapServiceError`, no try/catch):+- `GET /series/:id/manuscript` → `{ sections, primaryStageId }`.+- `GET /series/:id/manuscript/review` → `getReview`.+- `POST /series/:id/manuscript/completeness` (existing) — after `analyzeManuscriptCompleteness`,+ call `seedReviewFromFindings` and return the merged review alongside `issues` (keep+ returning `issues` for the existing ArcHeader caller — backward compatible).+- `PATCH /series/:id/manuscript/review/comments/:commentId` → `updateComment`.+- `POST /series/:id/manuscript/review/comments/:commentId/fix` → `generateManuscriptFix`.+- `POST /series/:id/manuscript/review/comments/:commentId/accept` → `acceptManuscriptFix`.++**Zod schemas** (inline near the existing `manuscriptCompletenessSchema` at line 587):+- `manuscriptFixGenerateSchema = z.object(providerOverrideShape)`.+- `manuscriptFixAcceptSchema = z.object({ find: z.string().min(1).max(STAGE_OUTPUT_MAX), replace: z.string().max(STAGE_OUTPUT_MAX) })`.+- `manuscriptCommentPatchSchema = z.object({ status: z.enum(['open','accepted','dismissed']).optional(), fix: z.object({ find: z.string().max(STAGE_OUTPUT_MAX), replace: z.string().max(STAGE_OUTPUT_MAX) }).nullable().optional() }).strict()` (absent vs explicit-null).++### 2.7 Client — API wrappers+**File:** `client/src/services/apiPipeline.js` (near `analyzePipelineManuscriptCompleteness`+line 415; re-export via `api.js` since pages import from `../services/api`):+`getPipelineManuscript`, `getPipelineManuscriptReview`, `patchPipelineManuscriptComment`,+`generatePipelineManuscriptFix`, `acceptPipelineManuscriptFix`, and a free-text section save+(reuse `updatePipelineIssue`).++### 2.8 Client — editor page+**File (new):** `client/src/pages/PipelineManuscriptEditor.jsx` — full-bleed two-pane:+- Loads series + `getPipelineManuscript` + `getPipelineManuscriptReview` (Promise.all with+ the cancel-guard pattern from `PipelineSeries.jsx` lines 58-78).+- **Left pane (scrollable manuscript):** one section per issue, header `Issue N — Title+ (stageId)`, stable `id={`ms-issue-${number}`}` + a `ref` for scroll-to. Each section is a+ **live-editable textarea** (full free-text editing) with dirty-tracking + debounced save+ via `updatePipelineIssue` (status badge like `TextStagePanel`). `primaryStageId` shown as+ the editor mode label.+- **Right pane (comments sidebar):** comments grouped by status with severity/category+ badges. Per card: problem, suggestion, **Jump** (scroll to section + transient highlight+ of `anchorQuote` substring), **Generate fix**, then a `{find → replace}` preview with an+ **editable `replace` textarea** + **Accept** / **Dismiss**. After accept, update the+ affected section content from the response and move the comment to "accepted" locally+ (reactive update, no full reload). `fuzzy` fixes fall back to manual editing.+- Full-bleed is automatic: Layout's `isFullWidth` already matches `/pipeline/series/`.++**File:** `client/src/App.jsx` — lazy import + `<Route path="pipeline/series/:seriesId/manuscript" .../>`+(mirror the existing roadmap sub-route).++**Entry point:** in `ArcCanvas.jsx` `CompletenessResults` / ArcHeader results block, add an+`Open manuscript editor` Link to `/pipeline/series/${series.id}/manuscript`. Because the+completeness route now seeds the review file, the editor shows the just-generated comments+on open.++**Nav manifest:** no `NAV_COMMANDS` entry — this is a per-series detail sub-route needing a+concrete `:seriesId`, matching the existing `/pipeline/series/:seriesId/roadmap` precedent.++---++## Reuse notes+- `collectManuscriptSections` = refactored core of `collectIssueSourceText`+ (arcPlanner.js:195) — same precedence/order; corpus derived from sections to stay+ byte-identical.+- Accept + free-text writes go through `updateStageWithLatest` (issues.js:974): already+ serialized, already snapshots `runHistory` (`snapshotRunHistory`, line 262) on `lastRunId`+ change, already enforces `STAGE_OUTPUT_MAX`.+- Prompt migration via `makePromptReplaceMigration` (`scripts/migrations/_lib.js`, used by 054).+- Client load/cancel + reactive-update conventions from `PipelineSeries.jsx`; toasts via+ `client/src/components/ui/Toast`.++---++## Verification / test plan+**Server (`*.test.js` next to sources):**+- `collectManuscriptSections` returns correct ordered per-issue records; `collectIssueSourceText`+ output **byte-identical** after refactor (string-equality test).+- `shapeCompletenessFindings` carries/validates `issueNumber`/`anchorQuote`; backward compat+ for unanchored findings.+- `manuscriptReview` seed/dedupe/merge LWW; absent-file → empty; accepted comments survive re-seed.+- `manuscriptFix` accept applies find/replace, snapshots prior output to `runHistory`, throws+ `ERR_VALIDATION` on missing `find`.+- Routes: GET sections/review; POST completeness seeds review; PATCH/fix/accept happy ++ Zod 422 paths.+- Migration `056` test mirrors `054-…test.js` (old hash upgrades; customized prompt left intact).++**Client:** smoke render of `PipelineManuscriptEditor` with mocked API — Jump scrolls/highlights;+accept relocates comment reactively; free-text edit triggers debounced save.++**Manual:** run "Finish the draft" on a series with drafted scripts → Open editor → Jump to+anchor → Generate fix → edit replacement → Accept → confirm stage `output` updated and prior+text in `runHistory`; edit a section free-text → confirm saved; reload → review + comment+statuses persist; switch series on the arc page → confirm prior completeness results cleared+(Change 1).++Run: `cd server && npm test`, `cd client && npm test`. Run `/simplify` before committing.++---++## Risks / sequencing+- **Anchor fragility:** `anchorQuote`/`find` are verbatim substrings; the byte-identical+ corpus↔sections invariant is load-bearing. Validate presence server-side; mark `fuzzy` and+ fall back to manual editing rather than failing.+- **Migration hashes:** compute exact pre/post normalized `md5()` and mirror the new hash into+ `setup-data.js`'s drift table in the same change, or `setup-data` flags drift.+- **runHistory churn:** each accepted fix + free-text save consumes a `runHistory` slot (cap 5).+ Acceptable; bulk fixes on one issue roll older generations out.+- **Sequencing:** 2.1 + 2.2 are independent; 2.3 depends on both; 2.4/2.5 depend on 2.1; client+ (2.7/2.8) depends on routes (2.6). Ship the prompt edit + migration together.diff --git a/scripts/migrations/056-manuscript-anchored-findings-prompt.js b/scripts/migrations/056-manuscript-anchored-findings-prompt.jsnew file mode 100644index 0000000000..3735beffce--- /dev/null+++ b/scripts/migrations/056-manuscript-anchored-findings-prompt.js@@ -0,0 +1,51 @@+/**+ * Add anchored findings to the manuscript-completeness ("Finish the draft")+ * prompt.+ *+ * The prompt previously returned findings with only a fuzzy human `location`+ * string. It now also returns a structured `issueNumber` plus a verbatim+ * `anchorQuote` excerpt, so the manuscript editor can map a finding to its+ * issue section and jump to the exact spot the gap occurs. See+ * server/services/pipeline/arcPlanner.js (shapeCompletenessFindings).+ *+ * `scripts/setup-data.js` only copies *missing* prompts, so existing installs+ * keep their old template until this migration rewrites it. Customization-safe:+ * only installs whose copy still hashes to the known pre-change shipped version+ * are auto-updated; customized prompts are left intact and warned about.+ *+ * Strategy: hash-driven prompt-replace via `./_lib.js`. Idempotent.+ */++import { makePromptReplaceMigration } from './_lib.js';++// Pre-change shipped hash (location-only findings).+export const ACCEPTED_OLD_MD5 = {+ 'pipeline-manuscript-completeness.md': ['e6858c74ab2cead752d388e3f428406c'],+};++// Post-change shipped hash (issueNumber + anchorQuote anchored findings).+// Mirror this into setup-data.js's drift table.+export const NEW_SHIPPED_MD5 = {+ 'pipeline-manuscript-completeness.md': '4f2b95778aed85f5fc461d71eb461b79',+};++const { applyMigration, up } = makePromptReplaceMigration({+ accepted: ACCEPTED_OLD_MD5,+ current: NEW_SHIPPED_MD5,+ label: 'manuscript-completeness anchored-findings prompt',+ customizedHint: (filename) =>+ ` To add anchored findings manually, diff:\n` ++ ` data.reference/prompts/stages/${filename}\n` ++ ` against your current:\n` ++ ` data/prompts/stages/${filename}\n` ++ ` and add the issueNumber + anchorQuote fields to the output contract.`,+ skipFooter: (count) =>+ `⚠️ ${count} prompt(s) could not be auto-updated because they were\n` ++ ` customized. "Finish the draft" still works, but its findings won't\n` ++ ` carry issueNumber/anchorQuote (so click-to-jump in the manuscript\n` ++ ` editor falls back to the fuzzy location text) until you merge the\n` ++ ` change. See data.reference/prompts/stages/pipeline-manuscript-completeness.md.`,+});++export { applyMigration };+export default { up };diff --git a/scripts/migrations/056-manuscript-anchored-findings-prompt.test.js b/scripts/migrations/056-manuscript-anchored-findings-prompt.test.jsnew file mode 100644index 0000000000..bb6af344b5--- /dev/null+++ b/scripts/migrations/056-manuscript-anchored-findings-prompt.test.js@@ -0,0 +1,14 @@+import { describe } from 'vitest';++import { runPromptMigrationTests } from './_testHelpers.js';+import migration, { applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5 } from './056-manuscript-anchored-findings-prompt.js';++describe('migration 056 — manuscript-completeness anchored findings prompt', () => {+ runPromptMigrationTests({+ migration,+ applyMigration,+ ACCEPTED_OLD_MD5,+ NEW_SHIPPED_MD5,+ prefix: 'migration-056-',+ });+});diff --git a/scripts/setup-data.js b/scripts/setup-data.jsindex bbab268ad8..a4711a339a 100644--- a/scripts/setup-data.js+++ b/scripts/setup-data.js@@ -186,6 +186,9 @@ const SHIPPED_PROMPT_OLD_MD5 = {// editorial-analysis: pre-042 (pipe-separated arcDirection enum + ≤160// excerpt) auto-updatable to the post-042 (single-value example, ≤200) hash.'pipeline-editorial-analysis.md': ['14d9879697c66d51830cc798040d5369'],+ // manuscript-completeness: pre-056 (location-only findings) auto-updatable to+ // the post-056 (issueNumber + anchorQuote anchored findings) hash.+ 'pipeline-manuscript-completeness.md': ['e6858c74ab2cead752d388e3f428406c'],// CoS agent prompt: drop obsolete "# Chief of Staff Agent Briefing" header// and "You are an autonomous agent…" preamble (migration 009). Every// historical shipped hash is auto-updatable to the new sample.@@ -214,6 +217,7 @@ const SHIPPED_PROMPT_NEW_MD5 = {'universe-character-expand.md':'67b6e73ed47f318451a730088b4cff14','story-builder-idea-expand.md':'c12d76fefaaded2838023065bfc94bb0','pipeline-editorial-analysis.md':'daeb02bd54b0c099b21af659c6298cfe',+ 'pipeline-manuscript-completeness.md':'4f2b95778aed85f5fc461d71eb461b79',};const SHIPPED_PROMPT_FILES = Object.keys(SHIPPED_PROMPT_OLD_MD5);diff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex bbb88acb81..d5f4f45a45 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -37,6 +37,8 @@ import * as seriesSvc from '../services/pipeline/series.js';import * as issuesSvc from '../services/pipeline/issues.js';import * as seasonsSvc from '../services/pipeline/seasons.js';import * as arcPlanner from '../services/pipeline/arcPlanner.js';+import * as manuscriptReview from '../services/pipeline/manuscriptReview.js';+import * as manuscriptFix from '../services/pipeline/manuscriptFix.js';import { generateStage } from '../services/pipeline/textStages.js';import * as autoRunner from '../services/pipeline/autoRunner.js';import * as editorialAnalysis from '../services/pipeline/editorialAnalysis.js';@@ -113,6 +115,9 @@ const SERVICE_ERROR_STATUS = {[seasonsSvc.ERR_VALIDATION]: 400,[seasonsSvc.ERR_REASSIGN_TARGET]: 400,[arcPlanner.ERR_VALIDATION]: 400,+ [manuscriptFix.ERR_VALIDATION]: 400,+ [manuscriptFix.ERR_NOT_FOUND]: 404,+ PIPELINE_REVIEW_NOT_FOUND: 404,[ERR_NO_STORYBOARDS]: 400,[ERR_NO_RENDERED_PAGES]: 409,[ERR_NO_VOLUME_COVER]: 409,@@ -217,6 +222,7 @@ const seriesCreateSchema = z.object({stylePromptOverride: z.string().trim().max(seriesSvc.STYLE_PROMPT_OVERRIDE_MAX).optional().default(''),stylePromptOverrideMode: z.enum(seriesSvc.STYLE_PROMPT_OVERRIDE_MODES).optional(),targetFormat: z.enum(seriesSvc.TARGET_FORMATS).optional(),+ primaryManuscriptType: z.enum(seriesSvc.MANUSCRIPT_TYPES).nullable().optional(),issueCountTarget: z.number().int().min(0).max(seriesSvc.ISSUE_COUNT_TARGET_MAX).optional(),llm: llmSchema,// Local-only "don't sync to peers" marker.@@ -238,6 +244,7 @@ const seriesPatchSchema = z.object({stylePromptOverride: z.string().trim().max(seriesSvc.STYLE_PROMPT_OVERRIDE_MAX).optional(),stylePromptOverrideMode: z.enum(seriesSvc.STYLE_PROMPT_OVERRIDE_MODES).optional(),targetFormat: z.enum(seriesSvc.TARGET_FORMATS).optional(),+ primaryManuscriptType: z.enum(seriesSvc.MANUSCRIPT_TYPES).nullable().optional(),issueCountTarget: z.number().int().min(0).max(seriesSvc.ISSUE_COUNT_TARGET_MAX).optional(),llm: llmSchema,ephemeral: z.boolean().optional(),@@ -586,6 +593,28 @@ const arcDeriveCommitSchema = z.object({// Manuscript-completeness ("finish the draft") editor pass — override shape only.const manuscriptCompletenessSchema = z.object(providerOverrideShape);+// Manuscript editor — review comment operations.+const manuscriptFixGenerateSchema = z.object(providerOverrideShape);+const manuscriptFixAcceptSchema = z.object({+ find: z.string().min(1).max(issuesSvc.STAGE_OUTPUT_MAX),+ replace: z.string().max(issuesSvc.STAGE_OUTPUT_MAX),+});+// Comment PATCH: status flip and/or attach/clear a fix. `.strict()` rejects+// stray keys; `fix` nullable so an explicit clear is distinguishable from absent.+const manuscriptCommentPatchSchema = z.object({+ status: z.enum(['open', 'accepted', 'dismissed']).optional(),+ fix: z.object({+ find: z.string().max(issuesSvc.STAGE_OUTPUT_MAX),+ replace: z.string().max(issuesSvc.STAGE_OUTPUT_MAX),+ fuzzy: z.boolean().optional(),+ }).nullable().optional(),+}).strict();+// Versioned free-text section save — writes one issue's manuscript stage.+const manuscriptSectionSaveSchema = z.object({+ stageId: z.enum(seriesSvc.MANUSCRIPT_TYPES),+ output: z.string().max(issuesSvc.STAGE_OUTPUT_MAX),+});+const autoRunSchema = z.object({providerId: z.string().trim().max(80).optional(),model: z.string().trim().max(200).optional(),@@ -1295,6 +1324,81 @@ router.post('/series/:id/manuscript/completeness', asyncHandler(async (req, res)const body = validateRequest(manuscriptCompletenessSchema, req.body ?? {});const result = await arcPlanner.analyzeManuscriptCompleteness(req.params.id, body).catch((err) => { throw mapServiceError(err); });+ // Persist findings as a Word-style comment set so the manuscript editor can+ // work through them across reloads. `issues` stays in the response for the+ // existing ArcHeader caller — the editor reads the merged `review`.+ const review = await manuscriptReview.seedReviewFromFindings(req.params.id, result.issues, { runId: result.runId })+ .catch((err) => { throw mapServiceError(err); });+ res.json({ ...result, review });+}));++// =====================+// Manuscript editor — full series manuscript + persisted editorial comments.+// The "manuscript" is virtual: one chosen stage per issue (comicScript ▸+// teleplay ▸ prose) concatenated in story order. Edits target a specific+// issue+stage; comments persist in data/pipeline-series/{id}/manuscript-review.json.+// =====================++// Full series manuscript in a chosen format (prose / teleplay / comic script).+// `?type=` selects the format; absent → the series' pinned primaryManuscriptType,+// else the auto-detected dominant format. Returns the requested format's+// sections plus the metadata the editor's format switcher needs.+router.get('/series/:id/manuscript', asyncHandler(async (req, res) => {+ const series = await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });+ const { sectionsByType, availableTypes, detectedPrimary } = await arcPlanner.collectManuscriptByType(req.params.id);+ // Resolve the primary (source-of-truth) format: pinned bible value wins, then+ // detection, then a stable default so the editor always has something to show.+ const primaryStageId = series.primaryManuscriptType || detectedPrimary || 'prose';+ const requested = seriesSvc.MANUSCRIPT_TYPES.includes(req.query.type) ? req.query.type : null;+ const viewType = requested || primaryStageId;+ res.json({+ sections: sectionsByType[viewType] || [],+ viewType,+ primaryStageId,+ pinnedPrimary: series.primaryManuscriptType || null,+ availableTypes,+ });+}));++router.get('/series/:id/manuscript/review', asyncHandler(async (req, res) => {+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });+ res.json(await manuscriptReview.getReview(req.params.id));+}));++router.patch('/series/:id/manuscript/review/comments/:commentId', asyncHandler(async (req, res) => {+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });+ const body = validateRequest(manuscriptCommentPatchSchema, req.body ?? {});+ const comment = await manuscriptReview.updateComment(req.params.id, req.params.commentId, body)+ .catch((err) => { throw mapServiceError(err); });+ res.json({ comment });+}));++// Generate an anchored find/replace fix for one comment (does not apply it).+router.post('/series/:id/manuscript/review/comments/:commentId/fix', asyncHandler(async (req, res) => {+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });+ const body = validateRequest(manuscriptFixGenerateSchema, req.body ?? {});+ const result = await manuscriptFix.generateManuscriptFix(req.params.id, { commentId: req.params.commentId, ...body })+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++// Apply an (optionally edited) fix into the issue's stage output + mark accepted.+router.post('/series/:id/manuscript/review/comments/:commentId/accept', asyncHandler(async (req, res) => {+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });+ const body = validateRequest(manuscriptFixAcceptSchema, req.body ?? {});+ const result = await manuscriptFix.acceptManuscriptFix(req.params.id, { commentId: req.params.commentId, ...body })+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++// Versioned free-text save of one manuscript section (snapshots the prior text+// into history so the edit is revertible). Revert reuses the stage-restore route+// (POST /issues/:id/stages/:stageId/restore).+router.put('/series/:id/manuscript/sections/:issueId', asyncHandler(async (req, res) => {+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });+ const body = validateRequest(manuscriptSectionSaveSchema, req.body ?? {});+ const result = await manuscriptFix.saveManuscriptSection(req.params.id, { issueId: req.params.issueId, ...body })+ .catch((err) => { throw mapServiceError(err); });res.json(result);}));diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.jsindex 0a05f3f403..439a67e314 100644--- a/server/routes/pipeline.test.js+++ b/server/routes/pipeline.test.js@@ -2021,6 +2021,94 @@ describe('pipeline routes', () => {expect(r.status).toBe(200);expect(r.body.issues[0].category).toBe('missing-content');expect(completenessSpy).toHaveBeenCalledWith(ser.body.id, expect.any(Object));+ // The completeness pass also seeds a persisted review the editor reads.+ expect(Array.isArray(r.body.review?.comments)).toBe(true);+ });++ describe('manuscript editor routes', () => {+ it('GET /series/:id/manuscript returns sections + primaryStageId; review starts empty', 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: 'One' });+ await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({+ stages: { prose: { output: 'A drafted scene.', status: 'ready' } },+ });+ const ms = await request(app).get(`/api/pipeline/series/${ser.body.id}/manuscript`);+ expect(ms.status).toBe(200);+ expect(ms.body.sections).toHaveLength(1);+ expect(ms.body.sections[0]).toMatchObject({ stageId: 'prose', content: 'A drafted scene.' });+ expect(ms.body.primaryStageId).toBe('prose');++ const review = await request(app).get(`/api/pipeline/series/${ser.body.id}/manuscript/review`);+ expect(review.status).toBe(200);+ expect(review.body.comments).toEqual([]);+ });++ it('switches manuscript format via ?type and reports the pinned primary', 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: 'One' });+ await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({+ stages: {+ prose: { output: 'Prose draft.', status: 'ready' },+ teleplay: { output: 'INT. ROOM - DAY', status: 'ready' },+ },+ });+ // Default view resolves to the detected dominant format; availableTypes lists both.+ const def = await request(app).get(`/api/pipeline/series/${ser.body.id}/manuscript`);+ expect(def.body.availableTypes.sort()).toEqual(['prose', 'teleplay']);+ // Explicit format switch.+ const tele = await request(app).get(`/api/pipeline/series/${ser.body.id}/manuscript?type=teleplay`);+ expect(tele.body.viewType).toBe('teleplay');+ expect(tele.body.sections[0].content).toBe('INT. ROOM - DAY');+ // Pin a primary in the bible; it round-trips on the next load.+ await request(app).patch(`/api/pipeline/series/${ser.body.id}`).send({ primaryManuscriptType: 'teleplay' });+ const pinned = await request(app).get(`/api/pipeline/series/${ser.body.id}/manuscript`);+ expect(pinned.body.pinnedPrimary).toBe('teleplay');+ expect(pinned.body.viewType).toBe('teleplay');+ });++ it('PUT section save versions the edit; restore reverts it', 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: 'One' });+ await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({+ stages: { prose: { output: 'First draft.', status: 'ready' } },+ });+ // Versioned save snapshots the prior text.+ const saved = await request(app)+ .put(`/api/pipeline/series/${ser.body.id}/manuscript/sections/${iss.body.id}`)+ .send({ stageId: 'prose', output: 'Second draft.' });+ expect(saved.status).toBe(200);+ expect(saved.body.section.content).toBe('Second draft.');+ expect(saved.body.section.versions).toHaveLength(1);+ // Revert through the stage-restore route.+ const runId = saved.body.section.versions[0].runId;+ const restored = await request(app)+ .post(`/api/pipeline/issues/${iss.body.id}/stages/prose/restore`)+ .send({ runId });+ expect(restored.status).toBe(200);+ expect(restored.body.stage.output).toBe('First draft.');+ // Non-manuscript stage is rejected.+ const bad = await request(app)+ .put(`/api/pipeline/series/${ser.body.id}/manuscript/sections/${iss.body.id}`)+ .send({ stageId: 'idea', output: 'x' });+ expect(bad.status).toBe(400);+ });++ it('PATCH unknown comment is a 404; accept rejects a missing find with a 400', async () => {+ const app = makeApp();+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });+ const patch = await request(app)+ .patch(`/api/pipeline/series/${ser.body.id}/manuscript/review/comments/mrc-nope`)+ .send({ status: 'dismissed' });+ expect(patch.status).toBe(404);++ const accept = await request(app)+ .post(`/api/pipeline/series/${ser.body.id}/manuscript/review/comments/mrc-nope/accept`)+ .send({ replace: 'x' }); // missing required `find`+ expect(accept.status).toBe(400);+ });});describe('audio stage routes', () => {diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.jsindex 2632ec063c..16006aaaa3 100644--- a/server/services/pipeline/arcPlanner.js+++ b/server/services/pipeline/arcPlanner.js@@ -22,7 +22,7 @@import { runStagedLLM } from '../../lib/stageRunner.js';import { ServerError } from '../../lib/errorHandler.js';import { stripAnsi } from '../../lib/ansiStrip.js';-import { getSeries, updateSeries, updateSeasonOnSeries, ARC_LOCKABLE_FIELDS } from './series.js';+import { getSeries, updateSeries, updateSeasonOnSeries, ARC_LOCKABLE_FIELDS, MANUSCRIPT_TYPES } from './series.js';import { listIssues, updateIssue, recomputeIssueNumbersForSeries, getIssue, updateStage, updateStageWithLatest, assertStageUnlocked } from './issues.js';import { emitRecordUpdated, withReexportSuppressed } from '../sharing/recordEvents.js';import { getSeason } from './seasons.js';@@ -170,12 +170,16 @@ const BACKFILL_SOURCE_MAX = 200_000;// question — "does this stage have ANY content to use as a generation source".)const stageTextOf = (stage) => (stage?.output?.trim() || stage?.input?.trim() || '');+// The drafted-manuscript stages, in precedence order. Single source of truth is+// `MANUSCRIPT_TYPES` in series.js (which series.js needs for the bible field and+// arcPlanner already imports — so no new cycle). Re-exported under the+// historical name for the existing importers.+export const MANUSCRIPT_STAGES = MANUSCRIPT_TYPES;// Default stage precedence: the richest authored artifact per issue. `idea`// (the outline/synopsis seed) is the lowest-priority fallback — it lets an// arc be back-derived from outlines alone. Callers that specifically mean// "the DRAFTED MANUSCRIPT" must pass MANUSCRIPT_STAGES to exclude it.-const SOURCE_STAGE_ORDER = ['comicScript', 'teleplay', 'prose', 'idea'];-export const MANUSCRIPT_STAGES = ['comicScript', 'teleplay', 'prose'];+const SOURCE_STAGE_ORDER = [...MANUSCRIPT_STAGES, 'idea'];/*** Concatenate the richest authored artifact per issue into one corpus an@@ -192,19 +196,99 @@ export const MANUSCRIPT_STAGES = ['comicScript', 'teleplay', 'prose'];* Shared by `deriveFromManuscript` here and the Story Builder's plotArc/idea* backfill (storyBuilder.js) so both see the identical corpus shape.*/-export async function collectIssueSourceText(seriesId, { stageOrder = SOURCE_STAGE_ORDER } = {}) {- if (!seriesId) return '';+export async function collectManuscriptSections(seriesId, { stageOrder = MANUSCRIPT_STAGES } = {}) {+ if (!seriesId) return [];const issues = (await listIssues({ seriesId }).catch(() => [])).sort(compareIssuesByPosition);- const parts = [];+ const sections = [];for (const iss of issues) {const st = iss.stages || {};const pick = stageOrder.map((sid) => ({ sid, content: stageTextOf(st[sid]) })).find((x) => x.content);if (!pick) continue;- parts.push(`# Issue ${iss.number}${iss.title ? ` — ${iss.title}` : ''} (${pick.sid})\n\n${pick.content}`);+ sections.push({+ issueId: iss.id,+ number: iss.number,+ title: iss.title || '',+ stageId: pick.sid,+ content: pick.content,+ });+ }+ return sections;+}++// Header for one manuscript section. The corpus join below derives from+// `collectManuscriptSections` so the text the LLM sees stays byte-identical to+// the per-section text the editor renders — anchorQuote/find matching depends+// on that invariant.+const manuscriptSectionHeader = (s) => `# Issue ${s.number}${s.title ? ` — ${s.title}` : ''} (${s.stageId})`;++export async function collectIssueSourceText(seriesId, { stageOrder = SOURCE_STAGE_ORDER } = {}) {+ if (!seriesId) return '';+ const sections = await collectManuscriptSections(seriesId, { stageOrder });+ return sections+ .map((s) => `${manuscriptSectionHeader(s)}\n\n${s.content}`)+ .join('\n\n---\n\n')+ .slice(0, BACKFILL_SOURCE_MAX);+}++// Lightweight version list for a stage — `{ runId, createdAt }` per retained+// prior version (full text stays in the issue record, fetched on revert via the+// restore route). Lets the editor show "History (N)" + revert without shipping+// every snapshot's text in the manuscript payload.+export const stageVersionsOf = (stage) =>+ (Array.isArray(stage?.runHistory) ? stage.runHistory : [])+ .map((h) => ({ runId: h.runId, createdAt: h.createdAt }));++// The dominant manuscript type across the series' sections — the editor's+// display "mode". Per-section stageId stays authoritative for writes.+export function primaryStageIdOf(sections) {+ const counts = new Map();+ for (const s of sections) counts.set(s.stageId, (counts.get(s.stageId) || 0) + 1);+ let best = null;+ let bestN = 0;+ for (const [sid, n] of counts) if (n > bestN) { best = sid; bestN = n; }+ return best;+}++/**+ * Collect the FULL series manuscript in every format at once, for the+ * format-switching manuscript editor. Unlike `collectManuscriptSections`+ * (which picks one richest stage per issue), this returns a complete+ * issue-by-issue section list for EACH of comicScript / teleplay / prose —+ * every issue appears in every format's list (content `''` where that issue+ * hasn't been drafted in that format yet) so the editor spans the whole story+ * and the author can fill gaps. One issue scan feeds all three.+ *+ * Returns `{ sectionsByType, availableTypes, detectedPrimary }`:+ * - sectionsByType[stageId] = [{ issueId, number, title, stageId, content }]+ * - availableTypes = the formats that have content in ≥1 issue+ * - detectedPrimary = the format with the most drafted issues (the+ * fallback when the series hasn't pinned one)+ */+export async function collectManuscriptByType(seriesId) {+ // Derive the accumulators from MANUSCRIPT_STAGES so a new format added there+ // can't desync into a missing key (a `.push` on undefined).+ const sectionsByType = Object.fromEntries(MANUSCRIPT_STAGES.map((t) => [t, []]));+ const counts = Object.fromEntries(MANUSCRIPT_STAGES.map((t) => [t, 0]));+ if (!seriesId) return { sectionsByType, availableTypes: [], detectedPrimary: null };+ const issues = (await listIssues({ seriesId }).catch(() => [])).sort(compareIssuesByPosition);+ for (const iss of issues) {+ const st = iss.stages || {};+ for (const sid of MANUSCRIPT_STAGES) {+ const content = stageTextOf(st[sid]);+ sectionsByType[sid].push({+ issueId: iss.id, number: iss.number, title: iss.title || '', stageId: sid, content,+ versions: stageVersionsOf(st[sid]),+ });+ if (content) counts[sid] += 1;+ }}- return parts.join('\n\n---\n\n').slice(0, BACKFILL_SOURCE_MAX);+ const availableTypes = MANUSCRIPT_STAGES.filter((t) => counts[t] > 0);+ let detectedPrimary = null;+ let best = 0;+ for (const t of MANUSCRIPT_STAGES) if (counts[t] > best) { detectedPrimary = t; best = counts[t]; }+ return { sectionsByType, availableTypes, detectedPrimary };}// Series + world + arc fields shared by every arc-level prompt context.@@ -603,6 +687,11 @@ function shapeCompletenessFindings(rawIssues) {location: typeof raw?.location === 'string' ? raw.location.trim().slice(0, 200) : '',problem: problem.slice(0, 2000),suggestion: typeof raw?.suggestion === 'string' ? raw.suggestion.trim().slice(0, 2000) : '',+ // Structured anchor: lets the editor map a finding to its issue section+ // and jump to the verbatim excerpt. Both optional — older runs and+ // un-anchorable findings still render (just without click-to-jump).+ issueNumber: Number.isInteger(raw?.issueNumber) ? raw.issueNumber : null,+ anchorQuote: typeof raw?.anchorQuote === 'string' ? raw.anchorQuote.trim().slice(0, 400) : '',});}return out;diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.jsindex b8bd8131e3..5c6bd4fae9 100644--- a/server/services/pipeline/arcPlanner.test.js+++ b/server/services/pipeline/arcPlanner.test.js@@ -1540,6 +1540,44 @@ describe('arcPlanner — manuscript completeness + derive-from-manuscript', () =await expect(planner.analyzeManuscriptCompleteness(s.id)).rejects.toMatchObject({ code: 'PIPELINE_ARC_VALIDATION' });});+ it('analyzeManuscriptCompleteness carries issueNumber + anchorQuote and tolerates their absence', async () => {+ const s = await setupSeries();+ await issuesSvc.createIssue({ seriesId: s.id, title: 'One', arcPosition: 1, stages: { prose: { output: 'A short draft.', status: 'ready' } } });+ stageRunnerSpy = vi.fn(async () => ({+ content: { issues: [+ { severity: 'high', category: 'arc-gap', issueNumber: 1, anchorQuote: ' a quote ', problem: 'anchored', suggestion: 'fix it' },+ { severity: 'low', category: 'pacing', problem: 'unanchored', suggestion: '' },+ ] },+ runId: 'rc', providerId: 'p', model: 'm',+ }));+ const out = await planner.analyzeManuscriptCompleteness(s.id);+ expect(out.issues[0]).toMatchObject({ issueNumber: 1, anchorQuote: 'a quote' });+ expect(out.issues[1]).toMatchObject({ issueNumber: null, anchorQuote: '' });+ });++ it('collectManuscriptSections orders by arcPosition, drops empties, and collectIssueSourceText stays byte-identical', async () => {+ const s = await setupSeries();+ // Insert out of arcPosition order to prove sorting (don't assert on the+ // auto-assigned `number`, which follows creation order, not arcPosition).+ await issuesSvc.createIssue({ seriesId: s.id, title: 'Two', arcPosition: 2, stages: { teleplay: { output: 'TELE two', status: 'ready' } } });+ await issuesSvc.createIssue({ seriesId: s.id, title: 'One', arcPosition: 1, stages: { comicScript: { output: 'PAGE 1\none', status: 'ready' } } });+ await issuesSvc.createIssue({ seriesId: s.id, title: 'Empty', arcPosition: 3 });++ const sections = await planner.collectManuscriptSections(s.id);+ // Empty issue dropped; remaining two ordered by arcPosition (One before Two).+ expect(sections.map((x) => x.content)).toEqual(['PAGE 1\none', 'TELE two']);+ expect(sections.map((x) => x.stageId)).toEqual(['comicScript', 'teleplay']);+ expect(sections.map((x) => x.title)).toEqual(['One', 'Two']);+ expect(planner.primaryStageIdOf(sections)).toBeDefined();++ // The corpus join derives from the sections — verify the invariant.+ const corpus = await planner.collectIssueSourceText(s.id, { stageOrder: planner.MANUSCRIPT_STAGES });+ const expected = sections+ .map((x) => `# Issue ${x.number} — ${x.title} (${x.stageId})\n\n${x.content}`)+ .join('\n\n---\n\n');+ expect(corpus).toBe(expected);+ });+it('deriveFromManuscript proposes a single volume + bible + zipped issue synopses', async () => {const s = await setupSeries();const sea = await seasonsSvc.createSeason(s.id, { title: 'V1', episodeCountTarget: 3 });diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex c60fcc7a03..42e55e36f0 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -259,18 +259,23 @@ const sanitizeTextStage = (raw) => ({* editing the existing version, not replacing it. The previous run remains* the active version; the next generate will snapshot it.*/-export function snapshotRunHistory(prevStage, patch, stageId) {+export function snapshotRunHistory(prevStage, patch, stageId, { force = false } = {}) {const prevHistory = Array.isArray(prevStage?.runHistory) ? prevStage.runHistory : [];if (!patch || typeof patch !== 'object') return prevHistory;if (!TEXT_STAGE_IDS.includes(stageId)) return prevHistory;const nextRunId = isStr(patch.lastRunId) ? patch.lastRunId : '';if (!nextRunId) return prevHistory;if (nextRunId === prevStage?.lastRunId) return prevHistory;- if (!prevStage?.lastRunId) return prevHistory;- const prevOutput = prevStage.output || '';+ // Default: only snapshot a prior that was itself a recorded run (keeps the+ // first generate from snapshotting an empty/seed-only stage). With `force`+ // (manuscript-editor edits), snapshot ANY non-empty prior, synthesizing an id+ // when the prior was never a run — so imported/hand-typed text stays+ // revertible from its very first edit.+ if (!prevStage?.lastRunId && !force) return prevHistory;+ const prevOutput = prevStage?.output || '';if (!prevOutput.trim()) return prevHistory;const snapshot = {- runId: prevStage.lastRunId,+ runId: prevStage.lastRunId || `pre-${nextRunId}`,createdAt: prevStage.updatedAt || new Date().toISOString(),input: prevStage.input || '',output: prevOutput,@@ -971,7 +976,7 @@ export function deleteIssue(id) {* inside the queue; its return value is shallow-merged over the stage exactly* as `updateStage` merges a static patch.*/-export function updateStageWithLatest(issueId, stageId, computeFn) {+export function updateStageWithLatest(issueId, stageId, computeFn, { snapshotPrior = false } = {}) {if (!STAGE_IDS.includes(stageId)) {// Validate before queueing so the caller gets an immediate rejection// rather than waiting in line for an error it already knows about.@@ -1003,7 +1008,7 @@ export function updateStageWithLatest(issueId, stageId, computeFn) {// Snapshot the prior `{ runId, input, output }` into runHistory when this// patch carries a fresh lastRunId (i.e. a generate just replaced prior// content). Computed BEFORE the spread so it reads pre-merge state.- const nextRunHistory = snapshotRunHistory(currentStage, patch, stageId);+ const nextRunHistory = snapshotRunHistory(currentStage, patch, stageId, { force: snapshotPrior });const merged = {...currentStage,...patch,diff --git a/server/services/pipeline/manuscriptEditor.test.js b/server/services/pipeline/manuscriptEditor.test.jsnew file mode 100644index 0000000000..779bd430db--- /dev/null+++ b/server/services/pipeline/manuscriptEditor.test.js@@ -0,0 +1,188 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { mockNoPeerSync, mockNoPeers } from '../../lib/mockPathsDataRoot.js';++const fileStore = new Map();+let stageRunnerSpy;++vi.mock('../../lib/fileUtils.js', () => ({+ tryReadFile: vi.fn().mockResolvedValue(null),+ PATHS: { data: '/mock/data' },+ ensureDir: vi.fn().mockResolvedValue(undefined),+ atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),+ readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),+}));++let uuidCounter = 0;+vi.mock('crypto', async () => {+ const actual = await vi.importActual('crypto');+ return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };+});++vi.mock('../instances.js', () => mockNoPeers());+vi.mock('../sharing/peerSync.js', () => mockNoPeerSync());++vi.mock('../../lib/stageRunner.js', () => ({+ runStagedLLM: vi.fn((...args) => stageRunnerSpy(...args)),+ extractJson: (raw) => JSON.parse(raw),+}));++const seriesSvc = await import('./series.js');+const issuesSvc = await import('./issues.js');+const review = await import('./manuscriptReview.js');+const fixer = await import('./manuscriptFix.js');++async function setupSeriesWithDraft(output = 'The hero walked in. She left.') {+ const s = await seriesSvc.createSeries({ name: 'Draft', logline: 'lg', premise: 'pr', issueCountTarget: 1 });+ const issue = await issuesSvc.createIssue({+ seriesId: s.id, number: 1, title: 'One', arcPosition: 1,+ stages: { prose: { output, status: 'ready' } },+ });+ return { s, issue };+}++const finding = (over = {}) => ({+ severity: 'high', category: 'arc-gap', issueNumber: 1,+ anchorQuote: 'She left.', problem: 'abrupt ending', suggestion: 'add a beat', ...over,+});++beforeEach(() => {+ fileStore.clear();+ uuidCounter = 0;+ stageRunnerSpy = undefined;+});++describe('manuscriptReview', () => {+ it('getReview returns an empty review when none exists', async () => {+ const { s } = await setupSeriesWithDraft();+ expect(await review.getReview(s.id)).toEqual({ schemaVersion: 1, comments: [] });+ });++ it('seedReviewFromFindings resolves issueId/stageId from the manuscript section', async () => {+ const { s, issue } = await setupSeriesWithDraft();+ const seeded = await review.seedReviewFromFindings(s.id, [finding()], { runId: 'r1' });+ expect(seeded.comments).toHaveLength(1);+ expect(seeded.comments[0]).toMatchObject({ issueNumber: 1, issueId: issue.id, stageId: 'prose', status: 'open', sourceRunId: 'r1' });+ });++ it('seedReviewFromFindings dedupes identical findings but preserves resolved ones', async () => {+ const { s } = await setupSeriesWithDraft();+ const first = await review.seedReviewFromFindings(s.id, [finding()]);+ // Dismiss it, then re-seed the same finding + a new one.+ await review.updateComment(s.id, first.comments[0].id, { status: 'dismissed' });+ const second = await review.seedReviewFromFindings(s.id, [finding(), finding({ problem: 'new gap', anchorQuote: 'walked in.' })]);+ // The dismissed one is kept (not re-opened as a dup), only the genuinely new finding is added.+ expect(second.comments).toHaveLength(2);+ expect(second.comments.find((c) => c.status === 'dismissed')).toBeTruthy();+ expect(second.comments.find((c) => c.problem === 'new gap')).toBeTruthy();+ });++ it('seedReviewFromFindings preserves an in-progress open comment (and its fix) on re-run', async () => {+ const { s } = await setupSeriesWithDraft();+ const first = await review.seedReviewFromFindings(s.id, [finding()]);+ // User generated a fix but hasn't accepted yet — must not be wiped by a re-run.+ await review.updateComment(s.id, first.comments[0].id, { fix: { find: 'She left.', replace: 'She left, slowly.' } });+ const second = await review.seedReviewFromFindings(s.id, [finding(), finding({ problem: 'new gap', anchorQuote: 'walked in.' })]);+ const original = second.comments.find((c) => c.problem === 'abrupt ending');+ expect(original).toBeTruthy();+ expect(original.status).toBe('open');+ expect(original.fix).toMatchObject({ replace: 'She left, slowly.' });+ expect(second.comments).toHaveLength(2); // original preserved + 1 new, no duplicate+ });++ it('updateComment flips status and attaches a fix, last-write-wins on updatedAt', async () => {+ const { s } = await setupSeriesWithDraft();+ const seeded = await review.seedReviewFromFindings(s.id, [finding()]);+ const id = seeded.comments[0].id;+ const withFix = await review.updateComment(s.id, id, { fix: { find: 'She left.', replace: 'She left, slowly.' } });+ expect(withFix.fix).toMatchObject({ find: 'She left.', replace: 'She left, slowly.' });+ await expect(review.updateComment(s.id, 'mrc-nope', { status: 'open' })).rejects.toMatchObject({ code: 'PIPELINE_REVIEW_NOT_FOUND' });+ });++ it('mergeReviewFromSync takes the newer comment per id', async () => {+ const { s } = await setupSeriesWithDraft();+ const seeded = await review.seedReviewFromFindings(s.id, [finding()]);+ const remote = {+ schemaVersion: 1,+ comments: [{ ...seeded.comments[0], status: 'accepted', updatedAt: '2999-01-01T00:00:00.000Z' }],+ };+ const merged = await review.mergeReviewFromSync(s.id, remote);+ expect(merged.comments[0].status).toBe('accepted');+ });+});++describe('manuscriptFix', () => {+ it('generateManuscriptFix persists an anchored fix and flags non-verbatim find as fuzzy', async () => {+ const { s } = await setupSeriesWithDraft();+ const seeded = await review.seedReviewFromFindings(s.id, [finding()]);+ const id = seeded.comments[0].id;++ stageRunnerSpy = vi.fn(async (template) => {+ expect(template).toBe('pipeline-manuscript-fix');+ return { content: { find: 'She left.', replace: 'She left, but paused at the door.' }, runId: 'rf' };+ });+ const ok = await fixer.generateManuscriptFix(s.id, { commentId: id });+ expect(ok.fix).toMatchObject({ find: 'She left.' });+ expect(ok.fix.fuzzy).toBeUndefined();+ expect(ok.comment.fix.replace).toContain('paused');++ stageRunnerSpy = vi.fn(async () => ({ content: { find: 'NOT IN TEXT', replace: 'whatever' }, runId: 'rf2' }));+ const fuzzy = await fixer.generateManuscriptFix(s.id, { commentId: id });+ expect(fuzzy.fix.fuzzy).toBe(true);+ });++ it('acceptManuscriptFix applies the find/replace to the stage output and marks the comment accepted', async () => {+ const { s, issue } = await setupSeriesWithDraft();+ const seeded = await review.seedReviewFromFindings(s.id, [finding()]);+ const id = seeded.comments[0].id;++ const result = await fixer.acceptManuscriptFix(s.id, { commentId: id, find: 'She left.', replace: 'She left, but paused.' });+ expect(result.comment.status).toBe('accepted');+ expect(result.section.content).toBe('The hero walked in. She left, but paused.');++ const after = await issuesSvc.getIssue(issue.id);+ expect(after.stages.prose.output).toBe('The hero walked in. She left, but paused.');+ });++ it('acceptManuscriptFix throws when the anchor text is gone', async () => {+ const { s } = await setupSeriesWithDraft();+ const seeded = await review.seedReviewFromFindings(s.id, [finding()]);+ await expect(+ fixer.acceptManuscriptFix(s.id, { commentId: seeded.comments[0].id, find: 'GONE', replace: 'x' }),+ ).rejects.toMatchObject({ code: 'PIPELINE_MANUSCRIPT_FIX_VALIDATION' });+ });++ it('acceptManuscriptFix snapshots the pre-fix text even on an imported stage (no prior runId)', async () => {+ const { s, issue } = await setupSeriesWithDraft();+ const seeded = await review.seedReviewFromFindings(s.id, [finding()]);+ const result = await fixer.acceptManuscriptFix(s.id, { commentId: seeded.comments[0].id, find: 'She left.', replace: 'She left, but paused.' });+ // The original imported text is now revertible from history.+ expect(result.section.versions.length).toBe(1);+ const after = await issuesSvc.getIssue(issue.id);+ expect(after.stages.prose.runHistory[0].output).toBe('The hero walked in. She left.');+ });+});++describe('saveManuscriptSection (versioned free-text edit)', () => {+ it('writes the new output and snapshots the prior text for revert', async () => {+ const { s, issue } = await setupSeriesWithDraft('Original prose.');+ const out = await fixer.saveManuscriptSection(s.id, { issueId: issue.id, stageId: 'prose', output: 'Edited prose.' });+ expect(out.section.content).toBe('Edited prose.');+ expect(out.section.versions.length).toBe(1); // prior version retained++ const after = await issuesSvc.getIssue(issue.id);+ expect(after.stages.prose.output).toBe('Edited prose.');+ expect(after.stages.prose.runHistory[0].output).toBe('Original prose.');++ // Revert restores the original through the existing restore path.+ const runId = out.section.versions[0].runId;+ const { stage } = await issuesSvc.restoreStageFromHistory(issue.id, 'prose', runId);+ expect(stage.output).toBe('Original prose.');+ });++ it('rejects a non-manuscript stage', async () => {+ const { s, issue } = await setupSeriesWithDraft();+ await expect(+ fixer.saveManuscriptSection(s.id, { issueId: issue.id, stageId: 'idea', output: 'x' }),+ ).rejects.toMatchObject({ code: 'PIPELINE_MANUSCRIPT_FIX_VALIDATION' });+ });+});diff --git a/server/services/pipeline/manuscriptFix.js b/server/services/pipeline/manuscriptFix.jsnew file mode 100644index 0000000000..2c71fbdad5--- /dev/null+++ b/server/services/pipeline/manuscriptFix.js@@ -0,0 +1,165 @@+/**+ * Pipeline — Manuscript Fix generation + accept+ *+ * Turns a "Finish the draft" comment into a surgical, anchored edit. The LLM+ * returns `{ find, replace }` where `find` is a verbatim excerpt of the issue's+ * drafted stage text and `replace` is that excerpt rewritten to close the gap.+ * The user can edit `replace` before accepting; accept applies the find/replace+ * to the issue's stage output through the serialized stage-write path (which+ * snapshots the prior text into runHistory).+ *+ * Read this alongside manuscriptReview.js (where the comment + fix persist) and+ * arcPlanner.js (which owns the completeness pass that creates the comments).+ */++import { randomUUID } from 'crypto';+import { runStagedLLM } from '../../lib/stageRunner.js';+import { getSeries, MANUSCRIPT_TYPES } from './series.js';+import { getIssue, updateStageWithLatest } from './issues.js';+import { collectManuscriptSections, stageVersionsOf } from './arcPlanner.js';+import { getComment, updateComment } from './manuscriptReview.js';++export const ERR_VALIDATION = 'PIPELINE_MANUSCRIPT_FIX_VALIDATION';+export const ERR_NOT_FOUND = 'PIPELINE_MANUSCRIPT_FIX_NOT_FOUND';+const makeErr = (message, code) => Object.assign(new Error(message), { code });++// Output before input: the drafted artifact wins over the upstream seed.+// Mirrors arcPlanner's stageTextOf (inlined there to avoid an import cycle).+const stageTextOf = (stage) => (stage?.output?.trim() || stage?.input?.trim() || '');++// Resolve which issue+stage a comment edits. Prefer the ids stored on the+// comment at seed time; fall back to matching issueNumber against the current+// manuscript sections (the manuscript may have grown since the comment was+// created). Returns { issueId, stageId } or throws ERR_VALIDATION.+async function resolveTarget(seriesId, comment) {+ if (comment.issueId && comment.stageId) {+ return { issueId: comment.issueId, stageId: comment.stageId };+ }+ const sections = await collectManuscriptSections(seriesId);+ const section = comment.issueNumber != null+ ? sections.find((s) => s.number === comment.issueNumber)+ : null;+ if (!section) {+ throw makeErr(+ 'This comment is not anchored to a specific issue — edit the manuscript directly to address it',+ ERR_VALIDATION,+ );+ }+ return { issueId: section.issueId, stageId: section.stageId };+}++async function loadStageText(issueId, stageId) {+ const issue = await getIssue(issueId).catch(() => null);+ if (!issue) throw makeErr(`Issue not found: ${issueId}`, ERR_NOT_FOUND);+ return stageTextOf(issue.stages?.[stageId]);+}++// Shape one manuscript section response from a freshly-written stage.+const sectionFrom = (issue, stageId, stage) => ({+ issueId: issue.id,+ number: issue.number,+ title: issue.title || '',+ stageId,+ content: stageTextOf(stage),+ versions: stageVersionsOf(stage),+});++/**+ * Free-text manuscript edit, versioned. Writes `output` to the issue's stage and+ * snapshots the PRIOR text into runHistory (via `snapshotPrior`) so every saved+ * edit is revertible — including the first edit of an imported stage that never+ * had a run id. A fresh `lastRunId` makes the new version itself restorable.+ */+export async function saveManuscriptSection(seriesId, { issueId, stageId, output } = {}) {+ if (!MANUSCRIPT_TYPES.includes(stageId)) {+ throw makeErr(`Not an editable manuscript stage: ${stageId}`, ERR_VALIDATION);+ }+ const { issue, stage } = await updateStageWithLatest(+ issueId,+ stageId,+ () => ({ output, status: 'edited', lastRunId: `edit-${randomUUID()}` }),+ { snapshotPrior: true },+ );+ return { section: sectionFrom(issue, stageId, stage) };+}++/**+ * Generate an anchored find/replace fix for a comment and persist it on the+ * comment (status stays `open` — the user still has to accept). When the LLM's+ * `find` can't be located verbatim in the current stage text, the fix is+ * flagged `fuzzy: true` so the client falls back to manual editing rather than+ * a write that would silently miss.+ */+export async function generateManuscriptFix(seriesId, { commentId, providerOverride, modelOverride } = {}) {+ const series = await getSeries(seriesId);+ const comment = await getComment(seriesId, commentId);+ if (!comment) throw makeErr(`Comment not found: ${commentId}`, ERR_NOT_FOUND);++ const { issueId, stageId } = await resolveTarget(seriesId, comment);+ const manuscript = await loadStageText(issueId, stageId);+ if (!manuscript) {+ throw makeErr('That issue has no drafted text to edit', ERR_VALIDATION);+ }++ const arc = series.arc || {};+ const ctx = {+ series: { name: series.name, logline: series.logline, premise: series.premise },+ arc: {+ logline: arc.logline || '',+ themesCsv: Array.isArray(arc.themes) ? arc.themes.join(', ') : '',+ },+ manuscript,+ finding: {+ category: comment.category,+ severity: comment.severity,+ problem: comment.problem,+ suggestion: comment.suggestion,+ anchorQuote: comment.anchorQuote,+ },+ };++ const { content, runId } = await runStagedLLM('pipeline-manuscript-fix', ctx, {+ providerOverride,+ modelOverride,+ returnsJson: true,+ source: 'pipeline-manuscript-fix',+ });++ const find = typeof content?.find === 'string' ? content.find : '';+ const replace = typeof content?.replace === 'string' ? content.replace : '';+ if (!replace) throw makeErr('The model did not return a usable fix — try again', ERR_VALIDATION);+ const fix = { find, replace };+ // A `find` that isn't present verbatim can't be applied surgically; mark it+ // so the UI offers manual editing instead of a no-op accept.+ if (find && !manuscript.includes(find)) fix.fuzzy = true;++ const updated = await updateComment(seriesId, commentId, { fix });+ return { comment: updated, fix, runId };+}++/**+ * Apply an (optionally user-edited) find/replace to the issue's stage output and+ * mark the comment accepted. Serialized through `updateStageWithLatest`, which+ * snapshots the prior output into runHistory when a fresh run id is stamped.+ * Returns the refreshed manuscript section + the accepted comment.+ */+export async function acceptManuscriptFix(seriesId, { commentId, find, replace } = {}) {+ const comment = await getComment(seriesId, commentId);+ if (!comment) throw makeErr(`Comment not found: ${commentId}`, ERR_NOT_FOUND);+ const { issueId, stageId } = await resolveTarget(seriesId, comment);++ const { issue, stage } = await updateStageWithLatest(issueId, stageId, (cur) => {+ const text = stageTextOf(cur);+ const idx = text.indexOf(find);+ if (idx === -1) {+ throw makeErr('Anchor text is no longer present in the manuscript — regenerate the fix', ERR_VALIDATION);+ }+ const next = text.slice(0, idx) + replace + text.slice(idx + find.length);+ // Fresh run id + snapshotPrior so the pre-fix text is preserved in history+ // and this accepted version is itself revertible later.+ return { output: next, status: 'edited', lastRunId: `fix-${randomUUID()}` };+ }, { snapshotPrior: true });++ const updated = await updateComment(seriesId, commentId, { status: 'accepted' });+ return { comment: updated, section: sectionFrom(issue, stageId, stage) };+}diff --git a/server/services/pipeline/manuscriptReview.js b/server/services/pipeline/manuscriptReview.jsnew file mode 100644index 0000000000..d8b097c2c4--- /dev/null+++ b/server/services/pipeline/manuscriptReview.js@@ -0,0 +1,202 @@+/**+ * Pipeline — Manuscript Review ("Finish the draft" comments)+ *+ * Persists the editorial findings from the manuscript-completeness pass as a+ * Word-style comment set the user works through in the manuscript editor:+ * each comment can be jumped-to, given an AI fix, edited, and accepted into the+ * manuscript (or dismissed). Findings are otherwise ephemeral — this is what+ * makes "Finish the draft" actionable across reloads.+ *+ * Stored as a sibling of the series record at+ * `data/pipeline-series/{id}/manuscript-review.json`, so it travels with the+ * series folder on share/sync without bloating the LWW-merged series+ * `index.json` (the review is an independent, larger document with its own+ * write cadence). Writes serialize on a per-series tail (single tail per shared+ * file, per CLAUDE.md).+ */++import { join } from 'path';+import { randomUUID } from 'crypto';+import { atomicWrite, readJSONFile } from '../../lib/fileUtils.js';+import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';+import { seriesStore } from './series.js';+import { collectManuscriptSections } from './arcPlanner.js';++// Storage-layout version for the review document. Bump + migrate if the+// comment shape changes in a way older peers can't read.+const SCHEMA_VERSION = 1;++export const COMMENT_STATUSES = Object.freeze(['open', 'accepted', 'dismissed']);+const STATUS_SET = new Set(COMMENT_STATUSES);++const REVIEW_FILE = 'manuscript-review.json';+const reviewPath = (seriesId) => join(seriesStore().recordDir(seriesId), REVIEW_FILE);++// Per-series write tail (the review file is distinct per series, so each only+// serializes against itself). One canonical single-tail queue per series id.+const reviewQueues = new Map();+function queueReviewWrite(seriesId, fn) {+ const key = typeof seriesId === 'string' && seriesId ? seriesId : '__unknown__';+ let q = reviewQueues.get(key);+ if (!q) { q = createFileWriteQueue(); reviewQueues.set(key, q); }+ return q(fn);+}++const emptyReview = () => ({ schemaVersion: SCHEMA_VERSION, comments: [] });++const clampStr = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');++function sanitizeFix(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const find = typeof raw.find === 'string' ? raw.find : '';+ const replace = typeof raw.replace === 'string' ? raw.replace : '';+ if (!find && !replace) return null;+ const out = { find, replace };+ if (raw.fuzzy === true) out.fuzzy = true;+ return out;+}++// Shape one stored comment. Tolerant of partial/legacy records so a hand-edited+// or older-peer file round-trips without dropping fields.+function sanitizeComment(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const problem = clampStr(raw.problem, 2000);+ if (!problem) return null;+ return {+ id: typeof raw.id === 'string' && raw.id ? raw.id : `mrc-${randomUUID()}`,+ issueNumber: Number.isInteger(raw.issueNumber) ? raw.issueNumber : null,+ issueId: typeof raw.issueId === 'string' ? raw.issueId : null,+ stageId: typeof raw.stageId === 'string' ? raw.stageId : null,+ severity: ['high', 'medium', 'low'].includes(raw.severity) ? raw.severity : 'medium',+ category: clampStr(raw.category, 40) || 'other',+ location: clampStr(raw.location, 200),+ problem,+ suggestion: clampStr(raw.suggestion, 2000),+ anchorQuote: clampStr(raw.anchorQuote, 400),+ status: STATUS_SET.has(raw.status) ? raw.status : 'open',+ fix: sanitizeFix(raw.fix),+ sourceRunId: typeof raw.sourceRunId === 'string' ? raw.sourceRunId : null,+ createdAt: typeof raw.createdAt === 'string' ? raw.createdAt : new Date().toISOString(),+ updatedAt: typeof raw.updatedAt === 'string' ? raw.updatedAt : new Date().toISOString(),+ };+}++function sanitizeReview(raw) {+ if (!raw || typeof raw !== 'object' || !Array.isArray(raw.comments)) return emptyReview();+ return {+ schemaVersion: SCHEMA_VERSION,+ comments: raw.comments.map(sanitizeComment).filter(Boolean),+ };+}++async function readReview(seriesId) {+ // `null` = file absent (distinct from a present-but-empty review).+ const raw = await readJSONFile(reviewPath(seriesId), null);+ return raw == null ? emptyReview() : sanitizeReview(raw);+}++async function writeReview(seriesId, review) {+ await atomicWrite(reviewPath(seriesId), sanitizeReview(review));+}++/**+ * Read the persisted review for a series. Returns an empty review (never null)+ * when none has been generated yet.+ */+export async function getReview(seriesId) {+ return readReview(seriesId);+}++// Stable identity for a finding so re-running completeness doesn't duplicate a+// still-open comment the user hasn't acted on yet.+const findingKey = (c) => `${c.issueNumber ?? ''}|${c.anchorQuote}|${c.problem}`;++/**+ * Merge a fresh set of shaped completeness findings into the review. ALL+ * existing comments are preserved — open ones (the user may be mid-fix, with a+ * generated replacement attached) as well as accepted/dismissed decisions. Only+ * findings not already present (by (issueNumber, anchorQuote, problem)) are+ * appended, so re-running "Finish the draft" augments the list instead of+ * piling up duplicates or wiping work in progress. New findings resolve their+ * issueId/stageId from the current manuscript sections by issueNumber.+ */+export async function seedReviewFromFindings(seriesId, findings, { runId = null } = {}) {+ const sections = await collectManuscriptSections(seriesId);+ const byNumber = new Map(sections.map((s) => [s.number, s]));+ return queueReviewWrite(seriesId, async () => {+ const review = await readReview(seriesId);+ const seenKeys = new Set(review.comments.map(findingKey));+ const now = new Date().toISOString();++ const fresh = [];+ for (const f of Array.isArray(findings) ? findings : []) {+ const candidate = sanitizeComment({ ...f, status: 'open', sourceRunId: runId, createdAt: now, updatedAt: now });+ if (!candidate) continue;+ const key = findingKey(candidate);+ if (seenKeys.has(key)) continue; // already present (open or resolved) — don't duplicate+ const section = candidate.issueNumber != null ? byNumber.get(candidate.issueNumber) : null;+ if (section) {+ candidate.issueId = section.issueId;+ candidate.stageId = section.stageId;+ }+ seenKeys.add(key);+ fresh.push(candidate);+ }++ const next = { schemaVersion: SCHEMA_VERSION, comments: [...review.comments, ...fresh] };+ await writeReview(seriesId, next);+ return next;+ });+}++/**+ * Patch a single comment (status flip, attach/clear a generated fix, edit the+ * replacement text). Last-write-wins on `updatedAt`. Returns the updated+ * comment, or throws if the id is unknown.+ */+export async function updateComment(seriesId, commentId, patch) {+ return queueReviewWrite(seriesId, async () => {+ const review = await readReview(seriesId);+ const idx = review.comments.findIndex((c) => c.id === commentId);+ if (idx === -1) {+ throw Object.assign(new Error(`Comment not found: ${commentId}`), { code: 'PIPELINE_REVIEW_NOT_FOUND' });+ }+ const cur = review.comments[idx];+ const merged = { ...cur };+ if (patch.status !== undefined && STATUS_SET.has(patch.status)) merged.status = patch.status;+ // `fix: null` is an explicit clear; absent leaves it untouched.+ if (patch.fix !== undefined) merged.fix = sanitizeFix(patch.fix);+ merged.updatedAt = new Date().toISOString();+ const next = { ...review, comments: review.comments.map((c, i) => (i === idx ? sanitizeComment(merged) : c)) };+ await writeReview(seriesId, next);+ return next.comments[idx];+ });+}++/**+ * Sync-orchestrator entry: merge a remote peer's review into local state,+ * last-write-wins per comment on `updatedAt`. Mirrors `mergeIssuesFromSync`.+ */+export async function mergeReviewFromSync(seriesId, remoteReview) {+ const remote = sanitizeReview(remoteReview);+ return queueReviewWrite(seriesId, async () => {+ const local = await readReview(seriesId);+ const byId = new Map(local.comments.map((c) => [c.id, c]));+ for (const rc of remote.comments) {+ const lc = byId.get(rc.id);+ if (!lc || new Date(rc.updatedAt).getTime() >= new Date(lc.updatedAt).getTime()) {+ byId.set(rc.id, rc);+ }+ }+ const next = { schemaVersion: SCHEMA_VERSION, comments: [...byId.values()] };+ await writeReview(seriesId, next);+ return next;+ });+}++// Internal: used by manuscriptFix to read a single comment without a full+// round-trip ceremony. Returns null when absent.+export async function getComment(seriesId, commentId) {+ const review = await readReview(seriesId);+ return review.comments.find((c) => c.id === commentId) || null;+}diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex db4c194743..2278989d6e 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -80,6 +80,14 @@ export const WRITERS_ROOM_WORK_ID_MAX = 64;export const TARGET_FORMATS = Object.freeze(['comic', 'tv', 'comic+tv']);export const ISSUE_COUNT_TARGET_MAX = 999;+// The manuscript format the series is authored/finalized in first — the source+// of truth the other two formats are generated from. Stored as the stage id so+// it maps straight onto the issue stages. `null` = not chosen yet; the+// manuscript editor falls back to auto-detecting the dominant drafted stage.+// Mirrors MANUSCRIPT_STAGES in arcPlanner.js (kept local to avoid an import+// cycle — series.js is imported by arcPlanner.js).+export const MANUSCRIPT_TYPES = Object.freeze(['comicScript', 'teleplay', 'prose']);+export const LOCKABLE_STAGES = Object.freeze(['arc']);// Per-field arc lock targets. Each field can be individually frozen so@@ -151,6 +159,13 @@ const sanitizeSeries = (raw) => {? raw.stylePromptOverrideMode: STYLE_PROMPT_OVERRIDE_MODE_DEFAULT,targetFormat,+ // The format this series is finalized in first (source of truth for the+ // other two). `null` until the author picks one in the bible. Validated+ // against the stage-id list so a stale/hand-edited value can't smuggle in+ // a non-manuscript stage.+ primaryManuscriptType: MANUSCRIPT_TYPES.includes(raw.primaryManuscriptType)+ ? raw.primaryManuscriptType+ : null,issueCountTarget,llm,// Share-bucket provenance — present on imported records, absent on locally-authored ones.@@ -309,6 +324,7 @@ export async function updateSeries(id, patch = {}) {...('stylePromptOverride' in patch ? { stylePromptOverride: patch.stylePromptOverride } : {}),...('stylePromptOverrideMode' in patch ? { stylePromptOverrideMode: patch.stylePromptOverrideMode } : {}),...('targetFormat' in patch ? { targetFormat: patch.targetFormat } : {}),+ ...('primaryManuscriptType' in patch ? { primaryManuscriptType: patch.primaryManuscriptType } : {}),...('issueCountTarget' in patch ? { issueCountTarget: patch.issueCountTarget } : {}),...('origin' in patch ? { origin: patch.origin } : {}),// Local-only "don't sync" marker — sanitizer normalizes anything