Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

add 'generate edits for every finding' option to manuscript editorial review

[._.]/ Adam Eivye3ac77771586
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index e52fcb4199..b57800da27 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **Editorial review can draft every fix in one pass** — the manuscript editor's **Run editorial review** now has a second checkbox, **Generate edits for every finding**, next to *Start fresh*. With it on, the completeness pass returns not just the itemized editorial notes but a concrete rewrite (`replace`) for each one, so every comment lands with its fix already attached — you go straight to reviewing the full diff and accepting edits one-by-one, with no per-note **Generate fix** click. The model returns each finding's edit inline (a single LLM pass, no N+1 round-trips), and the run streams per-chunk progress over SSE (`Drafting edits — chunk 2 of 4…`) with a Cancel button, re-attaching if you reload mid-run. Findings whose anchor can't be located verbatim stay advice-only and fall back to manual fix generation, so nothing presents an unappliable diff. Leaving the box off keeps today's findings-only behavior unchanged. The new `replace` field rides in a `{{#withEdits}}` block of the completeness prompt (migration 083; the prior prompt auto-upgrades on existing installs). (`server/services/pipeline/arcPlanner.js`, `manuscriptReview.js`, `manuscriptCompletenessRunner.js`, `client/src/pages/PipelineManuscriptEditor.jsx`)
+
- **Animated 3D mini-character CoS avatars (bundled, CC0)** — two new Chief-of-Staff avatar styles, **Mini Character — Male (3D)** and **Mini Character — Female (3D)**, ship as rigged, animated GLB models out of the box (no user setup, no download). Unlike the `muse` style (which needs you to drop your own `data/avatar/model.glb`), these render immediately and play real skeletal animations mapped to the CoS agent state — `idle` while thinking, `walk` while coding, `sit` while sleeping, `sprint` while ideating, `emote-yes` while reviewing — plus a slow turntable rotation and a speaking head-bob, with clips crossfading on state change. The models are Kenney's [Mini Characters](https://kenney.nl/assets/mini-characters) (Creative Commons Zero), re-exported with the texture embedded and Draco compression disabled so they render offline / over Tailscale without fetching an external decoder from a CDN. Each is ~210 KB and ships in `data.reference/avatar/` (seeded into `data/avatar/` by `npm run setup:data`). The avatar route gained a safe `?variant=<name>` selector (strict `[a-z0-9-]` validation, no path traversal) so multiple bundled characters share one endpoint. Drop any rigged GLB at `data/avatar/<name>.glb` to add your own.
- **[issue-1092] Vocal takes remember their pitch analysis** — when you record a take against a song's notated melody, the take now keeps its color-match grading (percent-in-tune and per-note accuracy) and the tuner trace. Each saved take shows its score in the takes list, and a Review button replays that grading on the staff without re-singing.
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 0e732262be..f1af615a5e 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -45,6 +45,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useOpenClawStream` | OpenClaw SSE chat stream. | OpenClaw file-browser chat surface only. |
| `usePipelineAutoRunProgress` | Auto-run-text SSE for a pipeline issue. | Pipeline auto-run UI surfaces only. |
| `usePipelineEditorialProgress` | Series editorial reader-emotion batch SSE. | Editorial Roadmap analysis UI only. |
+| `usePipelineManuscriptCompletenessProgress` | Streamed manuscript-completeness review (generate-edits pass) per-chunk SSE. | Manuscript editor review trigger only. |
| `usePipelineVolumeBeatsProgress` | Volume beat-sheet SSE. | Volume beat-sheet UI only. |
| `useSeriesEditorial` | Editorial-roadmap aggregate + batch lifecycle (load, re-attach, SSE, start/cancel, reload). | Any view of the editorial roadmap (panel or Reader Map page). |
| `useStoryStepProgress` | Generate/refine SSE for one Story Builder step. | Story Builder step generate/refine progress only. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 4cde9e42af..46ac81f99f 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -60,6 +60,7 @@ export * from './useInstallStream.js';
export * from './useOpenClawStream.js';
export * from './usePipelineAutoRunProgress.js';
export * from './usePipelineEditorialProgress.js';
+export * from './usePipelineManuscriptCompletenessProgress.js';
export * from './usePipelineVolumeBeatsProgress.js';
export * from './useSeriesEditorial.js';
export * from './useSseProgress.js';
diff --git a/client/src/hooks/usePipelineManuscriptCompletenessProgress.js b/client/src/hooks/usePipelineManuscriptCompletenessProgress.js
new file mode 100644
index 0000000000..199d08f056
--- /dev/null
+++ b/client/src/hooks/usePipelineManuscriptCompletenessProgress.js
@@ -0,0 +1,13 @@
+import { pipelineManuscriptCompletenessSseUrl } from '../services/api';
+import { useSseProgress } from './useSseProgress';
+
+/**
+ * Subscribe to the streamed manuscript-completeness review SSE stream (the
+ * "generate edits for every finding" pass). Frame shapes are documented in
+ * server/services/pipeline/manuscriptCompletenessRunner.js
+ * (start / plan / chunk:start / chunk:complete / complete / canceled / error).
+ */
+export function usePipelineManuscriptCompletenessProgress(seriesId, { enabled = true } = {}) {
+ const url = seriesId ? pipelineManuscriptCompletenessSseUrl(seriesId) : null;
+ return useSseProgress(url, { enabled });
+}
diff --git a/client/src/pages/PipelineManuscriptEditor.jsx b/client/src/pages/PipelineManuscriptEditor.jsx
index 65f6a29db5..5652bd7bac 100644
--- a/client/src/pages/PipelineManuscriptEditor.jsx
+++ b/client/src/pages/PipelineManuscriptEditor.jsx
@@ -25,10 +25,11 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { Link, useParams, useNavigate } from 'react-router-dom';
import {
- ArrowLeft, Loader2, Sparkles, FileText, Star, ClipboardCheck, Layers, PencilLine, BookOpen, GitCompare,
+ ArrowLeft, Loader2, Sparkles, FileText, Star, ClipboardCheck, Layers, PencilLine, BookOpen, GitCompare, X,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import { useAsyncAction } from '../hooks/useAsyncAction';
+import { usePipelineManuscriptCompletenessProgress } from '../hooks/usePipelineManuscriptCompletenessProgress';
import { filterGenerationModels, mergeModelLists, localBackendForProvider, modelOptionLabel } from '../utils/providers';
import useLocalModels from '../hooks/useLocalModels';
import { locateAnchors } from '../lib/manuscriptAnchors';
@@ -41,7 +42,8 @@ import { MANUSCRIPT_TYPES, STAGE_LABEL } from '../components/pipeline/manuscript
import {
getPipelineSeries, updatePipelineSeries, getPipelineManuscript, getPipelineManuscriptReview,
savePipelineManuscriptSection, restorePipelineStageVersion,
- analyzePipelineManuscriptCompleteness, getProviders,
+ analyzePipelineManuscriptCompleteness, startPipelineManuscriptCompleteness,
+ cancelPipelineManuscriptCompleteness, getPipelineManuscriptCompletenessStatus, getProviders,
} from '../services/api';
// Stable empty array so sections that gain no comments/spans don't get a fresh
@@ -73,6 +75,14 @@ export default function PipelineManuscriptEditor() {
const [comments, setComments] = useState([]);
const [reviewMeta, setReviewMeta] = useState(null);
const [freshReview, setFreshReview] = useState(false);
+ // "Generate edits for every finding" — pre-builds each comment's fix during the
+ // review so the diff + Accept show with no per-comment "Generate fix" call.
+ // Runs through the streamed runner (per-chunk SSE progress) rather than the
+ // synchronous findings-only path.
+ const [generateEdits, setGenerateEdits] = useState(false);
+ // SSE-gated streaming state for the generate-edits run.
+ const [reviewActive, setReviewActive] = useState(false);
+ const [reviewStarting, setReviewStarting] = useState(false);
const [loading, setLoading] = useState(true);
const [switching, setSwitching] = useState(false);
const [pinning, setPinning] = useState(false);
@@ -193,6 +203,89 @@ export default function PipelineManuscriptEditor() {
{ errorMessage: 'Failed to run editorial review' },
);
+ // Streamed generate-edits review — `reviewActive` gates the SSE subscription;
+ // the latest frame drives the per-chunk button label. The terminal frame
+ // re-fetches the review (comments now carry pre-built fixes).
+ const { latest: reviewLatest } = usePipelineManuscriptCompletenessProgress(seriesId, { enabled: reviewActive });
+
+ // On mount, re-attach to an in-flight streamed run (e.g. after a reload mid-run).
+ useEffect(() => {
+ let canceled = false;
+ getPipelineManuscriptCompletenessStatus(seriesId, { silent: true })
+ .then((s) => { if (!canceled && s?.active) setReviewActive(true); })
+ .catch(() => {});
+ return () => { canceled = true; };
+ }, [seriesId]);
+
+ // Terminal-frame handler for the streamed run: refresh comments + toast, then
+ // tear the subscription down. Per-chunk frames only drive the button label.
+ useEffect(() => {
+ if (!reviewActive || !reviewLatest) return;
+ const type = reviewLatest.type;
+ if (type !== 'complete' && type !== 'canceled' && type !== 'error') return;
+ setReviewActive(false);
+ if (type === 'complete') {
+ getPipelineManuscriptReview(seriesId)
+ .then((review) => {
+ const next = Array.isArray(review?.comments) ? review.comments : [];
+ setComments(next);
+ setReviewMeta({ chunked: !!reviewLatest.chunked, chunkCount: reviewLatest.chunkCount || 1 });
+ const openCount = next.filter((c) => c.status === 'open').length;
+ toast.success(reviewLatest.chunked
+ ? `Editorial review complete — ${openCount} open notes with drafted edits (reviewed in ${reviewLatest.chunkCount} chunks)`
+ : `Editorial review complete — ${openCount} open notes with drafted edits`);
+ })
+ .catch((err) => toast.error(err.message || 'Failed to load review'));
+ } else if (type === 'canceled') {
+ toast.success('Editorial review canceled');
+ } else {
+ toast.error(reviewLatest.error || 'Editorial review failed');
+ }
+ }, [reviewActive, reviewLatest, seriesId]);
+
+ const startGenerateEditsReview = async (mode) => {
+ setReviewStarting(true);
+ const result = await startPipelineManuscriptCompleteness(seriesId, {
+ providerOverride, modelOverride, mode,
+ }).catch((err) => {
+ toast.error(err.message || 'Failed to start editorial review');
+ return null;
+ });
+ setReviewStarting(false);
+ if (!result) return;
+ setReviewActive(true);
+ };
+
+ const cancelGenerateEditsReview = async () => {
+ await cancelPipelineManuscriptCompleteness(seriesId).catch((err) => {
+ toast.error(err.message || 'Cancel failed');
+ });
+ };
+
+ // Unified trigger: the streamed generate-edits path when the box is checked,
+ // else today's synchronous findings-only path. Disabled state below covers both.
+ const onRunReview = () => {
+ const mode = freshReview ? 'fresh' : 'merge';
+ if (generateEdits) return startGenerateEditsReview(mode);
+ return runEditorialReview(mode);
+ };
+
+ const busy = reviewing || reviewActive || reviewStarting;
+
+ // The full review-button label: per-chunk progress for the streamed
+ // generate-edits run, the sync-pass spinner text, or the idle prompt.
+ const reviewButtonLabel = useMemo(() => {
+ if (reviewActive) {
+ const f = reviewLatest;
+ if (!f || f.type === 'start') return 'Starting editorial review…';
+ // Chunk number: chunk:start hasn't finished `done` yet, so show done+1.
+ const n = Math.min((f.done || 0) + (f.type === 'chunk:start' ? 1 : 0), f.total || 1);
+ if (f.total > 1) return `Drafting edits — chunk ${n} of ${f.total}…`;
+ return 'Drafting edits…';
+ }
+ return reviewing ? 'Running editorial review…' : 'Run editorial review';
+ }, [reviewActive, reviewLatest, reviewing]);
+
const changeView = async (type) => {
if (type === viewType || switching) return;
setSwitching(true);
@@ -532,23 +625,32 @@ export default function PipelineManuscriptEditor() {
) : null}
<button
type="button"
- onClick={() => runEditorialReview(freshReview ? 'fresh' : 'merge')}
- disabled={reviewing || sections.length === 0}
+ onClick={onRunReview}
+ disabled={busy || sections.length === 0}
title={sections.length === 0
? 'Draft at least one issue before running an editorial review'
: 'Re-run the editorial feedback pass over the manuscript with the selected provider'}
className="w-full inline-flex items-center justify-center gap-1.5 px-2.5 py-1.5 rounded text-[12px] font-medium border bg-port-bg text-port-accent border-port-border hover:border-port-accent/40 disabled:opacity-40"
>
- {reviewing ? <Loader2 size={12} className="animate-spin" /> : <ClipboardCheck size={12} />}
- {reviewing ? 'Running editorial review…' : 'Run editorial review'}
+ {busy ? <Loader2 size={12} className="animate-spin" /> : <ClipboardCheck size={12} />}
+ {reviewButtonLabel}
</button>
+ {reviewActive ? (
+ <button
+ type="button"
+ onClick={cancelGenerateEditsReview}
+ className="w-full inline-flex items-center justify-center gap-1.5 px-2.5 py-1 rounded text-[11px] font-medium border bg-port-bg text-gray-400 border-port-border hover:text-white hover:border-port-error/40"
+ >
+ <X size={11} /> Cancel
+ </button>
+ ) : null}
<label htmlFor="ms-fresh-review" className="flex items-start gap-1.5 text-[11px] text-gray-400 cursor-pointer">
<input
id="ms-fresh-review"
type="checkbox"
checked={freshReview}
onChange={(e) => setFreshReview(e.target.checked)}
- disabled={reviewing}
+ disabled={busy}
className="mt-0.5 accent-port-accent"
/>
<span>
@@ -559,6 +661,23 @@ export default function PipelineManuscriptEditor() {
</span>
</span>
</label>
+ <label htmlFor="ms-generate-edits" className="flex items-start gap-1.5 text-[11px] text-gray-400 cursor-pointer">
+ <input
+ id="ms-generate-edits"
+ type="checkbox"
+ checked={generateEdits}
+ onChange={(e) => setGenerateEdits(e.target.checked)}
+ disabled={busy}
+ className="mt-0.5 accent-port-accent"
+ />
+ <span>
+ Generate edits for every finding
+ <span className="text-gray-600">
+ {' '}— pre-build a fix per note so you can review the full diff &amp;
+ accept edits one-by-one without a separate “Generate fix” step.
+ </span>
+ </span>
+ </label>
</div>
{reviewMeta?.chunked ? (
diff --git a/client/src/pages/PipelineManuscriptEditor.test.jsx b/client/src/pages/PipelineManuscriptEditor.test.jsx
index 748252f61f..68ab806f5d 100644
--- a/client/src/pages/PipelineManuscriptEditor.test.jsx
+++ b/client/src/pages/PipelineManuscriptEditor.test.jsx
@@ -13,6 +13,10 @@ const api = vi.hoisted(() => ({
generatePipelineManuscriptFix: vi.fn(),
acceptPipelineManuscriptFix: vi.fn(),
analyzePipelineManuscriptCompleteness: vi.fn(),
+ startPipelineManuscriptCompleteness: vi.fn(),
+ cancelPipelineManuscriptCompleteness: vi.fn(),
+ getPipelineManuscriptCompletenessStatus: vi.fn(),
+ pipelineManuscriptCompletenessSseUrl: vi.fn((id) => `/api/pipeline/series/${id}/manuscript/completeness/progress`),
getProviders: vi.fn(),
}));
vi.mock('../services/api', () => api);
@@ -51,6 +55,7 @@ beforeEach(() => {
availableTypes: ['prose'],
});
api.getPipelineManuscriptReview.mockResolvedValue({ schemaVersion: 1, comments: [comment] });
+ api.getPipelineManuscriptCompletenessStatus.mockResolvedValue({ active: false });
api.getProviders.mockResolvedValue({ providers: [
{ id: 'anthropic', name: 'Anthropic', enabled: true, defaultModel: 'claude-opus', models: ['claude-opus', 'claude-haiku'] },
{ id: 'openai', name: 'OpenAI', enabled: true, defaultModel: 'gpt-5', models: ['gpt-5'] },
@@ -349,3 +354,80 @@ describe('PipelineManuscriptEditor', () => {
expect(screen.queryByText(/Reviewed in/)).not.toBeInTheDocument();
});
});
+
+// jsdom has no EventSource — stand up a minimal mock the test drives by hand.
+class MockEventSource {
+ constructor(url) {
+ this.url = url;
+ this.onmessage = null;
+ this.onerror = null;
+ this.onopen = null;
+ this.readyState = MockEventSource.OPEN;
+ MockEventSource.instances.push(this);
+ }
+ close() { this.readyState = MockEventSource.CLOSED; }
+ emit(payload) { this.onmessage?.({ data: JSON.stringify(payload) }); }
+}
+MockEventSource.CONNECTING = 0;
+MockEventSource.OPEN = 1;
+MockEventSource.CLOSED = 2;
+const lastEs = () => MockEventSource.instances[MockEventSource.instances.length - 1];
+
+describe('PipelineManuscriptEditor — generate-edits streamed review', () => {
+ beforeEach(() => {
+ MockEventSource.instances = [];
+ // Stub for the whole describe — a deferred SSE-open effect can fire after the
+ // test body returns (during RTL cleanup), so don't delete it per-test or that
+ // late `new EventSource(url)` throws a ReferenceError.
+ vi.stubGlobal('EventSource', MockEventSource);
+ });
+ afterEach(() => { vi.unstubAllGlobals(); });
+
+ it('checkbox-on runs the streamed edits endpoint (not the sync findings-only path)', async () => {
+ api.startPipelineManuscriptCompleteness.mockResolvedValue({ runId: 'cr-1', sseUrl: '/sse' });
+ renderEditor();
+ await screen.findByText('My Series');
+
+ fireEvent.click(screen.getByLabelText(/Generate edits for every finding/i));
+ fireEvent.click(screen.getByText('Run editorial review'));
+
+ await waitFor(() => expect(api.startPipelineManuscriptCompleteness).toHaveBeenCalledWith(
+ 'ser-1', expect.objectContaining({ mode: 'merge' }),
+ ));
+ expect(api.analyzePipelineManuscriptCompleteness).not.toHaveBeenCalled();
+ // Let the deferred SSE-open effect flush + close inside the test (while the
+ // EventSource stub is live) so it can't throw during teardown.
+ await waitFor(() => expect(MockEventSource.instances.length).toBeGreaterThan(0));
+ lastEs().emit({ type: 'canceled' });
+ });
+
+ it('on the complete frame, re-fetches the review so comments arrive with fixes (diff + Accept, no Generate fix)', async () => {
+ const withFix = {
+ ...comment,
+ fix: { find: 'She left.', replace: 'She left, but paused.', edits: [{ issueNumber: 1, issueId: 'iss-1', stageId: 'prose', find: 'She left.', replace: 'She left, but paused.' }] },
+ };
+ api.startPipelineManuscriptCompleteness.mockResolvedValue({ runId: 'cr-1', sseUrl: '/sse' });
+ // First load returns the fix-less comment; the post-complete re-fetch returns
+ // the comment with its pre-built fix.
+ api.getPipelineManuscriptReview
+ .mockResolvedValueOnce({ schemaVersion: 1, comments: [comment] })
+ .mockResolvedValueOnce({ schemaVersion: 1, comments: [withFix] });
+
+ renderEditor();
+ await screen.findByText('My Series');
+
+ fireEvent.click(screen.getByLabelText(/Generate edits for every finding/i));
+ fireEvent.click(screen.getByText('Run editorial review'));
+ await waitFor(() => expect(MockEventSource.instances.length).toBeGreaterThan(0));
+
+ // Drive the terminal frame; the editor re-fetches the review.
+ lastEs().emit({ type: 'complete', openCount: 1, chunked: false, chunkCount: 1 });
+ await waitFor(() => expect(api.getPipelineManuscriptReview).toHaveBeenCalledTimes(2));
+
+ // The comment now carries a fix → the in-context card shows Accept, not "Generate fix".
+ revealFromIndex('The ending is abrupt');
+ expect(await screen.findByDisplayValue('She left, but paused.')).toBeInTheDocument();
+ expect(screen.getByText('Accept')).toBeInTheDocument();
+ expect(screen.queryByText('Generate fix')).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index 8ec87c54ce..a042a9576e 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -421,6 +421,29 @@ export const analyzePipelineManuscriptCompleteness = (seriesId, { providerOverri
body: JSON.stringify({ providerOverride, modelOverride, mode }),
});
+// Streamed completeness review backing the "generate edits for every finding"
+// option: this pass always returns a concrete `replace` per finding so each
+// seeded comment lands with its `fix` pre-attached. Returns { runId,
+// alreadyRunning, sseUrl } — subscribe via pipelineManuscriptCompletenessSseUrl
+// to stream per-chunk progress, then re-fetch the review on `complete`.
+export const startPipelineManuscriptCompleteness = (seriesId, { providerOverride, modelOverride, mode } = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/manuscript/completeness/stream`, {
+ method: 'POST',
+ body: JSON.stringify({ providerOverride, modelOverride, mode }),
+ });
+
+export const cancelPipelineManuscriptCompleteness = (seriesId) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/manuscript/completeness/cancel`, {
+ method: 'POST',
+ });
+
+// { active: boolean } — lets a (re)mounting editor re-attach to an in-flight run.
+export const getPipelineManuscriptCompletenessStatus = (seriesId, options = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/manuscript/completeness/status`, options);
+
+export const pipelineManuscriptCompletenessSseUrl = (seriesId) =>
+ `/api/pipeline/series/${encodeURIComponent(seriesId)}/manuscript/completeness/progress`;
+
// ---- Manuscript editor ----
// Full series manuscript in one format. `type` (comicScript|teleplay|prose)
// selects the format; omit to get the series' primary/source format. Returns
diff --git a/data.reference/prompts/stages/pipeline-manuscript-completeness.md b/data.reference/prompts/stages/pipeline-manuscript-completeness.md
index 3827e6af2a..87176e9339 100644
--- a/data.reference/prompts/stages/pipeline-manuscript-completeness.md
+++ b/data.reference/prompts/stages/pipeline-manuscript-completeness.md
@@ -86,7 +86,8 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c
"location": "Issue 2, around the castle-escape page",
"problem": "string (what is missing or under-developed, with specific evidence from the script)",
"replacementStrategy": "delta",
- "suggestion": "string (the smallest concrete addition — a beat, a page, a scene, a line of motivation — that closes the gap)"
+ "suggestion": "string (the smallest concrete addition — a beat, a page, a scene, a line of motivation — that closes the gap)"{{#withEdits}},
+ "replace": "the rewritten passage that REPLACES anchorQuote verbatim to close this gap (see the rule below)"{{/withEdits}}
}
]
}
@@ -103,5 +104,8 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c
- **`medium`** — the story works but feels incomplete or thin here (an under-built relationship, a skipped transition).
- **`low`** — an opportunity to enrich (a theme that could land harder, a minor character that could carry more).
- **For `comic-structure` findings:** `severity` is always `high` and `replacementStrategy` is always `full-page`. The `suggestion` must be the **complete restructured page content** — a full `Panel 1 / Description: … / Caption: … / Dialogue: … / SFX: …` breakdown for every panel the page should have, not prose advice — because the fix step substitutes it directly for the malformed page rather than synthesizing an edit. Distribute the prose content from the page description into appropriately sequenced panels (4–6 panels typical for a story page; use your judgment for pacing). Set `anchorQuote` to the opening text of the malformed page description block so the editor can locate it precisely.
+{{#withEdits}}
+- **`replace` (required this pass):** in addition to the advice in `suggestion`, return the concrete edit that closes the gap. `replace` is the new text that **substitutes for `anchorQuote` exactly** — the editor splices it in over the span `anchorQuote` marks, so `anchorQuote` must be a real verbatim excerpt (not empty) and `replace` must be that same span rewritten to incorporate the fix. To ADD a missing beat, set `replace` to `anchorQuote` followed by the new material (so nothing is deleted); to REWRITE, set `replace` to the corrected version of that span. For `comic-structure` (`full-page`), `replace` is the complete panel-by-panel page (same content as `suggestion`). Keep `replace` tightly scoped to the anchored span — do not restate the whole issue. Omit `replace` (or set it to `""`) only when the gap genuinely has no in-place edit (e.g. a whole missing issue with no nearby text to anchor to); that finding then stays advice-only.
+{{/withEdits}}
Return `{ "issues": [] }` only if the manuscript is genuinely complete. Do NOT pad with low-confidence entries.
diff --git a/docs/plans/2026-06-10-manuscript-review-generate-edits.md b/docs/plans/2026-06-10-manuscript-review-generate-edits.md
new file mode 100644
index 0000000000..952edb65b0
--- /dev/null
+++ b/docs/plans/2026-06-10-manuscript-review-generate-edits.md
@@ -0,0 +1,152 @@
+# Manuscript Editorial Review — "Generate edits for every finding"
+
+## Context
+
+On the manuscript editor (`/pipeline/series/:id/manuscript`), **"Run editorial review"** runs the
+manuscript-completeness pass (`POST /pipeline/series/:id/manuscript/completeness` →
+`arcPlanner.analyzeManuscriptCompleteness` → `manuscriptReview.seedReviewFromFindings`). It produces
+itemized editorial comments only — each comment lands with `fix: null`, so the user must click
+**"Generate fix"** on every comment individually (one extra LLM call each) before they can review the
+diff and **Accept**.
+
+The user wants a second option on the review trigger: produce the editorial findings **and** a full
+proposed manuscript edit in the same pass — a `find`/`replace` per finding — so every comment arrives
+with its `fix` already attached. The existing per-comment diff viewer (`ManuscriptCommentCard` +
+`SideBySideDiff`/`InlineDiff`), the **Impact preview** modal, and the **Accept** path already render
+and apply `comment.fix` — so once fixes are pre-attached, **the entire review/accept-one-by-one UX
+already works** with no changes. This eliminates the N manual "Generate fix" round-trips.
+
+**Decisions (confirmed):**
+- **Single-pass prompt** — the completeness LLM call returns each finding's `replace` inline; attach
+ `fix = { find: anchorQuote, replace }` via the existing `locateFindSpan` anchoring. No N+1 fix loop.
+- **Checkbox** — add a second checkbox beside "Start fresh": *"Generate edits for every finding."*
+- **SSE progress** — stream per-chunk progress (mirrors `editorialAnalysisRunner`), since a chunked
+ large manuscript otherwise shows a long opaque spinner.
+
+## Approach
+
+### 1. Prompt: conditional `replace` field (single source, migrated)
+
+`data.reference/prompts/stages/pipeline-manuscript-completeness.md` — wrap an additive instruction +
+output-contract field in a Mustache section so it only appears when the editor asks for edits:
+
+```mustache
+{{#withEdits}}
+- `replace` — the rewritten text that **replaces `anchorQuote` verbatim** to close this gap. Copy
+ `anchorQuote` into `find`-equivalent position and supply the smallest concrete rewrite of that
+ exact span. For `comic-structure` (full-page), `replace` is the complete panel-by-panel page.
+ Omit `replace` only when no in-place edit is possible.
+{{/withEdits}}
+```
+Add `"replace": "..."` to the JSON example inside the same `{{#withEdits}}` block. `anchorQuote`
+already serves as the fix's `find`; `replace` is the new span. Keep the findings-only contract intact
+(the section is absent when `withEdits` is false → identical prompt for the legacy path).
+
+**Migration `scripts/migrations/083-completeness-with-edits-prompt.js`** (latest is 082):
+- Use `makePromptReplaceMigration` from `./_lib.js` (copy the shape of
+ `066-manuscript-finding-replacement-strategy-prompts.js`).
+- `ACCEPTED_OLD_MD5['pipeline-manuscript-completeness.md']` = current shipped hash (from 066's
+ `NEW_SHIPPED_MD5`, `cec8faeb75dfff74e41b8221145c2e92`).
+- `NEW_SHIPPED_MD5` = the post-edit hash (compute after editing the `.md`).
+- **Mirror the new hash into every earlier migration that tracks this file** (056, 057, 066) per the
+ prompt-migration-drift cross-sync rule — update their `NEW_SHIPPED_MD5` and the `setup-data.js`
+ drift table — or their drift-catch tests go red. Add a sibling `.test.js` like 066's.
+
+### 2. Server: thread `withEdits` through analyze → shape → seed
+
+**`server/services/pipeline/arcPlanner.js`** (`analyzeManuscriptCompleteness`, ~line 789):
+- Accept `options.withEdits`. Pass `withEdits: !!options.withEdits` into the template ctx (alongside
+ `manuscript`) in `runOne`.
+- `shapeCompletenessFindings` (~line 698): when `withEdits`, also read `raw.replace` (string, trimmed,
+ same `STAGE_OUTPUT_MAX`-ish cap as fix `replace`) onto each shaped finding. Absent/empty → no fix.
+- Bump `COMPLETENESS_OUTPUT_RESERVE_TOKENS` when `withEdits` (each finding now also carries a full
+ `replace`) — reserve more output room so a long edit list isn't truncated. Reuse `manuscriptFix`'s
+ `FIX_OUTPUT_RESERVE_TOKENS` sizing as a reference.
+
+**`server/services/pipeline/manuscriptReview.js`** (`seedReviewFromFindings`, ~line 174):
+- Build each candidate's `fix` from the finding's `anchorQuote` + `replace`: reuse
+ `manuscriptFix.locateFindSpan(section.content, anchorQuote)` (export already public) to confirm the
+ anchor resolves; set `fix = { find: anchorQuote, replace, fuzzy: <not-located-verbatim> }`, with
+ `edits: [{ issueNumber, issueId, stageId, find, replace }]` so the existing **Accept** path
+ (`acceptManuscriptFix`) and **Impact preview** consume it unchanged.
+- `sanitizeComment`/`sanitizeFix` already persist `fix` — just pass it in the candidate object.
+- When a finding has no usable `replace` (or anchor doesn't resolve), leave `fix: null` so the comment
+ falls back to manual "Generate fix" — no regression.
+- `findingKey` dedupe is unchanged (keyed on issueNumber/anchor/problem).
+
+> **Reuse note:** the fix-building logic (anchor → `{find, replace, edits}`, fuzzy flag) overlaps with
+> `manuscriptFix.normalizeFix`. Factor the per-finding `{anchorQuote, replace, section} → fix` shaping
+> into a small exported helper in `manuscriptFix.js` and call it from both seed and fix paths rather
+> than duplicating the `locateFindSpan`/`fuzzy` logic.
+
+### 3. Server: streaming runner + routes (mirror editorial analysis)
+
+**`server/services/pipeline/manuscriptCompletenessRunner.js`** (new — model on
+`editorialAnalysisRunner.js`): in-memory `runs` Map keyed by seriesId; `startCompletenessReview`,
+`attachClient`, `isActive`, `cancel`. The coordinator calls the same chunk loop but emits SSE frames
+per chunk, then seeds the review and emits a terminal frame:
+- `{ type:'start', runId, total }` (total = chunk count; 1 in whole mode)
+- `{ type:'chunk:start'|'chunk:complete', done, total }`
+- `{ type:'complete', runId, openCount, chunked, chunkCount }` / `{ type:'error', ... }` / `canceled`
+- Refactor: extract the chunk-iteration core of `analyzeManuscriptCompleteness` into an async
+ generator or callback-accepting form so both the sync endpoint and the runner share it (avoid
+ copy-pasting the chunk/merge/digest logic).
+
+**`server/routes/pipeline/manuscript.js`**: keep `POST /completeness` synchronous & unchanged for
+findings-only (ArcCanvas + checkbox-off both rely on the sync `{ issues, review }` contract). Add:
+- `POST /series/:id/manuscript/completeness/stream` → `startCompletenessReview` → `{ runId, sseUrl, mode:'fresh'|'merge', withEdits:true }`
+- `GET /series/:id/manuscript/completeness/progress` (SSE attach)
+- `GET /series/:id/manuscript/completeness/status` → `{ active }`
+- `POST /series/:id/manuscript/completeness/cancel`
+- Extend `manuscriptCompletenessSchema` with `withEdits: z.boolean().optional()` (and validate the
+ stream route body the same way).
+
+### 4. Client: checkbox + SSE-driven progress
+
+**`client/src/services/apiPipeline.js`**: add `startPipelineManuscriptCompleteness(seriesId, {providerOverride, modelOverride, mode, withEdits})`,
+`pipelineManuscriptCompletenessSseUrl(seriesId)`, status + cancel wrappers. Re-export from `api.js`
+and add README rows (catalog maintenance rule).
+
+**`client/src/hooks/usePipelineManuscriptCompletenessProgress.js`** (new): thin wrapper over
+`useSseProgress` like `usePipelineEditorialProgress.js`. Register in `hooks/index.js` + README.
+
+**`client/src/pages/PipelineManuscriptEditor.jsx`**:
+- Add `generateEdits` state + a second checkbox under "Start fresh" (id `ms-generate-edits`,
+ `htmlFor` paired). Label: *"Generate edits for every finding — pre-build a fix per note so you can
+ review the full diff & accept."*
+- When `generateEdits` is **off**: keep today's synchronous `runEditorialReview` path verbatim.
+- When **on**: call the stream endpoint, subscribe via the new hook, render per-chunk progress on the
+ button (`Drafting edit chunk 2 of 4…`) and a small list (reuse the `reviewMeta?.chunked` warning
+ area). On the terminal `complete` frame, re-fetch the review (`getPipelineManuscriptReview`) →
+ `setComments`, set `reviewMeta`, toast. Add a Cancel affordance while streaming.
+- On mount, probe `…/completeness/status` and re-attach to an in-flight run (mirror editorial).
+
+## Critical files
+
+- `data.reference/prompts/stages/pipeline-manuscript-completeness.md` — `{{#withEdits}}` `replace` block
+- `scripts/migrations/083-completeness-with-edits-prompt.js` (+ `.test.js`); sync hash into 056/057/066 + `scripts/setup-data.js`
+- `server/services/pipeline/arcPlanner.js` — `withEdits` ctx, `replace` shaping, output-reserve bump
+- `server/services/pipeline/manuscriptReview.js` — build/persist `fix` in `seedReviewFromFindings`
+- `server/services/pipeline/manuscriptFix.js` — export shared `{anchorQuote,replace,section}→fix` helper
+- `server/services/pipeline/manuscriptCompletenessRunner.js` (new) — SSE runner
+- `server/routes/pipeline/manuscript.js` — `withEdits` schema + stream/progress/status/cancel routes
+- `client/src/services/apiPipeline.js`, `client/src/hooks/usePipelineManuscriptCompletenessProgress.js` (new),
+ `client/src/pages/PipelineManuscriptEditor.jsx`
+
+## Verification
+
+1. **Unit/migration:** `cd server && npm test` — add coverage that `shapeCompletenessFindings({withEdits})`
+ reads `replace`; that `seedReviewFromFindings` attaches `fix` with correct `find`/`fuzzy`; migration
+ 083 test asserts old→new hash auto-update + drift-table parity (model on `066…test.js`).
+2. **Client:** `cd client && npm test` — extend `PipelineManuscriptEditor.test.jsx`: checkbox-on calls
+ the stream endpoint; a `complete` SSE frame populates comments **with `fix` set**, and the
+ "Generate fix" button is absent (diff + Accept shown directly).
+3. **End-to-end (dev server):** `npm run dev`, open a series with a drafted multi-issue manuscript →
+ `/pipeline/series/:id/manuscript`. Check "Generate edits for every finding" → Run. Confirm per-chunk
+ progress, then each comment shows a diff + **Accept** with no "Generate fix" step; Accept applies the
+ edit and snapshots a revertible version. Confirm **Impact preview** shows the aggregate diff. Re-run
+ with the box **off** → unchanged findings-only behavior. Confirm ArcCanvas "Finish the draft" still
+ works (sync path untouched).
+4. **Compat:** confirm an install whose completeness prompt was customized is left intact + warned
+ (migration is hash-gated), and that a model that omits `replace` yields `fix: null` comments that
+ still support manual "Generate fix".
diff --git a/scripts/migrations/056-manuscript-anchored-findings-prompt.js b/scripts/migrations/056-manuscript-anchored-findings-prompt.js
index ba6e6af14c..901d78956e 100644
--- a/scripts/migrations/056-manuscript-anchored-findings-prompt.js
+++ b/scripts/migrations/056-manuscript-anchored-findings-prompt.js
@@ -22,15 +22,16 @@ import { makePromptReplaceMigration } from './_lib.js';
// body for this file as accepted-old: '1ee5ac…' (the post-057 comic-structure
// shape) so a copy still at either prior version is auto-upgradable to current.
export const ACCEPTED_OLD_MD5 = {
- 'pipeline-manuscript-completeness.md': ['e6858c74ab2cead752d388e3f428406c', '1ee5ac936fbf1d365e0eaea99bcf1e77'],
+ 'pipeline-manuscript-completeness.md': ['e6858c74ab2cead752d388e3f428406c', '1ee5ac936fbf1d365e0eaea99bcf1e77', 'cec8faeb75dfff74e41b8221145c2e92'],
};
-// Current shipped hash — migrations 057 (comic-structure) and 066
-// (replacementStrategy) further updated this file, so this hash reflects the
-// post-066 body. The idempotent-rerun and drift-catch tests require it to match
-// the live data.reference body, not 056's own output.
+// Current shipped hash — migrations 057 (comic-structure), 066
+// (replacementStrategy) and 083 (with-edits replace field) further updated this
+// file, so this hash reflects the post-083 body. The idempotent-rerun and
+// drift-catch tests require it to match the live data.reference body, not 056's
+// own output.
export const NEW_SHIPPED_MD5 = {
- 'pipeline-manuscript-completeness.md': 'cec8faeb75dfff74e41b8221145c2e92',
+ 'pipeline-manuscript-completeness.md': 'fd26f928c33803c12878a1bfb8561ece',
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/057-comic-structure-completeness-prompt.js b/scripts/migrations/057-comic-structure-completeness-prompt.js
index 28c6029f2c..ba002b01e6 100644
--- a/scripts/migrations/057-comic-structure-completeness-prompt.js
+++ b/scripts/migrations/057-comic-structure-completeness-prompt.js
@@ -27,15 +27,15 @@ import { makePromptReplaceMigration } from './_lib.js';
// accepted-old entry — migration 066 (replacementStrategy) further updated the
// file, so a copy still at the 057 body is auto-upgradable to the current shape.
export const ACCEPTED_OLD_MD5 = {
- 'pipeline-manuscript-completeness.md': ['4f2b95778aed85f5fc461d71eb461b79', '1ee5ac936fbf1d365e0eaea99bcf1e77'],
+ 'pipeline-manuscript-completeness.md': ['4f2b95778aed85f5fc461d71eb461b79', '1ee5ac936fbf1d365e0eaea99bcf1e77', 'cec8faeb75dfff74e41b8221145c2e92'],
};
-// Current shipped hash — migration 066 further updated this file (added the
-// replacementStrategy contract), so this hash reflects the post-066 body.
-// The idempotent-rerun and drift-catch tests require it to match the live
-// data.reference body, not 057's own output.
+// Current shipped hash — migrations 066 (replacementStrategy contract) and 083
+// (with-edits replace field) further updated this file, so this hash reflects
+// the post-083 body. The idempotent-rerun and drift-catch tests require it to
+// match the live data.reference body, not 057's own output.
export const NEW_SHIPPED_MD5 = {
- 'pipeline-manuscript-completeness.md': 'cec8faeb75dfff74e41b8221145c2e92',
+ 'pipeline-manuscript-completeness.md': 'fd26f928c33803c12878a1bfb8561ece',
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/066-manuscript-finding-replacement-strategy-prompts.js b/scripts/migrations/066-manuscript-finding-replacement-strategy-prompts.js
index e165c0e118..8840f29bdb 100644
--- a/scripts/migrations/066-manuscript-finding-replacement-strategy-prompts.js
+++ b/scripts/migrations/066-manuscript-finding-replacement-strategy-prompts.js
@@ -28,15 +28,20 @@ import { makePromptReplaceMigration } from './_lib.js';
// Pre-change shipped hashes: completeness from migration 057 (six-category
// comic-structure prompt), fix from migration 060 (multi-edit prompt).
export const ACCEPTED_OLD_MD5 = {
- 'pipeline-manuscript-completeness.md': ['1ee5ac936fbf1d365e0eaea99bcf1e77'],
+ // 'cec8…' is this migration's own (post-066) completeness body, kept as
+ // accepted-old because migration 083 (with-edits replace field) is the current
+ // shape, so a copy still at the post-066 body is auto-upgradable.
+ 'pipeline-manuscript-completeness.md': ['1ee5ac936fbf1d365e0eaea99bcf1e77', 'cec8faeb75dfff74e41b8221145c2e92'],
'pipeline-manuscript-fix.md': ['c88a56304eb5e290ae0de9dadd20b310'],
};
-// Post-change shipped hashes (replacementStrategy contract on both prompts).
-// Mirror these into every earlier migration that tracks the same file
-// (056/057 for completeness, 060 for fix) so their drift-catch tests stay green.
+// Post-change shipped hashes. Mirror these into every earlier migration that
+// tracks the same file (056/057 for completeness, 060 for fix) so their
+// drift-catch tests stay green. The completeness hash reflects the post-083 body
+// (migration 083 added the with-edits `replace` field); the fix hash is still
+// 066's own output (no later migration touches it).
export const NEW_SHIPPED_MD5 = {
- 'pipeline-manuscript-completeness.md': 'cec8faeb75dfff74e41b8221145c2e92',
+ 'pipeline-manuscript-completeness.md': 'fd26f928c33803c12878a1bfb8561ece',
'pipeline-manuscript-fix.md': '88199bf7b5b50155bd2e1624bd920ebd',
};
diff --git a/scripts/migrations/083-completeness-with-edits-prompt.js b/scripts/migrations/083-completeness-with-edits-prompt.js
new file mode 100644
index 0000000000..90abb373c6
--- /dev/null
+++ b/scripts/migrations/083-completeness-with-edits-prompt.js
@@ -0,0 +1,59 @@
+/**
+ * Add the optional `replace` (with-edits) field to the manuscript-completeness
+ * ("Finish the draft") prompt.
+ *
+ * The editorial review can now run in a "generate edits for every finding" mode:
+ * the same completeness pass returns, alongside each finding's advisory
+ * `suggestion`, a concrete `replace` — the rewritten text that substitutes for
+ * `anchorQuote` to close the gap. The manuscript editor seeds each comment's
+ * `fix` from `{ find: anchorQuote, replace }`, so the user reviews the full diff
+ * and accepts edits one-by-one without a per-comment "Generate fix" call.
+ *
+ * The new `replace` field + its rule live inside a `{{#withEdits}}` Mustache
+ * section, so the findings-only pass renders the prompt exactly as before — only
+ * the with-edits pass sees the additional instruction. See
+ * server/services/pipeline/arcPlanner.js (shapeCompletenessFindings) and
+ * manuscriptReview.js (seedReviewFromFindings).
+ *
+ * `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: the post-066 (replacementStrategy) completeness body.
+export const ACCEPTED_OLD_MD5 = {
+ 'pipeline-manuscript-completeness.md': ['cec8faeb75dfff74e41b8221145c2e92'],
+};
+
+// Post-change shipped hash (with-edits `replace` field). Mirror this into every
+// earlier migration that tracks the same file (056/057/066) so their drift-catch
+// tests stay green.
+export const NEW_SHIPPED_MD5 = {
+ 'pipeline-manuscript-completeness.md': 'fd26f928c33803c12878a1bfb8561ece',
+};
+
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5,
+ current: NEW_SHIPPED_MD5,
+ label: 'manuscript-completeness with-edits replace prompt',
+ customizedHint: (filename) =>
+ ` To add the with-edits replace field manually, diff:\n` +
+ ` data.reference/prompts/stages/${filename}\n` +
+ ` against your current:\n` +
+ ` data/prompts/stages/${filename}\n` +
+ ` and add the {{#withEdits}} replace field to the output contract + rules.`,
+ skipFooter: (count) =>
+ `⚠️ ${count} prompt(s) could not be auto-updated because they were\n` +
+ ` customized. Editorial review still works, but the "generate edits for\n` +
+ ` every finding" option won't pre-build fixes (the per-comment\n` +
+ ` "Generate fix" button still works) until you merge the change.\n` +
+ ` See data.reference/prompts/stages/pipeline-manuscript-completeness.md.`,
+});
+
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/083-completeness-with-edits-prompt.test.js b/scripts/migrations/083-completeness-with-edits-prompt.test.js
new file mode 100644
index 0000000000..82407bfe6c
--- /dev/null
+++ b/scripts/migrations/083-completeness-with-edits-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 './083-completeness-with-edits-prompt.js';
+
+describe('migration 083 — manuscript-completeness with-edits replace prompt', () => {
+ runPromptMigrationTests({
+ migration,
+ applyMigration,
+ ACCEPTED_OLD_MD5,
+ NEW_SHIPPED_MD5,
+ prefix: 'migration-083-',
+ });
+});
diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.js
index 70a967cd26..4c905205c5 100644
--- a/scripts/setup-data-drift.test.js
+++ b/scripts/setup-data-drift.test.js
@@ -38,7 +38,7 @@ const EXPECTED_STAGE_OLD = {
'universe-character-expand.md': ['ef109eb8e12ddb664c11c790271b5139'],
'story-builder-idea-expand.md': ['778c86e2caa120856c36e4d5a4da3355', 'a23939626a226f7420cebfb45d47950c'],
'pipeline-editorial-analysis.md': ['14d9879697c66d51830cc798040d5369'],
- 'pipeline-manuscript-completeness.md': ['4f2b95778aed85f5fc461d71eb461b79', 'e6858c74ab2cead752d388e3f428406c', '1ee5ac936fbf1d365e0eaea99bcf1e77'],
+ 'pipeline-manuscript-completeness.md': ['4f2b95778aed85f5fc461d71eb461b79', 'e6858c74ab2cead752d388e3f428406c', '1ee5ac936fbf1d365e0eaea99bcf1e77', 'cec8faeb75dfff74e41b8221145c2e92'],
'pipeline-manuscript-fix.md': ['196625952f4a36f3cb962c729f60f0ee', 'c88a56304eb5e290ae0de9dadd20b310'],
'cos-agent-briefing.md': ['181b26838e526427173e4dccfc884d01', '3e1ca7f7b14b799f89a193c568003624', '699d053875472df455258724a0162bd5', '9bcd3a0167dd4aed7cfff7f404494dfb', 'af73fd50d6f29d561772474c12346e53', 'd761133753da290a0c02eca1c87709e4'],
'pipeline-tv-script.md': ['3f6fecc25573ed054b47db392250034a'],
@@ -59,7 +59,7 @@ const EXPECTED_STAGE_NEW = {
'universe-character-expand.md': '67b6e73ed47f318451a730088b4cff14',
'story-builder-idea-expand.md': 'c12d76fefaaded2838023065bfc94bb0',
'pipeline-editorial-analysis.md': 'daeb02bd54b0c099b21af659c6298cfe',
- 'pipeline-manuscript-completeness.md': 'cec8faeb75dfff74e41b8221145c2e92',
+ 'pipeline-manuscript-completeness.md': 'fd26f928c33803c12878a1bfb8561ece',
'pipeline-manuscript-fix.md': '88199bf7b5b50155bd2e1624bd920ebd',
'pipeline-tv-script.md': '376f779f4687b598f1c92ca4e770fd5a',
};
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
index 88a888b12c..a870a146f4 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -334,6 +334,13 @@ vi.mock('../services/pipeline/editorialAnalysisRunner.js', () => ({
cancelSeriesAnalysis: vi.fn(() => true),
isSeriesAnalysisActive: vi.fn(() => false),
}));
+const startCompletenessReviewMock = vi.fn(async () => ({ runId: 'cr-run-1', alreadyRunning: false }));
+vi.mock('../services/pipeline/manuscriptCompletenessRunner.js', () => ({
+ startCompletenessReview: (...a) => startCompletenessReviewMock(...a),
+ attachClient: vi.fn(() => false),
+ cancelCompletenessReview: vi.fn(() => true),
+ isCompletenessReviewActive: vi.fn(() => false),
+}));
const pipelineRouter = (await import('./pipeline/index.js')).default;
const universeSvc = await import('../services/universeBuilder.js');
@@ -2169,6 +2176,38 @@ describe('pipeline routes', () => {
expect(Array.isArray(r.body.review?.comments)).toBe(true);
});
+ it('POST /series/:id/manuscript/completeness/stream starts the runner + returns sseUrl', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
+ startCompletenessReviewMock.mockClear();
+ const r = await request(app)
+ .post(`/api/pipeline/series/${ser.body.id}/manuscript/completeness/stream`)
+ .send({ mode: 'fresh' });
+ expect(r.status).toBe(200);
+ expect(r.body.runId).toBe('cr-run-1');
+ expect(r.body.sseUrl).toContain(`/manuscript/completeness/progress`);
+ expect(startCompletenessReviewMock).toHaveBeenCalledWith(
+ ser.body.id,
+ expect.objectContaining({ mode: 'fresh' }),
+ );
+ });
+
+ it('GET /series/:id/manuscript/completeness/status reports active flag', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
+ const r = await request(app).get(`/api/pipeline/series/${ser.body.id}/manuscript/completeness/status`);
+ expect(r.status).toBe(200);
+ expect(r.body).toEqual({ active: false });
+ });
+
+ it('POST /series/:id/manuscript/completeness/cancel returns the cancel result', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
+ const r = await request(app).post(`/api/pipeline/series/${ser.body.id}/manuscript/completeness/cancel`).send({});
+ expect(r.status).toBe(200);
+ expect(r.body).toEqual({ canceled: true });
+ });
+
describe('manuscript editor routes', () => {
it('GET /series/:id/manuscript returns sections + primaryStageId; review starts empty', async () => {
const app = makeApp();
diff --git a/server/routes/pipeline/manuscript.js b/server/routes/pipeline/manuscript.js
index 3e88cfc698..8846059c45 100644
--- a/server/routes/pipeline/manuscript.js
+++ b/server/routes/pipeline/manuscript.js
@@ -9,13 +9,14 @@
import { Router } from 'express';
import { z } from 'zod';
-import { asyncHandler } from '../../lib/errorHandler.js';
+import { asyncHandler, ServerError } from '../../lib/errorHandler.js';
import { validateRequest } from '../../lib/validation.js';
import * as seriesSvc from '../../services/pipeline/series.js';
import * as issuesSvc from '../../services/pipeline/issues.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 * as completenessRunner from '../../services/pipeline/manuscriptCompletenessRunner.js';
import { mapServiceError, providerOverrideShape } from './shared.js';
const router = Router();
@@ -86,6 +87,43 @@ router.post('/series/:id/manuscript/completeness', asyncHandler(async (req, res)
res.json({ ...result, review });
}));
+// Streamed completeness review — backs the "generate edits for every finding"
+// option. Kicks off the runner (which streams per-chunk progress over SSE, then
+// seeds the review with pre-attached fixes) and returns the runId + SSE url. The
+// client re-fetches the review on the terminal `complete` frame.
+router.post('/series/:id/manuscript/completeness/stream', asyncHandler(async (req, res) => {
+ await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const body = validateRequest(manuscriptCompletenessSchema, req.body ?? {});
+ // The streamed runner always generates per-finding edits (that's its reason to
+ // exist) — no `withEdits` knob; the sync /completeness route stays findings-only.
+ const result = await completenessRunner.startCompletenessReview(req.params.id, {
+ providerOverride: body.providerOverride,
+ modelOverride: body.modelOverride,
+ mode: body.mode,
+ });
+ res.json({
+ ...result,
+ sseUrl: `/api/pipeline/series/${req.params.id}/manuscript/completeness/progress`,
+ });
+}));
+
+router.get('/series/:id/manuscript/completeness/progress', (req, res) => {
+ const attached = completenessRunner.attachClient(req.params.id, res);
+ if (!attached) {
+ throw new ServerError('No active completeness review for this series', { status: 404 });
+ }
+});
+
+// Lightweight probe so a (re)mounting client can re-attach to an in-flight run.
+router.get('/series/:id/manuscript/completeness/status', (req, res) => {
+ res.json({ active: completenessRunner.isCompletenessReviewActive(req.params.id) });
+});
+
+router.post('/series/:id/manuscript/completeness/cancel', asyncHandler(async (req, res) => {
+ const canceled = completenessRunner.cancelCompletenessReview(req.params.id);
+ res.json({ canceled });
+}));
+
// 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
diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.js
index 1b6c8b2393..0fe6448f6b 100644
--- a/server/services/pipeline/arcPlanner.js
+++ b/server/services/pipeline/arcPlanner.js
@@ -24,7 +24,7 @@ import { planManuscriptPass, estimateTokens } from '../../lib/contextBudget.js';
import { ServerError } from '../../lib/errorHandler.js';
import { stripAnsi } from '../../lib/ansiStrip.js';
import { getSeries, updateSeries, updateSeasonOnSeries, ARC_LOCKABLE_FIELDS, MANUSCRIPT_TYPES } from './series.js';
-import { listIssues, updateIssue, recomputeIssueNumbersForSeries, getIssue, updateStage, updateStageWithLatest, assertStageUnlocked, createIssue } from './issues.js';
+import { listIssues, updateIssue, recomputeIssueNumbersForSeries, getIssue, updateStage, updateStageWithLatest, assertStageUnlocked, createIssue, STAGE_OUTPUT_MAX } from './issues.js';
import { emitRecordUpdated, withReexportSuppressed } from '../sharing/recordEvents.js';
import { getSeason } from './seasons.js';
import {
@@ -695,14 +695,18 @@ export const REPLACEMENT_STRATEGIES = new Set(['delta', 'full-page']);
export const replacementStrategyForCategory = (category) =>
(category === 'comic-structure' ? 'full-page' : 'delta');
-function shapeCompletenessFindings(rawIssues) {
+// Cap on a finding's `replace` span (the with-edits in-place rewrite). Matches
+// the fix path's per-edit replace ceiling so a long page rewrite isn't clipped.
+const COMPLETENESS_REPLACE_MAX = STAGE_OUTPUT_MAX;
+
+function shapeCompletenessFindings(rawIssues, { withEdits = false } = {}) {
if (!Array.isArray(rawIssues)) return [];
const out = [];
for (const raw of rawIssues) {
const problem = typeof raw?.problem === 'string' ? raw.problem.trim() : '';
if (!problem) continue;
const category = COMPLETENESS_CATEGORIES.has(raw?.category) ? raw.category : 'other';
- out.push({
+ const finding = {
severity: VERIFY_SEVERITIES.has(raw?.severity) ? raw.severity : 'medium',
category,
// 'full-page' = suggestion is a complete replacement document (comic-structure);
@@ -720,7 +724,16 @@ function shapeCompletenessFindings(rawIssues) {
// 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) : '',
- });
+ };
+ // With-edits pass: carry the concrete in-place rewrite so the editor can seed
+ // each comment's `fix` from { find: anchorQuote, replace } without a separate
+ // "Generate fix" call. Absent/empty `replace` (or no anchor to splice over) →
+ // the finding stays advice-only and falls back to manual fix generation.
+ if (withEdits) {
+ const replace = typeof raw?.replace === 'string' ? raw.replace.trim() : '';
+ if (replace) finding.replace = replace.slice(0, COMPLETENESS_REPLACE_MAX);
+ }
+ out.push(finding);
}
return out;
}
@@ -743,6 +756,9 @@ const COMPLETENESS_STAGE = 'pipeline-manuscript-completeness';
// Output room for the findings list; comic-structure suggestions are full page
// rewrites, so reserve generously.
const COMPLETENESS_OUTPUT_RESERVE_TOKENS = 6_000;
+// The with-edits pass returns a full `replace` span per finding on top of the
+// advice, so it needs materially more output room or a long edit list truncates.
+const COMPLETENESS_WITH_EDITS_OUTPUT_RESERVE_TOKENS = 12_000;
// Earlier-chapter findings summarized into the rolling digest fed to later
// chunks, and the char cap on that digest (kept small so it fits the margin).
const COMPLETENESS_PRIOR_DIGEST_MAX = 40;
@@ -785,6 +801,17 @@ const findingKey = (f) => [
* target model's window it runs in one call (frontier models hold the entire
* book); otherwise it chunks by issue, feeds each chunk a digest of prior-chunk
* findings for continuity, and merges with first-wins dedupe.
+ *
+ * `options.withEdits` (default false) asks the model to also return a concrete
+ * `replace` per finding (an in-place rewrite of `anchorQuote`) so the editor can
+ * pre-seed each comment's fix. It widens the output reserve accordingly.
+ *
+ * `options.onProgress(event)` — optional callback fired around the chunk loop so
+ * the SSE runner can stream progress without re-implementing the chunk/merge/
+ * digest logic. Events: `{ type:'plan', mode, total }`, `{ type:'chunk:start',
+ * done, total }`, `{ type:'chunk:complete', done, total }`. `options.signal` —
+ * optional AbortSignal; when aborted between chunks the loop stops and returns
+ * the findings gathered so far (marked `canceled: true`).
*/
export async function analyzeManuscriptCompleteness(seriesId, options = {}) {
const series = await getSeries(seriesId);
@@ -798,6 +825,10 @@ export async function analyzeManuscriptCompleteness(seriesId, options = {}) {
);
}
+ const withEdits = !!options.withEdits;
+ const onProgress = typeof options.onProgress === 'function' ? options.onProgress : () => {};
+ const signal = options.signal || null;
+
// Base (non-manuscript) context is fixed overhead present in every call.
const baseCtx = await buildCompletenessContext(series, '', options.preloadedWorld);
const overheadTokens = estimateTokens(JSON.stringify(baseCtx)) + 2_000; // + template/instructions
@@ -809,10 +840,12 @@ export async function analyzeManuscriptCompleteness(seriesId, options = {}) {
contextWindow,
sections: sections.map((s) => ({ ...s, text: `${manuscriptSectionHeader(s)}\n\n${s.content}` })),
overheadTokens,
- outputReserveTokens: COMPLETENESS_OUTPUT_RESERVE_TOKENS,
+ outputReserveTokens: withEdits
+ ? COMPLETENESS_WITH_EDITS_OUTPUT_RESERVE_TOKENS
+ : COMPLETENESS_OUTPUT_RESERVE_TOKENS,
});
- const runOne = (manuscript) => runStagedLLM(COMPLETENESS_STAGE, { ...baseCtx, manuscript }, {
+ const runOne = (manuscript) => runStagedLLM(COMPLETENESS_STAGE, { ...baseCtx, manuscript, withEdits }, {
providerOverride: options.providerOverride,
modelOverride: options.modelOverride,
returnsJson: true,
@@ -820,24 +853,34 @@ export async function analyzeManuscriptCompleteness(seriesId, options = {}) {
});
if (plan.mode === 'whole') {
+ onProgress({ type: 'plan', mode: 'whole', total: 1 });
+ onProgress({ type: 'chunk:start', done: 0, total: 1 });
const { content, runId, providerId, model } = await runOne(sectionsCorpus(sections).slice(0, plan.usableChars));
- return { issues: shapeCompletenessFindings(content?.issues), raw: content, runId, providerId, model, chunked: false, chunkCount: 1 };
+ onProgress({ type: 'chunk:complete', done: 1, total: 1 });
+ return { issues: shapeCompletenessFindings(content?.issues, { withEdits }), raw: content, runId, providerId, model, chunked: false, chunkCount: 1 };
}
console.log(`📚 completeness: chunked review series=${String(seriesId).slice(0, 12)} chunks=${plan.chunks.length} window=${contextWindow ?? 'floor'}`);
+ onProgress({ type: 'plan', mode: 'chunked', total: plan.chunks.length });
// Accumulate findings into one first-wins map so the per-chunk digest is O(1)
// to derive (no re-merging every prior chunk).
const merged = new Map();
let first = null;
+ let done = 0;
+ let canceled = false;
for (const chunk of plan.chunks) {
+ if (signal?.aborted) { canceled = true; break; }
+ onProgress({ type: 'chunk:start', done, total: plan.chunks.length });
const digest = priorFindingsDigest([...merged.values()]);
const corpus = sectionsCorpus(chunk.sections).slice(0, plan.usableChars);
const result = await runOne(`${digest}${corpus}`);
if (!first) first = result;
- for (const f of shapeCompletenessFindings(result.content?.issues)) {
+ for (const f of shapeCompletenessFindings(result.content?.issues, { withEdits })) {
const k = findingKey(f);
if (!merged.has(k)) merged.set(k, f);
}
+ done += 1;
+ onProgress({ type: 'chunk:complete', done, total: plan.chunks.length });
}
const issues = [...merged.values()];
return {
@@ -848,6 +891,7 @@ export async function analyzeManuscriptCompleteness(seriesId, options = {}) {
model: first?.model,
chunked: true,
chunkCount: plan.chunks.length,
+ canceled,
};
}
diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.js
index a30cb28ad6..328cd6b266 100644
--- a/server/services/pipeline/arcPlanner.test.js
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -1686,6 +1686,46 @@ describe('arcPlanner — manuscript completeness + derive-from-manuscript', () =
expect(out[3].replacementStrategy).toBe('full-page'); // invalid → category default
});
+ it('shapeCompletenessFindings reads `replace` only in the with-edits pass (trimmed; absent → no key)', () => {
+ const { shapeCompletenessFindings } = planner.__testing;
+ const raw = [
+ { category: 'missing-content', problem: 'abrupt', anchorQuote: 'She left.', replace: ' She left, but paused. ' },
+ { category: 'pacing', problem: 'no replace', anchorQuote: 'q' }, // model omitted replace
+ ];
+ // Findings-only pass ignores `replace` entirely.
+ const findingsOnly = shapeCompletenessFindings(raw);
+ expect(findingsOnly[0]).not.toHaveProperty('replace');
+ // With-edits pass carries a trimmed `replace`; an absent one yields no key.
+ const withEdits = shapeCompletenessFindings(raw, { withEdits: true });
+ expect(withEdits[0].replace).toBe('She left, but paused.');
+ expect(withEdits[1]).not.toHaveProperty('replace');
+ });
+
+ it('analyzeManuscriptCompleteness passes withEdits into the prompt ctx and shapes replace', async () => {
+ const s = await setupSeries();
+ await issuesSvc.createIssue({ seriesId: s.id, title: 'One', arcPosition: 1, stages: { prose: { output: 'The hero walked in. She left.', status: 'ready' } } });
+ stageRunnerSpy = vi.fn(async (template, ctx) => {
+ expect(ctx.withEdits).toBe(true);
+ return {
+ content: { issues: [{ severity: 'high', category: 'arc-gap', issueNumber: 1, anchorQuote: 'She left.', problem: 'abrupt', suggestion: 'add a beat', replace: 'She left, but paused.' }] },
+ runId: 'rc', providerId: 'p', model: 'm',
+ };
+ });
+ const out = await planner.analyzeManuscriptCompleteness(s.id, { withEdits: true });
+ expect(out.issues[0].replace).toBe('She left, but paused.');
+ });
+
+ it('analyzeManuscriptCompleteness defaults withEdits false (ctx.withEdits=false, no replace shaped)', 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 (template, ctx) => {
+ expect(ctx.withEdits).toBe(false);
+ return { content: { issues: [{ severity: 'low', category: 'pacing', problem: 'thin', replace: 'ignored' }] }, runId: 'rc', providerId: 'p', model: 'm' };
+ });
+ const out = await planner.analyzeManuscriptCompleteness(s.id);
+ expect(out.issues[0]).not.toHaveProperty('replace');
+ });
+
it('analyzeManuscriptCompleteness reads the manuscript and returns shaped findings', async () => {
const s = await setupSeries();
await issuesSvc.createIssue({
diff --git a/server/services/pipeline/manuscriptCompletenessRunner.js b/server/services/pipeline/manuscriptCompletenessRunner.js
new file mode 100644
index 0000000000..22f976f1d5
--- /dev/null
+++ b/server/services/pipeline/manuscriptCompletenessRunner.js
@@ -0,0 +1,152 @@
+/**
+ * Pipeline — Batch runner for the manuscript-completeness ("Finish the draft")
+ * editorial review, streaming per-chunk progress to attached SSE clients.
+ *
+ * The synchronous `POST /manuscript/completeness` route stays the entry point
+ * for the findings-only pass (and the ArcCanvas "Finish the draft" caller). This
+ * runner backs the heavier "generate edits for every finding" pass, where the
+ * model also returns a concrete `replace` per finding: a chunked large manuscript
+ * would otherwise show a long opaque spinner, so we stream chunk progress.
+ *
+ * Mirrors editorialAnalysisRunner.js: a single in-memory `runs` map keyed by
+ * `seriesId`, with terminal-frame replay for late-connecting clients via
+ * lib/sseUtils.js. The actual chunk/merge/digest loop is NOT re-implemented here
+ * — it lives in arcPlanner.analyzeManuscriptCompleteness, which this runner
+ * drives via its `onProgress` + `signal` hooks. After analysis the runner seeds
+ * the review (so each comment lands with its `fix` pre-attached) exactly as the
+ * sync route does.
+ */
+
+import { randomUUID } from 'crypto';
+import { broadcastSse, attachSseClient, SSE_CLEANUP_DELAY_MS } from '../../lib/sseUtils.js';
+import { analyzeManuscriptCompleteness } from './arcPlanner.js';
+import { seedReviewFromFindings } from './manuscriptReview.js';
+
+// runs: Map<seriesId, { runId, clients[], lastPayload, cancelRequested, finished, cleanupTimer, startedAt, abort }>
+// A finished run lingers in the map for SSE_CLEANUP_DELAY_MS so late-attaching
+// clients can replay its terminal frame — but `finished` lets `isActive` and
+// the restart guard treat it as done, so an immediate re-run isn't swallowed.
+const runs = new Map();
+
+export function isCompletenessReviewActive(seriesId) {
+ const run = runs.get(seriesId);
+ return !!run && !run.finished;
+}
+
+// Hold a finished run open briefly for terminal-frame replay, then evict it —
+// but only if THIS record is still the one mapped, so a restart that replaced
+// it within the window isn't clobbered by the prior run's timer.
+function scheduleCleanup(seriesId, record) {
+ record.cleanupTimer = setTimeout(() => {
+ if (runs.get(seriesId) !== record) return;
+ for (const c of record.clients) c.end();
+ runs.delete(seriesId);
+ }, SSE_CLEANUP_DELAY_MS);
+}
+
+export function attachClient(seriesId, res) {
+ return attachSseClient(runs, seriesId, res);
+}
+
+export function cancelCompletenessReview(seriesId) {
+ const run = runs.get(seriesId);
+ if (!run) return false;
+ run.cancelRequested = true;
+ run.abort?.abort();
+ return true;
+}
+
+function broadcast(seriesId, payload) {
+ const run = runs.get(seriesId);
+ if (!run) return;
+ broadcastSse(run, payload);
+}
+
+/**
+ * Kick off the streamed completeness review (always the generate-edits pass).
+ * Returns the runId immediately; progress lands via SSE. Re-calling while a run
+ * is in flight resolves to the existing runId.
+ * `options`: { providerOverride, modelOverride, mode }.
+ */
+export async function startCompletenessReview(seriesId, options = {}) {
+ const existing = runs.get(seriesId);
+ if (existing && !existing.finished) {
+ return { runId: existing.runId, alreadyRunning: true };
+ }
+ if (existing) {
+ // A finished run still in its replay window — cancel its pending eviction
+ // and drop its replay clients so this fresh run fully replaces it.
+ if (existing.cleanupTimer) clearTimeout(existing.cleanupTimer);
+ for (const c of existing.clients) c.end();
+ }
+ const runId = randomUUID();
+ const abort = new AbortController();
+ const record = {
+ runId,
+ clients: [],
+ lastPayload: null,
+ cancelRequested: false,
+ finished: false,
+ cleanupTimer: null,
+ startedAt: new Date().toISOString(),
+ abort,
+ };
+ runs.set(seriesId, record);
+
+ // Fire-and-forget coordinator. The try/catch is the permitted boundary use:
+ // an unhandled LLM rejection here would crash the process on Node ≥15.
+ (async () => {
+ try {
+ broadcast(seriesId, { type: 'start', runId });
+ const result = await analyzeManuscriptCompleteness(seriesId, {
+ providerOverride: options.providerOverride,
+ modelOverride: options.modelOverride,
+ withEdits: true, // the streamed runner exists to pre-build per-finding edits
+ signal: abort.signal,
+ onProgress: (event) => {
+ // Forward the analyzer's progress events to SSE, stamping the runId and
+ // flattening `plan`'s mode into a `chunked` flag the client reads.
+ if (event.type === 'plan') broadcast(seriesId, { type: 'plan', runId, total: event.total, chunked: event.mode === 'chunked' });
+ else if (event.type === 'chunk:start' || event.type === 'chunk:complete') {
+ broadcast(seriesId, { type: event.type, runId, done: event.done, total: event.total });
+ }
+ },
+ });
+
+ if (record.cancelRequested || result.canceled) {
+ broadcast(seriesId, { type: 'canceled', runId, canceledAt: new Date().toISOString() });
+ console.log(`📚 completeness review canceled — series=${String(seriesId).slice(0, 12)}`);
+ return;
+ }
+
+ // Seed the persisted review exactly as the sync route does, so each comment
+ // lands with its pre-built `fix` (when the finding carried a replace).
+ const review = await seedReviewFromFindings(seriesId, result.issues, {
+ runId: result.runId,
+ mode: options.mode,
+ });
+ const openCount = review.comments.filter((c) => c.status === 'open').length;
+ broadcast(seriesId, {
+ type: 'complete',
+ runId,
+ openCount,
+ chunked: !!result.chunked,
+ chunkCount: result.chunkCount || 1,
+ completedAt: new Date().toISOString(),
+ });
+ console.log(`📚 completeness review complete — series=${String(seriesId).slice(0, 12)} open=${openCount} chunks=${result.chunkCount || 1}`);
+ } catch (err) {
+ const message = (err?.message || String(err)).slice(0, 1000);
+ console.error(`❌ completeness review failed — series=${String(seriesId).slice(0, 12)} ${message}`);
+ broadcast(seriesId, { type: 'error', runId, error: message, failedAt: new Date().toISOString() });
+ } finally {
+ record.finished = true;
+ scheduleCleanup(seriesId, record);
+ }
+ })();
+
+ return { runId, alreadyRunning: false };
+}
+
+// Export internals for tests.
+export const __testing = { runs };
diff --git a/server/services/pipeline/manuscriptFix.js b/server/services/pipeline/manuscriptFix.js
index 3c8ac91d5d..6cf2984b5a 100644
--- a/server/services/pipeline/manuscriptFix.js
+++ b/server/services/pipeline/manuscriptFix.js
@@ -92,38 +92,56 @@ function resolveEditSection(raw, targets) {
return null;
}
+/**
+ * Shape one anchored edit from a `find`/`replace` pair against a resolved
+ * manuscript section. Returns null when either side is empty. `fuzzy` is set
+ * only when `find` can't be located even tolerating whitespace differences —
+ * i.e. when accept would actually fail; a quote that differs only in spacing
+ * still applies, so it doesn't warn. Shared by the fix pass (normalizeFix) and
+ * the with-edits completeness pass (manuscriptReview.seedReviewFromFindings),
+ * so both produce byte-identical edit shapes the accept path can consume.
+ */
+export function shapeAnchoredEdit(section, { find, replace, note } = {}) {
+ if (!section || !find || !replace) return null;
+ const edit = {
+ issueNumber: section.number,
+ issueId: section.issueId,
+ stageId: section.stageId,
+ title: section.title || '',
+ find,
+ replace,
+ };
+ if (typeof note === 'string' && note.trim()) edit.note = note.trim().slice(0, 1000);
+ if (!locateFindSpan(section.content || '', find)) edit.fuzzy = true;
+ return edit;
+}
+
+/**
+ * Wrap a list of shaped edits into a `fix` record, rebuilding the single-edit
+ * convenience fields (`find`/`replace`/`fuzzy`) the accept path reads. Returns
+ * null for an empty list. Shared by normalizeFix, mergeFixes, and the seed path.
+ */
+export function fixFromEdits(edits) {
+ if (!Array.isArray(edits) || edits.length === 0) return null;
+ const fix = { edits };
+ if (edits.length === 1) {
+ fix.find = edits[0].find;
+ fix.replace = edits[0].replace;
+ if (edits[0].fuzzy) fix.fuzzy = true;
+ }
+ return fix;
+}
+
function normalizeFix(content, targets) {
const edits = normalizeModelEdits(content)
.map((raw) => {
const find = typeof raw?.find === 'string' ? raw.find : '';
const replace = typeof raw?.replace === 'string' ? raw.replace : '';
if (!find || !replace) return null;
- const section = resolveEditSection(raw, targets);
- if (!section) return null;
- const edit = {
- issueNumber: section.number,
- issueId: section.issueId,
- stageId: section.stageId,
- title: section.title || '',
- find,
- replace,
- };
- if (typeof raw.note === 'string' && raw.note.trim()) edit.note = raw.note.trim().slice(0, 1000);
- // Flag fuzzy only when the find can't be located even tolerating
- // whitespace differences — i.e. accept would actually fail. A quote that
- // differs only in spacing still applies, so it shouldn't warn.
- if (!locateFindSpan(section.content || '', find)) edit.fuzzy = true;
- return edit;
+ return shapeAnchoredEdit(resolveEditSection(raw, targets), { find, replace, note: raw.note });
})
.filter(Boolean);
- if (edits.length === 0) return null;
- const fix = { edits };
- if (edits.length === 1) {
- fix.find = edits[0].find;
- fix.replace = edits[0].replace;
- if (edits[0].fuzzy) fix.fuzzy = true;
- }
- return fix;
+ return fixFromEdits(edits);
}
function editsFromAcceptRequest({ comment, find, replace, edits }) {
@@ -322,14 +340,7 @@ function mergeFixes(fixes) {
edits.push(e);
}
}
- if (edits.length === 0) return null;
- const fix = { edits };
- if (edits.length === 1) {
- fix.find = edits[0].find;
- fix.replace = edits[0].replace;
- if (edits[0].fuzzy) fix.fuzzy = true;
- }
- return fix;
+ return fixFromEdits(edits);
}
export async function generateManuscriptFix(seriesId, { commentId, providerOverride, modelOverride } = {}) {
diff --git a/server/services/pipeline/manuscriptReview.js b/server/services/pipeline/manuscriptReview.js
index c5b6087761..6a8a92184a 100644
--- a/server/services/pipeline/manuscriptReview.js
+++ b/server/services/pipeline/manuscriptReview.js
@@ -21,6 +21,7 @@ import { atomicWrite, readJSONFile } from '../../lib/fileUtils.js';
import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';
import { seriesStore } from './series.js';
import { collectManuscriptSections, REPLACEMENT_STRATEGIES, replacementStrategyForCategory } from './arcPlanner.js';
+import { shapeAnchoredEdit, fixFromEdits } from './manuscriptFix.js';
import { emitRecordUpdated } from '../sharing/recordEvents.js';
// Storage-layout version for the review document. Bump + migrate if the
@@ -183,7 +184,12 @@ export async function seedReviewFromFindings(seriesId, findings, { runId = null,
const candidates = [];
for (const f of Array.isArray(findings) ? findings : []) {
const candidate = sanitizeComment({ ...f, status: 'open', sourceRunId: runId, createdAt: now, updatedAt: now });
- if (candidate) candidates.push(candidate);
+ if (!candidate) continue;
+ // `replace` (the with-edits in-place rewrite) isn't part of the stored
+ // comment shape, so sanitizeComment drops it — stash it on the candidate so
+ // the append loop below can build the comment's `fix` from it.
+ if (typeof f?.replace === 'string' && f.replace) candidate.replace = f.replace;
+ candidates.push(candidate);
}
const freshKeys = new Set(candidates.map(findingKey));
@@ -212,6 +218,23 @@ export async function seedReviewFromFindings(seriesId, findings, { runId = null,
candidate.issueId = section.issueId;
candidate.stageId = section.stageId;
}
+ // With-edits pass: the finding carried a concrete `replace` rewrite of its
+ // `anchorQuote`. Pre-seed the comment's fix from { find: anchorQuote,
+ // replace } via the same shaper the manual "Generate fix" path uses, so the
+ // editor shows the diff + Accept with no per-comment fix call. Skipped when
+ // there's no anchor to splice over, no resolved section, or no replace —
+ // those findings stay advice-only and fall back to manual fix generation.
+ // Also skipped when the anchor can't be located even whitespace-tolerantly
+ // (shapeAnchoredEdit flags that as `fuzzy`): unlike the manual path, the
+ // bulk pass has no per-comment warning, so an unappliable fix would present
+ // a diff whose Accept silently fails — leave it advice-only instead.
+ if (candidate.replace && candidate.anchorQuote && section) {
+ const edit = shapeAnchoredEdit(section, { find: candidate.anchorQuote, replace: candidate.replace });
+ if (edit && !edit.fuzzy) candidate.fix = fixFromEdits([edit]);
+ }
+ // `replace` is consumed into `fix` (or dropped) — it's not part of the
+ // stored comment shape (sanitizeComment ignores unknown keys, but be tidy).
+ delete candidate.replace;
seenKeys.add(key);
fresh.push(candidate);
}
diff --git a/server/services/pipeline/manuscriptReview.test.js b/server/services/pipeline/manuscriptReview.test.js
index 5e082dbbe0..1d363d373a 100644
--- a/server/services/pipeline/manuscriptReview.test.js
+++ b/server/services/pipeline/manuscriptReview.test.js
@@ -12,8 +12,9 @@ vi.mock('./series.js', () => ({
seriesStore: () => ({ recordDir: (id) => `/mock/series/${id}` }),
}));
-// No manuscript sections needed for these tests (seed resolves issueId/stageId
-// from them, but we don't assert on those here).
+// No manuscript sections needed for most tests (seed resolves issueId/stageId
+// from them, but we don't assert on those here). The with-edits fix-seeding test
+// overrides this to return a section so the anchor can resolve.
vi.mock('./arcPlanner.js', () => ({
collectManuscriptSections: vi.fn(async () => []),
// sanitizeComment imports these to classify a finding's suggestion. Mirror
@@ -23,6 +24,7 @@ vi.mock('./arcPlanner.js', () => ({
}));
import { recordEvents } from '../sharing/recordEvents.js';
+import { collectManuscriptSections } from './arcPlanner.js';
import { seedReviewFromFindings, updateComment, mergeReviewFromSync } from './manuscriptReview.js';
describe('manuscriptReview — record-event emission on write', () => {
@@ -162,3 +164,54 @@ describe('manuscriptReview — re-run merge vs fresh reconcile', () => {
expect(kept[0].status).toBe('dismissed');
});
});
+
+describe('manuscriptReview — with-edits fix seeding', () => {
+ beforeEach(() => {
+ fileStore.clear();
+ // A section whose content contains the verbatim anchor so the fix resolves.
+ collectManuscriptSections.mockResolvedValue([
+ { issueId: 'iss-1', stageId: 'prose', number: 1, title: 'One', content: 'The hero walked in. She left.' },
+ ]);
+ });
+ afterEach(() => { collectManuscriptSections.mockResolvedValue([]); });
+
+ it('attaches a fix built from { find: anchorQuote, replace } when the finding carries a replace', async () => {
+ const seeded = await seedReviewFromFindings('ser-edits', [
+ { problem: 'abrupt ending', anchorQuote: 'She left.', replace: 'She left, but paused.', issueNumber: 1 },
+ ]);
+ const c = seeded.comments[0];
+ expect(c.fix).toBeTruthy();
+ expect(c.fix.find).toBe('She left.');
+ expect(c.fix.replace).toBe('She left, but paused.');
+ expect(c.fix.edits).toHaveLength(1);
+ expect(c.fix.edits[0]).toMatchObject({ issueId: 'iss-1', stageId: 'prose', issueNumber: 1, find: 'She left.', replace: 'She left, but paused.' });
+ // `replace` is consumed into the fix, not persisted as a stray comment field.
+ expect(c.replace).toBeUndefined();
+ });
+
+ it('still attaches a fix when the anchor differs only in whitespace (tolerant match)', async () => {
+ const seeded = await seedReviewFromFindings('ser-edits-fuzzy', [
+ { problem: 'gap', anchorQuote: 'She left.', replace: 'She left, but paused.', issueNumber: 1 },
+ ]);
+ // The exact span "She left." is absent, but the whitespace-tolerant locate
+ // matches "She left." — accept would succeed, so the fix attaches (not gated
+ // out as unappliable).
+ const c = seeded.comments[0];
+ expect(c.fix).toBeTruthy();
+ expect(c.fix.find).toBe('She left.');
+ });
+
+ it('leaves fix null when the finding has no replace (advice-only / findings pass)', async () => {
+ const seeded = await seedReviewFromFindings('ser-no-edits', [
+ { problem: 'just advice', anchorQuote: 'She left.', issueNumber: 1 },
+ ]);
+ expect(seeded.comments[0].fix).toBeNull();
+ });
+
+ it('leaves fix null when the anchor cannot be located in any section', async () => {
+ const seeded = await seedReviewFromFindings('ser-no-anchor', [
+ { problem: 'unanchorable', anchorQuote: 'text that does not appear', replace: 'rewrite', issueNumber: 1 },
+ ]);
+ expect(seeded.comments[0].fix).toBeNull();
+ });
+});