Skip to content

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

feat([issue-2173]): Writers Room autonomous polish loop (cuts → revise → keep/revert)

Adam Eivye8eacdc74aac
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 031e4e7490..93ce1ae28b 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -57,6 +57,7 @@
- **[issue-2179] The voice-drift check can now measure each issue against the voice you CHOSE — its style-guide exemplars — instead of the average of what got drafted.** The `style.voice-drift` check flags an issue whose prose fingerprint sits more than a threshold's σ from a baseline; that baseline used to be the drafted-issue mean, which has a blind spot — if every issue drifted the same way, the average drifts with them and nothing flags. A new **Drift baseline** setting on the check adds two modes on top of the default `drafted`: `exemplars` re-centers every metric on the combined fingerprint of the style guide's voice exemplars (the "tuning fork" passages from the first #2179 slice), and `blended` uses the midpoint of the two. In exemplar/blended mode the spread (σ) is still the drafted corpus's — only the center shifts — so an issue is judged against the chosen voice while still tolerating the series' natural per-metric variance. When the style guide has too little exemplar prose (under ~40 words combined) the run silently falls back to `drafted` and says so. Findings read "…vs the style guide's chosen voice of 5 words" instead of implying drift from the drafted mean, and the deep-linkable **Voice Fingerprint** matrix view renders the chosen-voice baseline as its own footer row with the outlier cells measured against it. The check now also lists the style guide as a source, so editing an exemplar re-stales the finding — exactly like its LLM siblings. (Third slice of #2179 — the voice-fingerprint baseline hook; the AI-assisted voice-discovery flow and Writers Room parity ship separately.) (`server/lib/editorial/voiceFingerprint.js`, `server/lib/editorial/checks/proseStyle.js`, `server/services/pipeline/voiceFingerprint.js`, `client/src/pages/PipelineVoiceFingerprint.jsx`)
- **[issue-2248] The chosen-voice baseline now also catches drift the whole series shares — not just per-issue outliers.** The exemplar/blended `style.voice-drift` baseline (#2247) flags an issue that stands apart from the chosen voice, but it had a residual blind spot: when *every* drafted issue sits at the same value on a metric (zero spread) yet that shared value is far from the chosen voice, there is no per-issue outlier to name — the whole corpus is uniformly off-register. The classic case is a dialogue-free series measured against a dialogue-heavy chosen voice: every issue's dialogue ratio is 0, so the per-issue z-score model stays silent even though the register is plainly wrong. The check now emits a distinct **series-wide** finding for exactly this case ("The whole series sits at 0% on dialogue ratio vs the style guide's chosen voice of 42.5% — the corpus is uniformly below the chosen voice here"), gated on a scale-free relative distance so it works across metrics with wildly different scales and never fires under the default `drafted` baseline (where the center is the mean by definition). Series-wide findings carry no issue number (it's a corpus-wide observation, not an outlier) and escalate one severity rank above the per-issue floor, and the **Voice Fingerprint** matrix view surfaces them as a banner above the table since they have no single cell to highlight. (Follow-up slice of #2179.) (`server/lib/editorial/voiceFingerprint.js`, `server/lib/editorial/checks/proseStyle.js`, `server/services/pipeline/voiceFingerprint.js`, `client/src/pages/PipelineVoiceFingerprint.jsx`)
+- **[issue-2173] The Writers Room can now auto-polish a draft in place — cutting fat, rewriting to a brief, and keeping the change only if it scored better.** A new **Polish** action on any Writers Room work runs the same adversarial quality loop the series pipeline gets, sized for a single piece: it evaluates the draft, runs a ruthless-editor cut pass, mechanically applies the safe cuts (over-explaining and redundancy), rewrites the result against an auto-built brief that spells out what to keep (the protected passage and strongest lines), then re-evaluates and keeps the revision only if it didn't score worse — otherwise it reverts. Run 1–3 cycles; the loop stops early once quality plateaus. Live per-cycle progress streams into the panel (before/after score, words trimmed, kept vs reverted), and every cycle first snapshots the body to an immutable revert point, so you can roll back to any prior state at any time — including the original baseline. It only ever runs from the explicit Polish button (no background or startup AI calls). (`server/services/writersRoom/polish.js`, `data.reference/prompts/stages/writers-room-cuts.md`, `data.reference/prompts/stages/writers-room-revise.md`, `client/src/components/writers-room/PolishPanel.jsx`)
- **[issue-2179] "Discover voice" now writes the same scene beat in five distinct registers so you can pick the series voice by ear.** Filling in a voice exemplar from a blank page is the hard part — so the series style-guide editor gains a **Discover voice** button that runs one LLM call and returns the *same* invented scene moment written five ways (spare / lyric / wry / close-psychic / cinematic). Each candidate renders side-by-side with its register label; one click files it into `voiceExemplars` ("the tuning fork") or, for a passage in the wrong register, into `voiceAntiExemplars` — both capped at 3, with the register carried as the passage note. Nothing persists until you save, exactly like the New Series "Generate with AI" concept flow, and the call only fires on your explicit click (no cold-bootstrap LLM work). The trial passages are seeded with the series' premise + existing tone/house-style so the registers vary *within* the world rather than swapping genre. Ships as a new `pipeline-series-voice-discover` stage prompt (seeded to existing installs, no migration since it's a brand-new template) behind `POST /api/pipeline/series/:id/discover-voice`. (Fourth slice of #2179 — the phase headline; Writers Room parity ships separately.) (`server/services/pipeline/seriesVoiceDiscover.js`, `server/routes/pipeline/series.js`, `server/lib/styleGuide.js`, `client/src/pages/PipelineSeries.jsx`, `data.reference/prompts/stages/pipeline-series-voice-discover.md`)
## Human Activity Tracking
diff --git a/client/src/components/writers-room/PolishPanel.jsx b/client/src/components/writers-room/PolishPanel.jsx
new file mode 100644
index 0000000000..ab80e897e5
--- /dev/null
+++ b/client/src/components/writers-room/PolishPanel.jsx
@@ -0,0 +1,262 @@
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { Sparkles, StopCircle, RotateCcw, Check, X, ArrowRight, Loader2 } from 'lucide-react';
+import toast from '../ui/Toast';
+import useMounted from '../../hooks/useMounted';
+import { useSseProgress, isTerminalSseFrame } from '../../hooks/useSseProgress';
+import { timeAgo } from '../../utils/formatters';
+import {
+ startWritersRoomPolish,
+ cancelWritersRoomPolish,
+ getWritersRoomPolishStatus,
+ listWritersRoomPolishSnapshots,
+ revertWritersRoomPolishSnapshot,
+} from '../../services/apiWritersRoom';
+
+// Human-readable phase labels for the live progress line.
+const PHASE_LABEL = {
+ evaluate: 'Evaluating…',
+ cuts: 'Cutting fat…',
+ revise: 'Revising…',
+ reevaluate: 'Re-evaluating…',
+};
+
+/**
+ * Writers Room — autonomous Polish loop control (#2173). Runs the
+ * cuts → revise → keep/revert cycle over the saved draft, streaming live
+ * per-cycle progress, and surfaces the immutable body snapshots as revert
+ * points. Explicit user trigger only (AI provider policy).
+ *
+ * Props:
+ * work — the work manifest (needs .id)
+ * dirty — true when the editor buffer has unsaved edits (polish runs on
+ * the SAVED draft, so we gate Start on a clean buffer)
+ * onBodyChanged — async () => void; called after a completed run or a revert
+ * so the editor reloads the server-mutated body
+ */
+export default function PolishPanel({ work, dirty, onBodyChanged }) {
+ const mountedRef = useMounted();
+ const [cycles, setCycles] = useState(1);
+ const [sseUrl, setSseUrl] = useState(null);
+ const [starting, setStarting] = useState(false);
+ const [snapshots, setSnapshots] = useState([]);
+ const [reverting, setReverting] = useState(null);
+
+ const { frames, latest, closed } = useSseProgress(sseUrl, { enabled: !!sseUrl });
+ const running = !!sseUrl && !closed;
+
+ const refreshSnapshots = useCallback(async () => {
+ const list = await listWritersRoomPolishSnapshots(work.id).catch(() => []);
+ if (mountedRef.current) setSnapshots(list);
+ }, [work.id, mountedRef]);
+
+ // On mount / work switch: reset stream state and load existing snapshots. If a
+ // run is already active on the server (e.g. this panel was reopened), re-attach.
+ useEffect(() => {
+ setSseUrl(null);
+ setSnapshots([]);
+ refreshSnapshots();
+ getWritersRoomPolishStatus(work.id)
+ .then((s) => { if (s?.active && mountedRef.current) setSseUrl(`/api/writers-room/works/${encodeURIComponent(work.id)}/polish/progress`); })
+ .catch(() => {});
+ }, [work.id, refreshSnapshots, mountedRef]);
+
+ // When the stream closes on a terminal frame, refresh snapshots and pull the
+ // server-mutated body back into the editor.
+ useEffect(() => {
+ if (!closed || !latest) return;
+ refreshSnapshots();
+ if (latest.type === 'complete') {
+ const kept = (latest.reports || []).filter((r) => r.decision === 'keep').length;
+ toast.success(`Polish complete — ${latest.cyclesRun} cycle${latest.cyclesRun === 1 ? '' : 's'}, ${kept} kept (score ${fmtScore(latest.finalScore)})`);
+ onBodyChanged?.();
+ } else if (latest.type === 'error') {
+ toast.error(`Polish failed: ${latest.error || 'unknown error'}`);
+ } else if (latest.type === 'canceled') {
+ toast('Polish canceled', { icon: '🛑' });
+ onBodyChanged?.();
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [closed]);
+
+ const start = async () => {
+ if (running || starting) return;
+ if (dirty) { toast.error('Save your draft first — polish runs on the saved version'); return; }
+ setStarting(true);
+ const res = await startWritersRoomPolish(work.id, { cycles }).catch((err) => {
+ if (mountedRef.current) toast.error(`Could not start polish: ${err.message}`);
+ return null;
+ });
+ if (!mountedRef.current) return;
+ setStarting(false);
+ if (!res) return;
+ if (res.alreadyRunning) toast('A polish run is already in progress', { icon: 'ℹ️' });
+ setSseUrl(res.sseUrl || `/api/writers-room/works/${encodeURIComponent(work.id)}/polish/progress`);
+ };
+
+ const cancel = async () => {
+ await cancelWritersRoomPolish(work.id).catch(() => {});
+ };
+
+ const revert = async (snapshotId) => {
+ if (running) { toast.error('Wait for the current run to finish before reverting'); return; }
+ setReverting(snapshotId);
+ const ok = await revertWritersRoomPolishSnapshot(work.id, snapshotId).catch((err) => {
+ if (mountedRef.current) toast.error(`Revert failed: ${err.message}`);
+ return null;
+ });
+ if (!mountedRef.current) return;
+ setReverting(null);
+ if (!ok) return;
+ toast.success('Reverted to snapshot');
+ onBodyChanged?.();
+ refreshSnapshots();
+ };
+
+ // Derive display state from the frame stream.
+ const baseline = useMemo(() => frames.find((f) => f.type === 'baseline'), [frames]);
+ const cycleFrames = useMemo(() => frames.filter((f) => f.type === 'cycle'), [frames]);
+ const activePhase = useMemo(() => {
+ if (!running) return null;
+ for (let i = frames.length - 1; i >= 0; i -= 1) {
+ if (frames[i].type === 'phase') return frames[i];
+ if (isTerminalSseFrame(frames[i])) return null;
+ }
+ return null;
+ }, [frames, running]);
+
+ return (
+ <div className="space-y-4 text-sm">
+ <p className="text-[12px] text-gray-400 leading-relaxed">
+ The Polish loop runs an adversarial cut pass, applies the safe cuts, then
+ rewrites against an editorial brief — keeping each revision only if it
+ scores at least as well as before. Every cycle snapshots the body first,
+ so you can always revert.
+ </p>
+
+ {/* Controls */}
+ <div className="flex items-end gap-3 flex-wrap">
+ <div>
+ <label htmlFor="polish-cycles" className="block text-[11px] text-gray-500 mb-1">Cycles</label>
+ <select
+ id="polish-cycles"
+ value={cycles}
+ disabled={running}
+ onChange={(e) => setCycles(parseInt(e.target.value, 10))}
+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm disabled:opacity-50"
+ >
+ <option value={1}>1</option>
+ <option value={2}>2</option>
+ <option value={3}>3</option>
+ </select>
+ </div>
+ {running ? (
+ <button
+ onClick={cancel}
+ className="flex items-center gap-1.5 px-3 py-1.5 rounded bg-port-error/90 text-white hover:bg-port-error text-sm"
+ >
+ <StopCircle size={14} /> Stop
+ </button>
+ ) : (
+ <button
+ onClick={start}
+ disabled={starting || dirty}
+ title={dirty ? 'Save your draft first — polish runs on the saved version' : 'Run the polish loop'}
+ className={`flex items-center gap-1.5 px-3 py-1.5 rounded text-sm ${
+ starting || dirty ? 'bg-port-bg text-gray-500' : 'bg-port-accent text-white hover:bg-port-accent/80'
+ }`}
+ >
+ <Sparkles size={14} /> {starting ? 'Starting…' : 'Polish'}
+ </button>
+ )}
+ </div>
+ {dirty && !running && (
+ <div className="text-[11px] text-port-warning">You have unsaved edits — polish runs on the saved draft.</div>
+ )}
+
+ {/* Live progress */}
+ {(running || baseline) && (
+ <div className="border border-port-border rounded p-3 space-y-2 bg-port-bg/40">
+ <div className="flex items-center justify-between text-[11px]">
+ <span className="uppercase tracking-wide text-gray-500">Progress</span>
+ {activePhase && (
+ <span className="flex items-center gap-1.5 text-port-accent">
+ <Loader2 size={11} className="animate-spin" />
+ {PHASE_LABEL[activePhase.phase] || activePhase.label || activePhase.phase}
+ {activePhase.cycle > 0 && <span className="text-gray-500">· cycle {activePhase.cycle}</span>}
+ </span>
+ )}
+ </div>
+ {baseline && (
+ <div className="text-[12px] text-gray-400">
+ Baseline score <ScoreBadge value={baseline.score} /> · {baseline.wordCount?.toLocaleString()} words
+ </div>
+ )}
+ <ul className="space-y-1.5">
+ {cycleFrames.map((f) => (
+ <li key={f.cycle} className="flex items-center gap-2 text-[12px]">
+ <span className="text-gray-500 w-14 shrink-0">Cycle {f.cycle}</span>
+ <ScoreBadge value={f.preScore} />
+ <ArrowRight size={11} className="text-gray-600 shrink-0" />
+ <ScoreBadge value={f.postScore} />
+ {f.decision === 'keep' ? (
+ <span className="flex items-center gap-1 text-port-success text-[11px]"><Check size={11} /> kept</span>
+ ) : (
+ <span className="flex items-center gap-1 text-gray-500 text-[11px]"><X size={11} /> reverted</span>
+ )}
+ <span className="text-gray-600 text-[10px] tabular-nums ml-auto">
+ {f.wordCountBefore?.toLocaleString()}→{f.wordCountAfter?.toLocaleString()}w · {f.cutsApplied} cut{f.cutsApplied === 1 ? '' : 's'}
+ </span>
+ </li>
+ ))}
+ </ul>
+ {latest?.type === 'plateau' && (
+ <div className="text-[11px] text-gray-500 italic">Converged (plateau) after cycle {latest.cycle}.</div>
+ )}
+ </div>
+ )}
+
+ {/* Snapshots / revert */}
+ <div>
+ <div className="text-[11px] uppercase tracking-wide text-gray-500 mb-1.5">
+ Snapshots {snapshots.length > 0 && <span className="text-gray-600">({snapshots.length})</span>}
+ </div>
+ {snapshots.length === 0 && (
+ <div className="text-[11px] text-gray-500 italic">No snapshots yet — run a polish cycle to create revert points.</div>
+ )}
+ <ul className="space-y-1">
+ {snapshots.map((s) => (
+ <li key={s.id} className="flex items-center gap-2 border border-port-border rounded px-2 py-1.5 text-[12px]">
+ <span className="flex-1 truncate">
+ {s.label || `Cycle ${s.cycle}`}
+ {typeof s.qualityScore === 'number' && <span className="text-gray-500"> · <ScoreBadge value={s.qualityScore} inline /></span>}
+ </span>
+ <span className="text-gray-600 text-[10px] shrink-0">{s.wordCount?.toLocaleString()}w · {timeAgo(s.createdAt, '')}</span>
+ <button
+ onClick={() => revert(s.id)}
+ disabled={running || reverting === s.id}
+ title="Revert the draft to this snapshot"
+ className="flex items-center gap-1 text-gray-400 hover:text-white disabled:opacity-40 text-[11px]"
+ >
+ <RotateCcw size={11} className={reverting === s.id ? 'animate-spin' : ''} /> Revert
+ </button>
+ </li>
+ ))}
+ </ul>
+ </div>
+ </div>
+ );
+}
+
+function fmtScore(v) {
+ return typeof v === 'number' ? (Math.round(v * 10) / 10).toString() : '—';
+}
+
+function ScoreBadge({ value, inline }) {
+ const label = fmtScore(value);
+ if (inline) return <span className="tabular-nums">{label}</span>;
+ return (
+ <span className="px-1.5 py-0.5 rounded border border-port-border bg-port-card text-[11px] tabular-nums shrink-0">
+ {label}
+ </span>
+ );
+}
diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsx
index 0ed5a5c6bb..73fb9f826d 100644
--- a/client/src/components/writers-room/WorkEditor.jsx
+++ b/client/src/components/writers-room/WorkEditor.jsx
@@ -23,6 +23,7 @@ import {
Film,
ExternalLink,
Zap,
+ Wand2,
} from 'lucide-react';
import toast from '../ui/Toast';
import ProseEditor from '../ui/ProseEditor';
@@ -35,6 +36,7 @@ import {
setWritersRoomActiveDraft,
updateWritersRoomWork,
runWritersRoomAnalysis,
+ getWritersRoomWork,
listWritersRoomCharacters,
listWritersRoomPlaces,
listWritersRoomObjects,
@@ -48,6 +50,7 @@ import LiveContinuationPanel from './LiveContinuationPanel';
import LiveRenderPanel from './LiveRenderPanel';
import CdBridgePanel from './CdBridgePanel';
import AnalysisHistory from './AnalysisHistory';
+import PolishPanel from './PolishPanel';
import ProseReader from './ProseReader';
import SyncedReview from './SyncedReview';
import ProseTokenPopover from './ProseTokenPopover';
@@ -55,7 +58,7 @@ import WritersRoomDock from './WritersRoomDock';
import useImageGenQueue from '../../hooks/useImageGenQueue';
const ANALYSIS_KIND = { SCRIPT: 'script', CHARACTERS: 'characters', PLACES: 'places', OBJECTS: 'objects', EVALUATE: 'evaluate', FORMAT: 'format' };
-const DRAWER = { VERSIONS: 'versions', HISTORY: 'history' };
+const DRAWER = { VERSIONS: 'versions', HISTORY: 'history', POLISH: 'polish' };
const MOBILE_TAB = { WRITING: 'writing', STORYBOARD: 'storyboard' };
const ANALYSIS_LABELS = {
@@ -648,6 +651,18 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
toast('Applied to editor — save to persist', { icon: '💾' });
};
+ // The Polish loop mutates the SAVED draft body on the server (cuts/revise +
+ // keep/revert). After a completed run or a manual revert, pull the fresh body
+ // back into the editor as the new saved baseline so the buffer isn't stale.
+ const reloadBodyFromServer = useCallback(async () => {
+ const fresh = await getWritersRoomWork(work.id).catch(() => null);
+ if (!fresh || !mountedRef.current) return;
+ const nextBody = fresh.activeDraftBody || '';
+ setBody(nextBody);
+ setSavedBody(nextBody);
+ onChange?.(fresh);
+ }, [work.id, onChange, mountedRef]);
+
const activeDraft = useMemo(
() => work.drafts?.find((d) => d.id === work.activeDraftVersionId),
[work.drafts, work.activeDraftVersionId]
@@ -867,6 +882,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
<MenuItem icon={MapPin} label="Refresh places" running={runningKind === ANALYSIS_KIND.PLACES} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.PLACES))} />
<MenuItem icon={Sparkles} label="Editorial pass" running={runningKind === ANALYSIS_KIND.EVALUATE} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.EVALUATE))} />
<MenuItem icon={FileSignature} label="Format pass" running={runningKind === ANALYSIS_KIND.FORMAT} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.FORMAT))} />
+ <MenuItem icon={Wand2} label="Polish (cut → revise)" onClick={closeOverflowAnd(() => setDrawer(DRAWER.POLISH))} />
<MenuItem icon={Zap} label={liveEnabled ? 'Disable live director' : 'Enable live director'} active={liveEnabled} onClick={closeOverflowAnd(toggleLiveMode)} />
</MenuSection>
<MenuSection label="Open">
@@ -1093,6 +1109,9 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
<Drawer open={drawer === DRAWER.HISTORY} onClose={() => setDrawer(null)} title="Analysis history">
<AnalysisHistory work={work} activeHash={activeHash} onApplyFormat={applyFormatText} />
</Drawer>
+ <Drawer open={drawer === DRAWER.POLISH} onClose={() => setDrawer(null)} title="Polish" size="md">
+ <PolishPanel work={work} dirty={dirty} onBodyChanged={reloadBodyFromServer} />
+ </Drawer>
</div>
);
}
diff --git a/client/src/services/apiWritersRoom.js b/client/src/services/apiWritersRoom.js
index 3ae6ae9874..b65e6591f8 100644
--- a/client/src/services/apiWritersRoom.js
+++ b/client/src/services/apiWritersRoom.js
@@ -61,6 +61,29 @@ export const runWritersRoomAnalysis = (workId, data) =>
export const getWritersRoomAnalysis = (workId, analysisId) =>
request(`/writers-room/works/${enc(workId)}/analysis/${enc(analysisId)}`);
+// Polish loop (#2173): autonomous cuts → revise → keep/revert, multi-pass.
+// startWritersRoomPolish returns { runId, alreadyRunning, sseUrl }; subscribe to
+// the sseUrl with useSseProgress for live per-cycle progress. Snapshots are the
+// immutable revert points (the keep/revert gate + the manual revert control).
+export const startWritersRoomPolish = (workId, opts = {}) =>
+ request(`/writers-room/works/${enc(workId)}/polish/start`, {
+ method: 'POST',
+ body: JSON.stringify(opts),
+ });
+export const cancelWritersRoomPolish = (workId) =>
+ request(`/writers-room/works/${enc(workId)}/polish/cancel`, { method: 'POST' });
+export const getWritersRoomPolishStatus = (workId) =>
+ request(`/writers-room/works/${enc(workId)}/polish/status`);
+export const listWritersRoomPolishSnapshots = (workId) =>
+ request(`/writers-room/works/${enc(workId)}/polish/snapshots`);
+export const getWritersRoomPolishSnapshot = (workId, snapshotId) =>
+ request(`/writers-room/works/${enc(workId)}/polish/snapshots/${enc(snapshotId)}`);
+export const revertWritersRoomPolishSnapshot = (workId, snapshotId) =>
+ request(`/writers-room/works/${enc(workId)}/polish/revert`, {
+ method: 'POST',
+ body: JSON.stringify({ snapshotId }),
+ });
+
// Live continuation (Phase 5): opt-in, debounced Creative Director feedback
// from the prose around the cursor. Returns { options, usage, budget }. The
// server gates on the per-work live-mode toggle (409) and daily budget (429);
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index 095417d2ea..9cfb5075e0 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -49,6 +49,20 @@
"returnsJson": true,
"variables": []
},
+ "writers-room-cuts": {
+ "name": "Writers Room — Adversarial Cut Pass",
+ "description": "Ruthless-editor pass over a Writers Room work body: identifies 8–12% of the prose to cut as typed passages (FAT/REDUNDANT/OVER-EXPLAIN/GENERIC/TELL/STRUCTURAL) plus fat_percentage and a protected tightest passage. Drives the Polish loop's mechanical safe-cut application (#2173).",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
+ },
+ "writers-room-revise": {
+ "name": "Writers Room — Brief-Driven Revision",
+ "description": "Rewrites a Writers Room draft against a PROBLEM / WHAT TO KEEP / WHAT TO CHANGE / VOICE RULES / TARGET brief, receiving the old draft as raw material. The revision half of the Polish loop's cut → revise → keep/revert cycle (#2173). Returns revised prose only.",
+ "model": "default",
+ "returnsJson": false,
+ "variables": []
+ },
"writers-room-continue": {
"name": "Writers Room — Live Continuation",
"description": "Live Creative Director feedback: from the prose around the cursor, propose 2–4 short optional continuation beats, prose snippets, or dialogue lines the writer can accept. Drives the opt-in live-mode side panel in the editor.",
diff --git a/data.reference/prompts/stages/writers-room-cuts.md b/data.reference/prompts/stages/writers-room-cuts.md
new file mode 100644
index 0000000000..7b9d0541a4
--- /dev/null
+++ b/data.reference/prompts/stages/writers-room-cuts.md
@@ -0,0 +1,82 @@
+# Writers Room — Adversarial Cut Pass
+
+You are a ruthless literary editor doing one job: **cutting fat**. If a sentence
+isn't earning its place, it goes. Quote exactly — never paraphrase.
+
+## Work being edited
+
+- Title: {{work.title}}
+- Kind: {{work.kind}}
+- Word count: {{work.wordCount}}
+
+Your goal: identify {{cutTargetPercent}}% of this draft that can be cut without
+losing story, character, or meaning. Aim for {{minCuts}}–{{maxCuts}} passages.
+
+## Cut types (classify each cut)
+
+- **FAT** — Purple prose, overwrought description, unnecessary flourishes that
+ don't advance story or character. Decorative language with no payoff.
+- **REDUNDANT** — The same information delivered twice (restated beats, repeated
+ emotional reactions, dialogue that echoes narration).
+- **OVER-EXPLAIN** — Spelling out what's already clear from context, action, or
+ dialogue. The reader got it; the author kept explaining.
+- **GENERIC** — Stock phrases, placeholder descriptions, anything that could
+ appear in any story ("she took a deep breath," "his eyes met hers"). No
+ specificity, no earned detail.
+- **TELL** — Emotional telling after showing, author intrusion explaining what
+ a character feels instead of letting action/dialogue carry it.
+- **STRUCTURAL** — Entire passages that don't advance plot, character, or theme.
+ Often backstory dumps or transitional filler.
+
+## What NOT to cut
+
+Do NOT cut necessary plot beats, character-defining moments, dialogue that
+reveals character or advances conflict, purposeful atmosphere, foreshadowing or
+thematic setup that pays off later, or voice-defining prose that establishes the
+narrator's personality.
+
+## Draft
+
+```
+{{draftBody}}
+```
+
+## Task
+
+Cut {{cutTargetPercent}}% of this draft. For each cut:
+
+1. Quote the EXACT passage verbatim (minimum 10 words, maximum 400 characters)
+2. Classify it as one of: FAT, REDUNDANT, OVER-EXPLAIN, GENERIC, TELL, STRUCTURAL
+3. Give a one-line reason why it should go
+
+Also identify:
+- The `fat_percentage`: your estimate of how much of this draft is cuttable fat
+- The `tightest_passage`: one passage so well-crafted it should NEVER be cut
+- The `loosest_passage`: the single worst offender — if you could only cut one thing
+- The `one_sentence_verdict`: your overall assessment of the prose's tightness
+
+If the draft is already tight with little to cut, return fewer findings and a low
+`fat_percentage`. Do not invent cuts to hit a quota.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence:
+
+```json
+{
+ "fat_percentage": 8,
+ "tightest_passage": "exact quote of the best-written passage",
+ "loosest_passage": "exact quote of the worst offender",
+ "one_sentence_verdict": "Overall assessment of prose tightness",
+ "findings": [
+ {
+ "severity": "high|medium|low",
+ "location": "e.g. second paragraph",
+ "problem": "1-2 sentences explaining why this should be cut",
+ "suggestion": "Cut this passage entirely",
+ "anchorQuote": "exact verbatim quote from the draft (10-400 chars)",
+ "cutType": "OVER-EXPLAIN|REDUNDANT|FAT|GENERIC|TELL|STRUCTURAL"
+ }
+ ]
+}
+```
diff --git a/data.reference/prompts/stages/writers-room-revise.md b/data.reference/prompts/stages/writers-room-revise.md
new file mode 100644
index 0000000000..8ba11e34da
--- /dev/null
+++ b/data.reference/prompts/stages/writers-room-revise.md
@@ -0,0 +1,37 @@
+# Writers Room — Brief-Driven Revision
+
+You are a skilled prose writer revising a draft against a specific editorial
+brief. You are given the current draft as **raw material** — keep everything the
+brief says to keep, change everything it says to change, and preserve the
+narrative voice exactly.
+
+## Work being revised
+
+- Title: {{work.title}}
+- Kind: {{work.kind}}
+
+## Revision brief
+
+{{brief}}
+
+## Current draft (raw material to revise)
+
+```
+{{draftBody}}
+```
+
+## Task
+
+Rewrite the draft to satisfy the brief. This is a **revision, not a rewrite from
+scratch**: preserve the plot, characters, structure, and the passages the brief
+protects. Tighten and sharpen — cut over-explanation and redundancy, let action
+and dialogue carry meaning, and honor the target length. Do NOT add new plot
+events, characters, or scenes the original didn't have. Do NOT pad back the fat
+the brief asked you to trim.
+
+Match the original's tense, point of view, and voice precisely.
+
+## Output contract
+
+Return ONLY the revised prose. No preamble, no commentary, no markdown fence, no
+notes about what you changed — just the finished revised draft text.
diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.md
index 201c7993bf..73313e682f 100644
--- a/server/lib/editorial/README.md
+++ b/server/lib/editorial/README.md
@@ -209,5 +209,6 @@ runner-injected `ctx.callInlineLLM` (an inline-prompt sibling of
| `letteringDensity.js` | Pure, dependency-free comic lettering-density primitives for `comic.lettering-density` (#1313): `countWords`, `panelLetteringMetrics` (per-panel balloon/caption/SFX word + balloon tally over the `comicScriptParser` output), `analyzeComicLettering` (flags balloons/panels/pages over the configurable thresholds in `DEFAULT_LETTERING_THRESHOLDS`), `overflowSeverity` (severity scaled by how far over the limit), and `sanitizeLetteringThresholds`. Mirrored to `client/src/lib/letteringDensity.js` for the comic-script stage's inline warnings — keep the two in sync. |
| `balloonAttribution.js` | Pure, dependency-free comic speech-balloon attribution primitives for `comic.balloon-attribution`: `analyzeBalloonAttribution` (flags a dialogue line whose speaker isn't shown in the panel description and carries no off-panel/broadcast cue — the case the image model mis-attributes to a visible character), `splitSpeaker`, `nameInText`, and `OFFPANEL_OK_MODIFIER` (the broadcast/off-panel/V.O./transmission modifier vocabulary — mirrors `visualStages.js` `BALLOON_STYLE_HINTS`, keep in sync). Severity scales `medium`/`low` by whether another canon character is visibly named in the panel. |
| `panelDisagreement.js` | Pure reader-panel disagreement-mining primitives for the four-persona reader panel (#2170 — CWQE Phase 6): the `PANEL_PERSONAS` / `PANEL_QUESTIONS` vocabulary, `sanitizePersonaResponse` (one persona's raw LLM answer → stable `{ persona, answers:{<qid>:{text,issues[]}}, verdict }` shape), `minePanelDisagreements` (cross-persona `consensus` ≥3-persona concern citations / `attention` some-but-not-all / `polarizing` best-vs-worst-scene splits), and `consensusToFindings` (consensus entries → `seedReviewFromFindings` finding shapes). Pure — all I/O (digest build, per-persona LLM calls, snapshot storage, review seeding) lives in `server/services/pipeline/readerPanel.js`. |
+| `cutApplier.js` | Pure, dependency-free adversarial-cut matcher/applier shared by the pipeline manuscript applier (`server/services/pipeline/applyCuts.js`) and the Writers Room polish loop (#2173): `locateCutSpan` (exact → whitespace-normalized regex → refuse ambiguous/short), `planCutsForSection` (safe-type filter + overlap guard → `{ applicable, refused }`), `applyCutsToText` (reverse-order span removal), `collapseBlankLines`, `buildWhitespaceTolerantRegex`, and `MIN_ANCHOR_CHARS`. Re-exports `CUT_TYPES`/`SAFE_CUT_TYPES` from `checkInfra.js`. Extracted from `applyCuts.js` so a freeform work body and per-issue stage sections share one matcher without coupling Writers Room to the pipeline. |
| `severityConfig.js` | Pure per-series severity-config helpers (#1616): the frozen `DEFAULT_SEVERITY_WEIGHTS` (high:12/medium:5/low:1) + `DEFAULT_BLOCKING_SEVERITIES` per autopilot gate (`BLOCKING_GATES` = arc/beatContinuity/editorial), `mergeSeverityWeights` (merge a per-series weight override over the defaults — absent/invalid keys keep the default), `resolveBlockingSet` (the per-gate blocking `Set` — `Array.isArray` first so an explicit empty `[]` "nothing blocks" is distinct from an absent gate's default), and the wire bounders `sanitizeSeverityWeights` / `sanitizeBlockingSeverities` (persisted on the series record, gated at `pipelineSeries` v9). Reuses `CHECK_SEVERITIES` from `checkRegistry.js` as the canonical enum so the wire gate can't drift. |
| `index.js` | Barrel re-export of the above. |
diff --git a/server/lib/editorial/cutApplier.js b/server/lib/editorial/cutApplier.js
new file mode 100644
index 0000000000..2c511e84b9
--- /dev/null
+++ b/server/lib/editorial/cutApplier.js
@@ -0,0 +1,150 @@
+/**
+ * Editorial — pure cut-matching + application helpers (#2168 / #2173).
+ *
+ * Autonovel's signature editing technique: the passages an editor persona
+ * marks for cutting ARE the revision plan. These pure functions locate a cut
+ * quote in a block of prose and remove it, with a multi-tier matching strategy
+ * so an LLM's whitespace reflow doesn't defeat an otherwise-valid cut.
+ *
+ * Extracted from `server/services/pipeline/applyCuts.js` so BOTH the pipeline
+ * manuscript applier (per-issue stage sections) AND the Writers Room polish
+ * loop (a single freeform work body) share one matcher — no side effects, no
+ * pipeline coupling.
+ *
+ * Matching tiers:
+ * 1. Exact string match — verbatim substring.
+ * 2. Whitespace-normalized regex — tokens joined by \s+, handles reflow.
+ * 3. Refuse ambiguous — more than 1 occurrence → manual review.
+ * 4. Refuse short — < MIN_ANCHOR_CHARS chars → too risky for mechanical removal.
+ */
+
+import { SAFE_CUT_TYPES, CUT_TYPES } from './checkInfra.js';
+
+export { SAFE_CUT_TYPES, CUT_TYPES };
+
+// Minimum anchor length to apply mechanically — shorter quotes are too risky.
+export const MIN_ANCHOR_CHARS = 25;
+
+/**
+ * Build a whitespace-tolerant regex for a quote. LLMs often reformat whitespace
+ * when quoting (collapsed indentation, added line breaks), so exact match fails
+ * even when the quote clearly targets a real span.
+ */
+export function buildWhitespaceTolerantRegex(quote) {
+ const escaped = quote.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ return new RegExp(escaped.replace(/\s+/g, '\\s+'), 'g');
+}
+
+/**
+ * Locate a cut quote in the text. Returns { start, end, method } on success,
+ * or { error: string } on failure.
+ *
+ * @param {string} text - The prose text.
+ * @param {string} quote - The exact quote to find and cut.
+ * @returns {{ start: number, end: number, method: 'exact'|'normalized' } | { error: string }}
+ */
+export function locateCutSpan(text, quote) {
+ if (!quote || typeof quote !== 'string') {
+ return { error: 'Missing or invalid quote' };
+ }
+ if (quote.length < MIN_ANCHOR_CHARS) {
+ return { error: `Quote too short (${quote.length} < ${MIN_ANCHOR_CHARS} chars)` };
+ }
+
+ // Tier 1: exact match.
+ const first = text.indexOf(quote);
+ if (first !== -1) {
+ // Check for ambiguity (multiple occurrences).
+ const second = text.indexOf(quote, first + 1);
+ if (second !== -1) {
+ return { error: 'Ambiguous: quote appears multiple times' };
+ }
+ return { start: first, end: first + quote.length, method: 'exact' };
+ }
+
+ // Tier 2: whitespace-normalized regex.
+ const re = buildWhitespaceTolerantRegex(quote);
+ const matches = [];
+ let m;
+ while ((m = re.exec(text)) !== null) {
+ matches.push({ start: m.index, end: m.index + m[0].length });
+ // Guard against zero-width matches.
+ if (m.index === re.lastIndex) re.lastIndex += 1;
+ }
+
+ if (matches.length === 0) {
+ return { error: 'Quote not found in text' };
+ }
+ if (matches.length > 1) {
+ return { error: 'Ambiguous: quote matches multiple locations (whitespace-normalized)' };
+ }
+ return { ...matches[0], method: 'normalized' };
+}
+
+/**
+ * Collapse runs of blank lines into a single blank line after cuts are applied.
+ * Cutting a paragraph can leave orphaned blank lines; this cleans them up.
+ */
+export function collapseBlankLines(text) {
+ // Replace 3+ consecutive newlines with 2 (one blank line).
+ return text.replace(/\n{3,}/g, '\n\n');
+}
+
+/**
+ * Plan cuts for a block of prose. Returns an array of applicable cuts and
+ * an array of refused cuts with reasons.
+ *
+ * @param {string} text - The prose text.
+ * @param {Array<{ anchorQuote: string, subtype: string|null }>} cuts - Cuts to apply.
+ * @param {{ safeTypesOnly?: boolean, allowTypes?: string[] }} opts
+ * @returns {{ applicable: Array<{ quote: string, span: { start: number, end: number, method: string }, cutType: string|null }>, refused: Array<{ quote: string, reason: string, cutType: string|null }> }}
+ */
+export function planCutsForSection(text, cuts, { safeTypesOnly = true, allowTypes = SAFE_CUT_TYPES } = {}) {
+ const applicable = [];
+ const refused = [];
+
+ for (const cut of cuts) {
+ const quote = typeof cut?.anchorQuote === 'string' ? cut.anchorQuote : '';
+ const cutType = CUT_TYPES.includes(cut?.subtype) ? cut.subtype : null;
+
+ // Filter by cut type if requested.
+ if (safeTypesOnly && cutType && !allowTypes.includes(cutType)) {
+ refused.push({ quote, reason: `Cut type "${cutType}" is not in the safe list`, cutType });
+ continue;
+ }
+
+ const result = locateCutSpan(text, quote);
+ if (result.error) {
+ refused.push({ quote, reason: result.error, cutType });
+ continue;
+ }
+
+ // Check for overlaps with already-planned cuts.
+ const overlaps = applicable.some(
+ (a) => result.start < a.span.end && a.span.start < result.end,
+ );
+ if (overlaps) {
+ refused.push({ quote, reason: 'Overlaps with another cut', cutType });
+ continue;
+ }
+
+ applicable.push({ quote, span: result, cutType });
+ }
+
+ return { applicable, refused };
+}
+
+/**
+ * Apply planned cuts to text, returning the modified text.
+ * Cuts are applied in reverse order (highest start index first) to preserve
+ * earlier indices as we remove spans.
+ */
+export function applyCutsToText(text, applicable) {
+ let result = text;
+ // Sort by start descending so we can slice without index shifting.
+ const sorted = [...applicable].sort((a, b) => b.span.start - a.span.start);
+ for (const cut of sorted) {
+ result = result.slice(0, cut.span.start) + result.slice(cut.span.end);
+ }
+ return collapseBlankLines(result);
+}
diff --git a/server/lib/editorial/index.js b/server/lib/editorial/index.js
index d12542ad7a..456931e9ad 100644
--- a/server/lib/editorial/index.js
+++ b/server/lib/editorial/index.js
@@ -1,6 +1,7 @@
// Barrel for server/lib/editorial/ — the extensible editorial-check registry
// (#1284). See README.md for the catalog. Re-export every public module here.
export * from './checkRegistry.js';
+export * from './cutApplier.js';
export * from './severityConfig.js';
export * from './balloonAttribution.js';
export * from './cliches.js';
diff --git a/server/lib/pipelineValidation.js b/server/lib/pipelineValidation.js
index 8d43742bc5..62be67bdaa 100644
--- a/server/lib/pipelineValidation.js
+++ b/server/lib/pipelineValidation.js
@@ -313,6 +313,22 @@ export const writersRoomAnalysisCreateSchema = z.object({
kind: z.enum(ANALYSIS_KINDS)
}).strict();
+// Start options for the autonomous Polish loop (#2173). All bounds mirror the
+// polish.js runtime clamps so a direct API call can't request an out-of-range
+// run; the runner clamps again defensively.
+export const writersRoomPolishStartSchema = z.object({
+ cycles: z.number().int().min(1).max(3).optional(),
+ plateauThreshold: z.number().min(0).max(100).optional(),
+ cutTargetPercent: z.number().int().min(5).max(20).optional(),
+ minCuts: z.number().int().min(1).max(50).optional(),
+ maxCuts: z.number().int().min(1).max(50).optional(),
+}).strict();
+
+// Manual revert of a work body to an immutable Polish snapshot (#2173).
+export const writersRoomPolishRevertSchema = z.object({
+ snapshotId: z.string().trim().regex(/^wr-snap-[0-9a-f-]+$/i, 'Invalid snapshot id'),
+}).strict();
+
// Character profile fields are all optional on update so the UI can PATCH
// one field at a time. `name` accepts trimmed non-empty when present; all
// other text fields tolerate '' so the writer can deliberately blank a field
diff --git a/server/routes/writersRoom.js b/server/routes/writersRoom.js
index 81e77dcf3d..7ac83c34a8 100644
--- a/server/routes/writersRoom.js
+++ b/server/routes/writersRoom.js
@@ -16,6 +16,8 @@ import {
writersRoomExerciseCreateSchema,
writersRoomExerciseFinishSchema,
writersRoomAnalysisCreateSchema,
+ writersRoomPolishStartSchema,
+ writersRoomPolishRevertSchema,
writersRoomLiveSuggestSchema,
writersRoomLiveRenderPreviewSchema,
writersRoomCdBridgeSuggestSchema,
@@ -36,6 +38,10 @@ import {
import {
runAnalysis, listAnalyses, getAnalysis, persistSceneImage,
} from '../services/writersRoom/evaluator.js';
+import {
+ startPolish, attachClient as attachPolishClient, cancelPolish, isPolishActive,
+ listSnapshots, getSnapshot, revertToSnapshot,
+} from '../services/writersRoom/polish.js';
import { getSyncedReview } from '../services/writersRoom/syncedReview.js';
import {
suggestContinuation, reserveRenderPreview, suggestCdBridge, sendToCreativeDirector,
@@ -194,6 +200,50 @@ router.get('/works/:id/analysis/:analysisId', asyncHandler(async (req, res) => {
res.json(await getAnalysis(req.params.id, req.params.analysisId));
}));
+// ---------- polish loop (#2173): cuts → revise → keep/revert, multi-pass ----------
+
+// Start an autonomous Polish run. Explicit user action (satisfies the AI
+// provider policy — no boot/background invocation). Pre-validate the work has a
+// non-empty body so an empty draft gets a clean 400 rather than an SSE error
+// frame, then hand off to the streaming runner and return the SSE URL.
+router.post('/works/:id/polish/start', asyncHandler(async (req, res) => {
+ const data = validateRequest(writersRoomPolishStartSchema, req.body || {});
+ const { body } = await getWorkWithBody(req.params.id);
+ if (!body || !body.trim()) {
+ throw new ServerError('Cannot polish an empty draft — write some prose first', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ const result = startPolish(req.params.id, data);
+ res.json({ ...result, sseUrl: `/api/writers-room/works/${req.params.id}/polish/progress` });
+}));
+
+router.get('/works/:id/polish/progress', (req, res) => {
+ const attached = attachPolishClient(req.params.id, res);
+ if (!attached) {
+ throw new ServerError('No active polish run for this work', { status: 404 });
+ }
+});
+
+router.post('/works/:id/polish/cancel', asyncHandler(async (req, res) => {
+ res.json({ canceled: cancelPolish(req.params.id) });
+}));
+
+router.get('/works/:id/polish/status', asyncHandler(async (req, res) => {
+ res.json({ active: isPolishActive(req.params.id) });
+}));
+
+router.get('/works/:id/polish/snapshots', asyncHandler(async (req, res) => {
+ res.json(await listSnapshots(req.params.id));
+}));
+
+router.get('/works/:id/polish/snapshots/:snapshotId', asyncHandler(async (req, res) => {
+ res.json(await getSnapshot(req.params.id, req.params.snapshotId));
+}));
+
+router.post('/works/:id/polish/revert', asyncHandler(async (req, res) => {
+ const { snapshotId } = validateRequest(writersRoomPolishRevertSchema, req.body || {});
+ res.json(await revertToSnapshot(req.params.id, snapshotId));
+}));
+
// ---------- live continuation (Phase 5: opt-in Creative Director feedback) ----------
// Throttled, opt-in live suggestions from the cursor context. The service
diff --git a/server/services/pipeline/applyCuts.js b/server/services/pipeline/applyCuts.js
index 22fc58a73a..59cf265695 100644
--- a/server/services/pipeline/applyCuts.js
+++ b/server/services/pipeline/applyCuts.js
@@ -20,139 +20,31 @@ import { randomUUID } from 'crypto';
import { updateStagesWithLatest } from './issues.js';
import { collectManuscriptSections } from './arcPlanner.js';
import { SAFE_CUT_TYPES, CUT_TYPES } from '../../lib/editorial/checkRegistry.js';
-
-export { SAFE_CUT_TYPES, CUT_TYPES };
-
-// Minimum anchor length to apply mechanically — shorter quotes are too risky.
-export const MIN_ANCHOR_CHARS = 25;
+import {
+ MIN_ANCHOR_CHARS,
+ locateCutSpan,
+ collapseBlankLines,
+ planCutsForSection,
+ applyCutsToText,
+} from '../../lib/editorial/cutApplier.js';
+
+// The pure cut-matching helpers now live in server/lib/editorial/cutApplier.js
+// so the Writers Room polish loop (#2173) can reuse them without pulling in the
+// pipeline. Re-export them here to keep this module's public surface stable for
+// existing importers (manuscript route, applyCuts.test.js).
+export {
+ SAFE_CUT_TYPES,
+ CUT_TYPES,
+ MIN_ANCHOR_CHARS,
+ locateCutSpan,
+ collapseBlankLines,
+ planCutsForSection,
+ applyCutsToText,
+};
// Output after input: drafted text wins over seed.
const stageTextOf = (stage) => (stage?.output?.trim() || stage?.input?.trim() || '');
-/**
- * Build a whitespace-tolerant regex for a quote. LLMs often reformat whitespace
- * when quoting (collapsed indentation, added line breaks), so exact match fails
- * even when the quote clearly targets a real span.
- */
-function buildWhitespaceTolerantRegex(quote) {
- const escaped = quote.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
- return new RegExp(escaped.replace(/\s+/g, '\\s+'), 'g');
-}
-
-/**
- * Locate a cut quote in the text. Returns { start, end, method } on success,
- * or { error: string } on failure.
- *
- * @param {string} text - The manuscript section text.
- * @param {string} quote - The exact quote to find and cut.
- * @returns {{ start: number, end: number, method: 'exact'|'normalized' } | { error: string }}
- */
-export function locateCutSpan(text, quote) {
- if (!quote || typeof quote !== 'string') {
- return { error: 'Missing or invalid quote' };
- }
- if (quote.length < MIN_ANCHOR_CHARS) {
- return { error: `Quote too short (${quote.length} < ${MIN_ANCHOR_CHARS} chars)` };
- }
-
- // Tier 1: exact match.
- const first = text.indexOf(quote);
- if (first !== -1) {
- // Check for ambiguity (multiple occurrences).
- const second = text.indexOf(quote, first + 1);
- if (second !== -1) {
- return { error: 'Ambiguous: quote appears multiple times' };
- }
- return { start: first, end: first + quote.length, method: 'exact' };
- }
-
- // Tier 2: whitespace-normalized regex.
- const re = buildWhitespaceTolerantRegex(quote);
- const matches = [];
- let m;
- while ((m = re.exec(text)) !== null) {
- matches.push({ start: m.index, end: m.index + m[0].length });
- // Guard against zero-width matches.
- if (m.index === re.lastIndex) re.lastIndex += 1;
- }
-
- if (matches.length === 0) {
- return { error: 'Quote not found in text' };
- }
- if (matches.length > 1) {
- return { error: 'Ambiguous: quote matches multiple locations (whitespace-normalized)' };
- }
- return { ...matches[0], method: 'normalized' };
-}
-
-/**
- * Collapse runs of blank lines into a single blank line after cuts are applied.
- * Cutting a paragraph can leave orphaned blank lines; this cleans them up.
- */
-export function collapseBlankLines(text) {
- // Replace 3+ consecutive newlines with 2 (one blank line).
- return text.replace(/\n{3,}/g, '\n\n');
-}
-
-/**
- * Plan cuts for a single section. Returns an array of applicable cuts and
- * an array of refused cuts with reasons.
- *
- * @param {string} text - The section's manuscript text.
- * @param {Array<{ anchorQuote: string, subtype: string|null }>} cuts - Cuts to apply.
- * @param {{ safeTypesOnly?: boolean, allowTypes?: string[] }} opts
- * @returns {{ applicable: Array<{ quote: string, span: { start: number, end: number, method: string }, cutType: string|null }>, refused: Array<{ quote: string, reason: string, cutType: string|null }> }}
- */
-export function planCutsForSection(text, cuts, { safeTypesOnly = true, allowTypes = SAFE_CUT_TYPES } = {}) {
- const applicable = [];
- const refused = [];
-
- for (const cut of cuts) {
- const quote = typeof cut?.anchorQuote === 'string' ? cut.anchorQuote : '';
- const cutType = CUT_TYPES.includes(cut?.subtype) ? cut.subtype : null;
-
- // Filter by cut type if requested.
- if (safeTypesOnly && cutType && !allowTypes.includes(cutType)) {
- refused.push({ quote, reason: `Cut type "${cutType}" is not in the safe list`, cutType });
- continue;
- }
-
- const result = locateCutSpan(text, quote);
- if (result.error) {
- refused.push({ quote, reason: result.error, cutType });
- continue;
- }
-
- // Check for overlaps with already-planned cuts.
- const overlaps = applicable.some(
- (a) => result.start < a.span.end && a.span.start < result.end,
- );
- if (overlaps) {
- refused.push({ quote, reason: 'Overlaps with another cut', cutType });
- continue;
- }
-
- applicable.push({ quote, span: result, cutType });
- }
-
- return { applicable, refused };
-}
-
-/**
- * Apply planned cuts to text, returning the modified text.
- * Cuts are applied in reverse order (highest start index first) to preserve
- * earlier indices as we remove spans.
- */
-export function applyCutsToText(text, applicable) {
- let result = text;
- // Sort by start descending so we can slice without index shifting.
- const sorted = [...applicable].sort((a, b) => b.span.start - a.span.start);
- for (const cut of sorted) {
- result = result.slice(0, cut.span.start) + result.slice(cut.span.end);
- }
- return collapseBlankLines(result);
-}
-
/**
* Dry-run preview of cuts. Returns the impact without applying.
*
diff --git a/server/services/writersRoom/evaluator.js b/server/services/writersRoom/evaluator.js
index 1f449cadda..cfbb32b53a 100644
--- a/server/services/writersRoom/evaluator.js
+++ b/server/services/writersRoom/evaluator.js
@@ -14,6 +14,7 @@ import { extractBible } from '../../lib/bibleExtractor.js';
import { extractScenes, SOURCE_KIND } from '../../lib/sceneExtractor.js';
import { BIBLE_KIND } from '../../lib/storyBible.js';
import { ANALYSIS_KINDS } from '../../lib/writersRoomPresets.js';
+import { CUT_TYPES } from '../../lib/editorial/cutApplier.js';
import { getWorkWithBody, ensureWorkMediaCollection } from './local.js';
import { addItem as addCollectionItem, ERR_DUPLICATE } from '../mediaCollections.js';
import { listCharacters, mergeExtractedCharacters } from './characters.js';
@@ -23,13 +24,20 @@ import { nowIso, badRequest, notFound, assertValidWorkId } from './_shared.js';
export { ANALYSIS_KINDS };
-const KIND_META = {
+// `cuts` and `revise` are the two Polish-loop pass kinds (#2173). They are NOT
+// in ANALYSIS_KINDS — they never run as standalone user analyses (no snapshot
+// row in the analysis history); the multi-pass Polish runner (polish.js) drives
+// them against the work body directly. They live here so the stage-name +
+// returnsJson mapping stays single-sourced.
+export const KIND_META = {
evaluate: { stage: 'writers-room-evaluate', returnsJson: true },
format: { stage: 'writers-room-format', returnsJson: false },
script: { stage: 'writers-room-script', returnsJson: true },
characters: { stage: 'writers-room-characters', returnsJson: true },
places: { stage: 'writers-room-places', returnsJson: true },
objects: { stage: 'writers-room-objects', returnsJson: true },
+ cuts: { stage: 'writers-room-cuts', returnsJson: true },
+ revise: { stage: 'writers-room-revise', returnsJson: false },
};
// Analysis id == kind. Each work keeps at most one snapshot per kind on disk
@@ -58,13 +66,17 @@ function extractJson(text) {
return JSON.parse(str);
}
-const SHAPERS = {
- format: (raw) => {
- let text = raw.trim();
- const fence = text.match(/^```(?:markdown|md|text)?\s*([\s\S]*?)```$/);
- if (fence) text = fence[1].trim();
- return { formattedBody: text };
- },
+// Strip a leading/trailing markdown code fence from a prose response — some
+// providers wrap returned prose in a ```markdown … ``` block.
+function stripProseFence(raw) {
+ let text = String(raw ?? '').trim();
+ const fence = text.match(/^```(?:markdown|md|text)?\s*([\s\S]*?)```$/);
+ if (fence) text = fence[1].trim();
+ return text;
+}
+
+export const SHAPERS = {
+ format: (raw) => ({ formattedBody: stripProseFence(raw) }),
evaluate: (raw) => {
const parsed = extractJson(raw);
return {
@@ -76,6 +88,33 @@ const SHAPERS = {
suggestions: Array.isArray(parsed.suggestions) ? parsed.suggestions.filter((s) => s && typeof s === 'object') : [],
};
},
+ // Adversarial-cut pass (#2173). Shapes the ruthless-editor JSON into typed cut
+ // findings the mechanical applier can consume (anchorQuote + cutType), plus the
+ // health signals (fat %, protected passage). Findings without a usable anchor
+ // quote or a recognized cut type are dropped — the applier can't act on them.
+ cuts: (raw) => {
+ const parsed = extractJson(raw);
+ const rawFindings = Array.isArray(parsed.findings) ? parsed.findings : [];
+ return {
+ fatPercentage: typeof parsed.fat_percentage === 'number' ? parsed.fat_percentage : null,
+ tightestPassage: typeof parsed.tightest_passage === 'string' ? parsed.tightest_passage : null,
+ loosestPassage: typeof parsed.loosest_passage === 'string' ? parsed.loosest_passage : null,
+ oneSentenceVerdict: typeof parsed.one_sentence_verdict === 'string' ? parsed.one_sentence_verdict : null,
+ findings: rawFindings
+ .filter((f) => f && typeof f === 'object')
+ .map((f) => ({
+ severity: typeof f.severity === 'string' ? f.severity : 'low',
+ location: typeof f.location === 'string' ? f.location : null,
+ problem: typeof f.problem === 'string' ? f.problem : '',
+ suggestion: typeof f.suggestion === 'string' ? f.suggestion : '',
+ anchorQuote: typeof f.anchorQuote === 'string' ? f.anchorQuote : '',
+ cutType: CUT_TYPES.includes(f.cutType) ? f.cutType : null,
+ }))
+ .filter((f) => f.anchorQuote && f.cutType),
+ };
+ },
+ // Brief-driven rewrite (#2173) returns prose only (returnsJson:false).
+ revise: (raw) => ({ revisedBody: stripProseFence(raw) }),
// characters / places / objects route through `extractBible`,
// and `script` routes through `extractScenes` — no per-kind shaper here.
};
@@ -263,6 +302,36 @@ export async function recoverStuckAnalyses() {
if (recovered > 0) console.log(`📝 wr: recovered ${recovered} stuck analysis snapshot(s) on boot`);
}
+// ---------- shared pass runner (used by runAnalysis + the Polish loop) ----------
+
+/**
+ * Run one LLM prose pass for a KIND_META kind against an already-loaded work
+ * body, returning the shaped result plus provider/model. Thin wrapper over
+ * runStagedLLM + the per-kind SHAPER so the Polish loop (polish.js) drives the
+ * `evaluate` / `cuts` / `revise` passes through the same single code path as
+ * the standalone analysis runner — no duplicated plumbing.
+ *
+ * Only the template-driven kinds (evaluate/format/cuts/revise) route here; the
+ * bible/script kinds have their own extraction paths in runAnalysis.
+ *
+ * @param {string} kind - A KIND_META key with a template stage.
+ * @param {object} variables - Extra prompt variables (work, draftBody, brief, …).
+ * @param {{ source?: string }} [opts]
+ * @returns {Promise<{ result: any, content: string, providerId: string, model: string }>}
+ */
+export async function runProsePass(kind, variables, { source } = {}) {
+ const meta = KIND_META[kind];
+ if (!meta) throw badRequest(`Unknown prose pass kind: ${kind}`);
+ const { stage, returnsJson } = meta;
+ const { content, model, providerId } = await runStagedLLM(
+ stage,
+ { ...variables, returnsJson },
+ { source: source || `writers-room-${kind}` },
+ );
+ const shaper = SHAPERS[kind];
+ return { result: shaper ? shaper(content) : content, content, providerId, model };
+}
+
// ---------- run ----------
export async function runAnalysis(workId, { kind } = {}) {
diff --git a/server/services/writersRoom/evaluator.test.js b/server/services/writersRoom/evaluator.test.js
new file mode 100644
index 0000000000..8e27814852
--- /dev/null
+++ b/server/services/writersRoom/evaluator.test.js
@@ -0,0 +1,66 @@
+import { describe, it, expect, vi } from 'vitest';
+
+// evaluator.js pulls in the whole extraction/LLM graph at module top. Stub the
+// heavy siblings so this unit test can import it cheaply — it only exercises the
+// pure KIND_META map + the `cuts`/`revise` SHAPERS, which depend on nothing but
+// stripCodeFences (aiProvider) and CUT_TYPES (cutApplier, real).
+vi.mock('../../lib/aiProvider.js', () => ({ stripCodeFences: (s) => String(s ?? '') }));
+vi.mock('../../lib/stageRunner.js', () => ({ runStagedLLM: vi.fn() }));
+vi.mock('../../lib/bibleExtractor.js', () => ({ extractBible: vi.fn() }));
+vi.mock('../../lib/sceneExtractor.js', () => ({ extractScenes: vi.fn(), SOURCE_KIND: { PROSE: 'prose' } }));
+vi.mock('../../lib/storyBible.js', () => ({ BIBLE_KIND: { CHARACTER: 'character', PLACE: 'place', OBJECT: 'object' } }));
+vi.mock('./local.js', () => ({ getWorkWithBody: vi.fn(), ensureWorkMediaCollection: vi.fn() }));
+vi.mock('../mediaCollections.js', () => ({ addItem: vi.fn(), ERR_DUPLICATE: 'DUP' }));
+vi.mock('./characters.js', () => ({ listCharacters: vi.fn(), mergeExtractedCharacters: vi.fn() }));
+vi.mock('./places.js', () => ({ listPlaces: vi.fn(), mergeExtractedPlaces: vi.fn() }));
+vi.mock('./objects.js', () => ({ listObjects: vi.fn(), mergeExtractedObjects: vi.fn() }));
+
+const { KIND_META, SHAPERS } = await import('./evaluator.js');
+
+describe('KIND_META', () => {
+ it('registers the cuts + revise Polish pass kinds with stage + returnsJson', () => {
+ expect(KIND_META.cuts).toEqual({ stage: 'writers-room-cuts', returnsJson: true });
+ expect(KIND_META.revise).toEqual({ stage: 'writers-room-revise', returnsJson: false });
+ });
+
+ it('still carries the standalone analysis kinds', () => {
+ for (const k of ['evaluate', 'format', 'script', 'characters', 'places', 'objects']) {
+ expect(KIND_META[k]).toHaveProperty('stage');
+ expect(typeof KIND_META[k].returnsJson).toBe('boolean');
+ }
+ });
+});
+
+describe('SHAPERS.cuts', () => {
+ it('shapes typed cut findings and drops ones without an anchor quote or valid type', () => {
+ const raw = JSON.stringify({
+ fat_percentage: 9,
+ tightest_passage: 'the best line',
+ loosest_passage: 'the worst line',
+ one_sentence_verdict: 'A touch loose.',
+ findings: [
+ { severity: 'high', anchorQuote: 'a redundant restatement here', cutType: 'REDUNDANT', problem: 'dup' },
+ { anchorQuote: '', cutType: 'FAT' }, // no anchor → dropped
+ { anchorQuote: 'unknown type quote', cutType: 'NONSENSE' }, // bad type → dropped
+ ],
+ });
+ const shaped = SHAPERS.cuts(raw);
+ expect(shaped.fatPercentage).toBe(9);
+ expect(shaped.tightestPassage).toBe('the best line');
+ expect(shaped.findings).toHaveLength(1);
+ expect(shaped.findings[0]).toMatchObject({ anchorQuote: 'a redundant restatement here', cutType: 'REDUNDANT' });
+ });
+
+ it('tolerates a missing findings array', () => {
+ const shaped = SHAPERS.cuts(JSON.stringify({ fat_percentage: 0 }));
+ expect(shaped.findings).toEqual([]);
+ expect(shaped.fatPercentage).toBe(0);
+ });
+});
+
+describe('SHAPERS.revise', () => {
+ it('returns the prose body, stripping a markdown fence', () => {
+ expect(SHAPERS.revise(' Just prose. ')).toEqual({ revisedBody: 'Just prose.' });
+ expect(SHAPERS.revise('```markdown\nFenced prose.\n```')).toEqual({ revisedBody: 'Fenced prose.' });
+ });
+});
diff --git a/server/services/writersRoom/polish.js b/server/services/writersRoom/polish.js
new file mode 100644
index 0000000000..6158f7c530
--- /dev/null
+++ b/server/services/writersRoom/polish.js
@@ -0,0 +1,372 @@
+/**
+ * Writers Room — autonomous "Polish" loop (CWQE Phase 9, #2173).
+ *
+ * Brings the pipeline's adversarial quality loop to a single freeform Writers
+ * Room work: evaluate → cuts → apply safe cuts → revise → re-evaluate →
+ * keep/revert, for a configurable number of cycles with plateau-stop. Composes
+ * the #2168 cut applier (via the shared server/lib/editorial/cutApplier.js) and
+ * the `evaluate`/`cuts`/`revise` prose passes (evaluator.js `KIND_META`).
+ *
+ * AI-provider policy: the loop only runs from the explicit user-triggered
+ * `POST /works/:id/polish/start` action — never from boot or a background job.
+ *
+ * Revertibility: every cycle writes an IMMUTABLE body snapshot under
+ * data/writers-room/works/<id>/snapshots/ before mutating the active draft, so
+ * the keep/revert gate (and a manual UI revert) can always restore prior prose.
+ */
+
+import { join } from 'path';
+import { randomUUID } from 'crypto';
+import { readFile, readdir } from 'fs/promises';
+import { PATHS, atomicWrite, ensureDir, safeJSONParse } from '../../lib/fileUtils.js';
+import { createSseRunner } from '../../lib/sseUtils.js';
+import { computeSlopPenalty } from '../../lib/editorial/slopScore.js';
+import { planCutsForSection, applyCutsToText, SAFE_CUT_TYPES } from '../../lib/editorial/cutApplier.js';
+import { runProsePass } from './evaluator.js';
+import { getWorkWithBody, saveDraftBody, countWords } from './local.js';
+import { nowIso, badRequest, notFound, assertValidWorkId, wrWorkDir } from './_shared.js';
+
+// ---------- tunables ----------
+
+export const DEFAULT_CYCLES = 1;
+export const MAX_CYCLES = 3;
+// Stop early once a cycle's kept-quality gain drops below this (autonovel's
+// Δ-plateau convergence, scaled for a single work rather than a whole series).
+export const DEFAULT_PLATEAU_THRESHOLD = 0.5;
+export const DEFAULT_CUT_TARGET_PERCENT = 10;
+export const DEFAULT_MIN_CUTS = 8;
+export const DEFAULT_MAX_CUTS = 20;
+
+const SNAP_ID_RE = /^wr-snap-[0-9a-f-]+$/i;
+
+// ---------- pure scoring / decision helpers (unit-tested) ----------
+
+// Weighted issue penalty from an `evaluate` pass, mapped to a 0–100 score
+// (higher = cleaner). Severities follow the evaluate prompt's contract.
+export const SEVERITY_WEIGHT = Object.freeze({ major: 3, moderate: 2, minor: 1 });
+
+export function scoreEvaluation(result) {
+ const issues = Array.isArray(result?.issues) ? result.issues : [];
+ const penalty = issues.reduce((sum, i) => sum + (SEVERITY_WEIGHT[i?.severity] ?? 1), 0);
+ return Math.max(0, 100 - penalty);
+}
+
+/**
+ * Composite quality score: the LLM evaluate score minus the free deterministic
+ * "AI slop" penalty (autonovel's dual immune system — the mechanical layer
+ * catches what the judge normalizes away). Higher is better.
+ */
+export function computeQualityScore(evaluateResult, body) {
+ return Math.round((scoreEvaluation(evaluateResult) - computeSlopPenalty(body || '')) * 100) / 100;
+}
+
+// Keep the revision only if it did not regress the composite score, else revert
+// the cycle's snapshot. Ties keep the new draft (the loop made forward progress
+// on cuts even at an equal score).
+export function decideKeepRevert(preScore, postScore) {
+ return postScore >= preScore ? 'keep' : 'revert';
+}
+
+// Converged when the kept-quality gain for this cycle is below the plateau
+// threshold — a reverted cycle (gain 0) always plateaus.
+export function shouldStopPlateau(preScore, keptScore, threshold = DEFAULT_PLATEAU_THRESHOLD) {
+ return Math.abs(keptScore - preScore) < threshold;
+}
+
+// Map shaped `cuts` findings to the applier's `{ anchorQuote, subtype }` shape.
+export function mapFindingsToCuts(findings) {
+ return (Array.isArray(findings) ? findings : [])
+ .filter((f) => f && typeof f.anchorQuote === 'string' && f.anchorQuote.trim() && f.cutType)
+ .map((f) => ({ anchorQuote: f.anchorQuote, subtype: f.cutType }));
+}
+
+/**
+ * Build the revision brief the `revise` pass rewrites against — PROBLEM /
+ * WHAT TO KEEP / WHAT TO CHANGE / VOICE RULES / TARGET, composed from the
+ * evaluate result and the cut pass. The WHAT TO KEEP section (strengths +
+ * protected passage) is what stops the rewrite from destroying good material.
+ * Pure — no I/O — so the composition is unit-testable.
+ */
+export function buildRevisionBrief({ evaluate = {}, cuts = {}, wordCount = 0 } = {}) {
+ const lines = [];
+ const issues = Array.isArray(evaluate.issues) ? evaluate.issues : [];
+ const strengths = Array.isArray(evaluate.strengths) ? evaluate.strengths : [];
+ const suggestions = Array.isArray(evaluate.suggestions) ? evaluate.suggestions : [];
+ const themes = Array.isArray(evaluate.themes) ? evaluate.themes : [];
+ // Cut findings NOT auto-applied (non-safe types) still describe fat to trim
+ // by hand during the rewrite.
+ const residualCuts = (Array.isArray(cuts.findings) ? cuts.findings : [])
+ .filter((f) => f.cutType && !SAFE_CUT_TYPES.includes(f.cutType));
+
+ lines.push('## PROBLEM');
+ if (issues.length === 0 && residualCuts.length === 0) {
+ lines.push('- No blocking issues flagged — tighten and sharpen without changing the story.');
+ }
+ for (const i of issues.slice(0, 8)) {
+ lines.push(`- (${i.severity || 'note'}/${i.category || 'general'}) ${i.note || ''}`.trimEnd());
+ }
+ for (const c of residualCuts.slice(0, 8)) {
+ lines.push(`- (cut/${c.cutType}) ${c.problem || 'Trim this passage.'} — "${(c.anchorQuote || '').slice(0, 120)}"`);
+ }
+ if (cuts.loosestPassage) {
+ lines.push(`- Worst offender to tighten: "${String(cuts.loosestPassage).slice(0, 160)}"`);
+ }
+
+ lines.push('', '## WHAT TO KEEP');
+ if (cuts.tightestPassage) {
+ lines.push(`- Protected passage — do NOT cut or weaken: "${String(cuts.tightestPassage).slice(0, 200)}"`);
+ }
+ for (const s of strengths.slice(0, 6)) lines.push(`- ${s}`);
+ if (strengths.length === 0 && !cuts.tightestPassage) {
+ lines.push('- Preserve the strongest imagery, voice, and any dialogue that reveals character.');
+ }
+
+ lines.push('', '## WHAT TO CHANGE');
+ if (suggestions.length === 0) {
+ lines.push('- Cut over-explanation and redundancy; let action and dialogue carry the meaning.');
+ }
+ for (const s of suggestions.slice(0, 8)) {
+ lines.push(`- ${s.target ? `[${s.target}] ` : ''}${s.recommendation || ''}`.trimEnd());
+ }
+
+ lines.push('', '## VOICE RULES');
+ if (evaluate.logline) lines.push(`- Keep the logline true: ${evaluate.logline}`);
+ if (themes.length) lines.push(`- Preserve the established themes: ${themes.join(', ')}`);
+ lines.push('- Match the existing narrative voice, tense, and POV exactly.');
+
+ lines.push('', '## TARGET');
+ lines.push(`- Aim for roughly ${wordCount} words — tightened. Do NOT pad back the fat that was cut.`);
+
+ return lines.join('\n');
+}
+
+// ---------- snapshot storage ----------
+
+const snapshotsDir = (workId) => {
+ assertValidWorkId(workId);
+ return join(wrWorkDir(workId), 'snapshots');
+};
+const snapshotPath = (workId, id) => join(snapshotsDir(workId), `${id}.json`);
+
+function buildSnapshot({ workId, cycle, phase, label, body, evaluate = null, qualityScore = null }) {
+ return {
+ id: `wr-snap-${randomUUID()}`,
+ workId,
+ cycle,
+ phase: phase || null,
+ label: label || null,
+ wordCount: countWords(body || ''),
+ qualityScore,
+ // Keep a compact echo of the evaluate result so the history UI can show the
+ // score breakdown without re-running a pass.
+ evaluate: evaluate ? { issues: evaluate.issues || [], strengths: evaluate.strengths || [] } : null,
+ body: String(body ?? ''),
+ createdAt: nowIso(),
+ };
+}
+
+async function saveSnapshot(workId, snap) {
+ await ensureDir(snapshotsDir(workId));
+ await atomicWrite(snapshotPath(workId, snap.id), snap);
+ return snap;
+}
+
+const summarizeSnapshot = (s) => ({
+ id: s.id,
+ workId: s.workId,
+ cycle: s.cycle,
+ phase: s.phase,
+ label: s.label,
+ wordCount: s.wordCount,
+ qualityScore: s.qualityScore,
+ createdAt: s.createdAt,
+});
+
+export async function listSnapshots(workId) {
+ const dir = snapshotsDir(workId);
+ await ensureDir(dir);
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
+ const ids = entries
+ .filter((e) => e.isFile() && e.name.endsWith('.json'))
+ .map((e) => e.name.replace(/\.json$/, ''))
+ .filter((id) => SNAP_ID_RE.test(id));
+ const loaded = await Promise.all(ids.map((id) => loadSnapshot(workId, id)));
+ return loaded
+ .filter(Boolean)
+ .map(summarizeSnapshot)
+ .sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
+}
+
+async function loadSnapshot(workId, id) {
+ if (!SNAP_ID_RE.test(id)) return null;
+ const content = await readFile(snapshotPath(workId, id), 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (content === null) return null;
+ return safeJSONParse(content, null, { allowArray: false, logError: true, context: snapshotPath(workId, id) });
+}
+
+export async function getSnapshot(workId, id) {
+ if (!SNAP_ID_RE.test(id)) throw badRequest('Invalid snapshot id');
+ const snap = await loadSnapshot(workId, id);
+ if (!snap) throw notFound('Snapshot');
+ return snap;
+}
+
+/**
+ * Restore a body snapshot into the active draft. Used by the keep/revert gate
+ * AND the manual UI revert control. Returns the updated manifest + body.
+ */
+export async function revertToSnapshot(workId, snapshotId) {
+ const snap = await getSnapshot(workId, snapshotId);
+ const { manifest, body } = await saveDraftBody(workId, snap.body);
+ console.log(`↩️ wr polish: reverted work ${workId.slice(0, 14)}… to snapshot ${snapshotId.slice(0, 14)}… (${countWords(body)} words)`);
+ return { manifest, body, snapshot: summarizeSnapshot(snap) };
+}
+
+// ---------- run options ----------
+
+export function resolvePolishOptions(opts = {}) {
+ const cyclesRaw = Number.isInteger(opts.cycles) ? opts.cycles : DEFAULT_CYCLES;
+ return {
+ cycles: Math.max(1, Math.min(MAX_CYCLES, cyclesRaw)),
+ plateauThreshold: typeof opts.plateauThreshold === 'number' && opts.plateauThreshold >= 0
+ ? opts.plateauThreshold
+ : DEFAULT_PLATEAU_THRESHOLD,
+ cutTargetPercent: Number.isInteger(opts.cutTargetPercent) ? opts.cutTargetPercent : DEFAULT_CUT_TARGET_PERCENT,
+ minCuts: Number.isInteger(opts.minCuts) ? opts.minCuts : DEFAULT_MIN_CUTS,
+ maxCuts: Number.isInteger(opts.maxCuts) ? opts.maxCuts : DEFAULT_MAX_CUTS,
+ };
+}
+
+// ---------- SSE runner ----------
+
+const polishRunner = createSseRunner({ logLabel: 'wr polish' });
+
+export const isPolishActive = (workId) => polishRunner.isActive(workId);
+export const attachClient = (workId, res) => polishRunner.attachClient(workId, res);
+export const cancelPolish = (workId) => polishRunner.cancel(workId);
+export const __testing = { runs: polishRunner.runs };
+
+const workContext = (manifest, body) => ({
+ id: manifest.id,
+ title: manifest.title,
+ kind: manifest.kind,
+ status: manifest.status,
+ wordCount: countWords(body || ''),
+});
+
+/**
+ * Start (or coalesce onto an in-flight) Polish run for a work. Returns the
+ * createSseRunner `{ runId, alreadyRunning }`. The route pre-validates the work
+ * exists and has a non-empty body before calling this so an empty draft gets a
+ * clean 400 rather than an SSE error frame.
+ */
+export function startPolish(workId, opts = {}) {
+ const cfg = resolvePolishOptions(opts);
+ return polishRunner.start(workId, async ({ runId, signal, broadcast }) => {
+ const isCanceled = () => signal.aborted;
+ const emitCanceled = () => broadcast({ type: 'canceled', runId, canceledAt: nowIso() });
+
+ broadcast({ type: 'start', runId, cycles: cfg.cycles, at: nowIso() });
+
+ const loaded = await getWorkWithBody(workId);
+ let body = loaded.body || '';
+ const ctx = () => workContext(loaded.manifest, body);
+
+ // Baseline evaluation + snapshot.
+ broadcast({ type: 'phase', cycle: 0, phase: 'evaluate', label: 'Baseline evaluation' });
+ let evalResult = (await runProsePass('evaluate', { work: ctx(), draftBody: body })).result;
+ let currentScore = computeQualityScore(evalResult, body);
+ const baseline = await saveSnapshot(workId, buildSnapshot({
+ workId, cycle: 0, phase: 'baseline', label: 'Baseline', body, evaluate: evalResult, qualityScore: currentScore,
+ }));
+ broadcast({ type: 'baseline', runId, score: currentScore, snapshotId: baseline.id, wordCount: countWords(body) });
+
+ const reports = [];
+ for (let c = 1; c <= cfg.cycles; c += 1) {
+ if (isCanceled()) { emitCanceled(); return; }
+
+ const preScore = currentScore;
+ const preBody = body;
+ const preEval = evalResult;
+ const cycleStart = Date.now();
+ // Immutable pre-cycle snapshot — the revert target for both the gate and
+ // the manual UI control.
+ const preSnap = await saveSnapshot(workId, buildSnapshot({
+ workId, cycle: c, phase: 'pre', label: `Cycle ${c} · before`, body: preBody, evaluate: preEval, qualityScore: preScore,
+ }));
+
+ // 1. Adversarial cut pass.
+ broadcast({ type: 'phase', cycle: c, phase: 'cuts', label: 'Adversarial cut pass' });
+ const cutsResult = (await runProsePass('cuts', {
+ work: ctx(), draftBody: preBody,
+ cutTargetPercent: cfg.cutTargetPercent, minCuts: cfg.minCuts, maxCuts: cfg.maxCuts,
+ })).result;
+ if (isCanceled()) { emitCanceled(); return; }
+
+ // 2. Mechanically apply the SAFE cut types (OVER-EXPLAIN + REDUNDANT).
+ const { applicable, refused } = planCutsForSection(
+ preBody, mapFindingsToCuts(cutsResult.findings), { safeTypesOnly: true, allowTypes: SAFE_CUT_TYPES },
+ );
+ const cutBody = applicable.length ? applyCutsToText(preBody, applicable) : preBody;
+ console.log(`✂️ wr polish: cycle ${c} cuts found=${(cutsResult.findings || []).length} applied=${applicable.length} refused=${refused.length}`);
+ broadcast({
+ type: 'cuts', cycle: c, found: (cutsResult.findings || []).length,
+ applied: applicable.length, refused: refused.length, fatPercentage: cutsResult.fatPercentage,
+ });
+
+ // 3. Brief-driven revision (receives the cut body as raw material).
+ broadcast({ type: 'phase', cycle: c, phase: 'revise', label: 'Brief-driven revision' });
+ const brief = buildRevisionBrief({ evaluate: preEval, cuts: cutsResult, wordCount: countWords(cutBody) });
+ const revised = (await runProsePass('revise', { work: ctx(), draftBody: cutBody, brief })).result;
+ const revisedBody = (revised.revisedBody && revised.revisedBody.trim()) ? revised.revisedBody : cutBody;
+ if (isCanceled()) { emitCanceled(); return; }
+
+ // Persist tentatively so a re-evaluate reads the same on-disk body.
+ await saveDraftBody(workId, revisedBody);
+
+ // 4. Re-evaluate + keep/revert gate.
+ broadcast({ type: 'phase', cycle: c, phase: 'reevaluate', label: 'Re-evaluation' });
+ const postEval = (await runProsePass('evaluate', { work: ctx(), draftBody: revisedBody })).result;
+ const postScore = computeQualityScore(postEval, revisedBody);
+ const decision = decideKeepRevert(preScore, postScore);
+
+ if (decision === 'revert') {
+ await saveDraftBody(workId, preBody);
+ body = preBody;
+ evalResult = preEval;
+ currentScore = preScore;
+ } else {
+ body = revisedBody;
+ evalResult = postEval;
+ currentScore = postScore;
+ }
+
+ const report = {
+ cycle: c,
+ preScore, postScore, keptScore: currentScore, decision,
+ cutsApplied: applicable.length,
+ wordCountBefore: countWords(preBody),
+ wordCountAfter: countWords(body),
+ snapshotId: preSnap.id,
+ ms: Date.now() - cycleStart,
+ };
+ reports.push(report);
+ console.log(`📝 wr polish: cycle ${c} ${decision} pre=${preScore} post=${postScore} kept=${currentScore} (${report.ms}ms)`);
+ broadcast({ type: 'cycle', ...report });
+
+ // 5. Plateau stop — converged when the kept gain is below threshold.
+ if (shouldStopPlateau(preScore, currentScore, cfg.plateauThreshold)) {
+ broadcast({ type: 'plateau', cycle: c, delta: Math.round(Math.abs(currentScore - preScore) * 100) / 100 });
+ break;
+ }
+ }
+
+ broadcast({
+ type: 'complete', runId, cyclesRun: reports.length, finalScore: currentScore,
+ wordCount: countWords(body), reports, completedAt: nowIso(),
+ });
+ });
+}
diff --git a/server/services/writersRoom/polish.test.js b/server/services/writersRoom/polish.test.js
new file mode 100644
index 0000000000..553807f2f2
--- /dev/null
+++ b/server/services/writersRoom/polish.test.js
@@ -0,0 +1,274 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtempSync, rmSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';
+
+let tempRoot;
+
+vi.mock('../../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../../lib/fileUtils.js');
+ return makePathsProxy(actual, { dataRoot: () => tempRoot });
+});
+
+// polish.js imports ONLY `runProsePass` from evaluator.js — a minimal mock keeps
+// the whole LLM/toolkit graph (and its data-dir reads) out of this unit test.
+vi.mock('./evaluator.js', () => ({ runProsePass: vi.fn() }));
+
+const { runProsePass } = await import('./evaluator.js');
+const polish = await import('./polish.js');
+const local = await import('./local.js');
+
+const {
+ scoreEvaluation, computeQualityScore, decideKeepRevert, shouldStopPlateau,
+ mapFindingsToCuts, buildRevisionBrief, resolvePolishOptions,
+ startPolish, listSnapshots, revertToSnapshot, isPolishActive, attachClient,
+ DEFAULT_PLATEAU_THRESHOLD, MAX_CYCLES,
+} = polish;
+
+beforeEach(() => {
+ tempRoot = mkdtempSync(join(tmpdir(), 'wr-polish-test-'));
+ runProsePass.mockReset();
+});
+
+afterEach(() => {
+ if (tempRoot && existsSync(tempRoot)) rmSync(tempRoot, { recursive: true, force: true });
+});
+
+// ---------- pure helpers ----------
+
+describe('scoreEvaluation', () => {
+ it('is 100 for a clean evaluation and drops by weighted severity', () => {
+ expect(scoreEvaluation({ issues: [] })).toBe(100);
+ expect(scoreEvaluation({ issues: [{ severity: 'major' }] })).toBe(97);
+ expect(scoreEvaluation({ issues: [{ severity: 'moderate' }, { severity: 'minor' }] })).toBe(97);
+ // Unknown severity weighted as 1; missing issues array → clean.
+ expect(scoreEvaluation({ issues: [{ severity: 'weird' }] })).toBe(99);
+ expect(scoreEvaluation(null)).toBe(100);
+ });
+
+ it('never goes below 0', () => {
+ const issues = Array.from({ length: 60 }, () => ({ severity: 'major' }));
+ expect(scoreEvaluation({ issues })).toBe(0);
+ });
+});
+
+describe('computeQualityScore', () => {
+ it('subtracts the deterministic slop penalty from the evaluate score', () => {
+ const clean = 'The door opened. Rain fell on the stones. She walked home in silence.';
+ const q = computeQualityScore({ issues: [] }, clean);
+ expect(q).toBeLessThanOrEqual(100);
+ // Slop-heavy text scores strictly lower than clean text for the same eval.
+ const slop = 'It was a tapestry of myriad delve. '.repeat(20);
+ expect(computeQualityScore({ issues: [] }, slop)).toBeLessThan(q + 0.001);
+ });
+});
+
+describe('decideKeepRevert', () => {
+ it('keeps when the score did not regress (ties keep)', () => {
+ expect(decideKeepRevert(90, 95)).toBe('keep');
+ expect(decideKeepRevert(90, 90)).toBe('keep');
+ expect(decideKeepRevert(90, 89.9)).toBe('revert');
+ });
+});
+
+describe('shouldStopPlateau', () => {
+ it('stops when the kept gain is below the threshold', () => {
+ expect(shouldStopPlateau(90, 90, DEFAULT_PLATEAU_THRESHOLD)).toBe(true);
+ expect(shouldStopPlateau(90, 90.2, 0.5)).toBe(true);
+ expect(shouldStopPlateau(90, 92, 0.5)).toBe(false);
+ });
+});
+
+describe('mapFindingsToCuts', () => {
+ it('keeps only findings with an anchor quote + cut type and maps cutType→subtype', () => {
+ const cuts = mapFindingsToCuts([
+ { anchorQuote: 'some passage', cutType: 'REDUNDANT' },
+ { anchorQuote: '', cutType: 'FAT' },
+ { anchorQuote: 'no type', cutType: null },
+ ]);
+ expect(cuts).toEqual([{ anchorQuote: 'some passage', subtype: 'REDUNDANT' }]);
+ expect(mapFindingsToCuts(null)).toEqual([]);
+ });
+});
+
+describe('buildRevisionBrief', () => {
+ it('composes PROBLEM / WHAT TO KEEP / WHAT TO CHANGE / VOICE / TARGET with protected material', () => {
+ const brief = buildRevisionBrief({
+ evaluate: {
+ logline: 'A knight doubts his oath.',
+ themes: ['duty', 'doubt'],
+ issues: [{ severity: 'major', category: 'pacing', note: 'The middle sags.' }],
+ strengths: ['Sharp dialogue'],
+ suggestions: [{ target: 'scene 2', recommendation: 'Cut the flashback.' }],
+ },
+ cuts: {
+ tightestPassage: 'the sword felt heavier than the vow',
+ loosestPassage: 'and so it was that everything happened as it did',
+ findings: [{ cutType: 'FAT', problem: 'Purple.', anchorQuote: 'gilded gossamer glory' }],
+ },
+ wordCount: 1200,
+ });
+ expect(brief).toContain('## PROBLEM');
+ expect(brief).toContain('The middle sags.');
+ expect(brief).toContain('## WHAT TO KEEP');
+ expect(brief).toContain('do NOT cut or weaken');
+ expect(brief).toContain('Sharp dialogue');
+ expect(brief).toContain('## WHAT TO CHANGE');
+ expect(brief).toContain('Cut the flashback.');
+ expect(brief).toContain('## VOICE RULES');
+ expect(brief).toContain('duty, doubt');
+ expect(brief).toContain('## TARGET');
+ expect(brief).toContain('1200 words');
+ // A safe-type cut is auto-applied elsewhere; only NON-safe types land in the brief.
+ expect(brief).toContain('gilded gossamer glory');
+ });
+});
+
+describe('resolvePolishOptions', () => {
+ it('clamps cycles to 1..MAX and applies defaults', () => {
+ expect(resolvePolishOptions({}).cycles).toBe(1);
+ expect(resolvePolishOptions({ cycles: 99 }).cycles).toBe(MAX_CYCLES);
+ expect(resolvePolishOptions({ cycles: 0 }).cycles).toBe(1);
+ expect(resolvePolishOptions({}).plateauThreshold).toBe(DEFAULT_PLATEAU_THRESHOLD);
+ expect(resolvePolishOptions({ cutTargetPercent: 12 }).cutTargetPercent).toBe(12);
+ });
+});
+
+// ---------- runner integration (mocked LLM, real disk) ----------
+
+// A fake SSE client so we can collect the broadcast frames and await the
+// terminal one. Attached right after startPolish returns — before the runner's
+// first `await` resolves — so every frame after `start` is captured.
+function makeFakeClient() {
+ const frames = [];
+ let resolveDone;
+ const done = new Promise((r) => { resolveDone = r; });
+ const res = {
+ req: { on: () => {} },
+ writeHead: () => {},
+ end: () => {},
+ write: (msg) => {
+ const frame = JSON.parse(msg.replace(/^data:\s*/, '').trim());
+ frames.push(frame);
+ if (frame.type === 'complete' || frame.type === 'error' || frame.type === 'canceled') resolveDone(frame);
+ },
+ };
+ return { res, frames, done };
+}
+
+async function seedWork(body) {
+ const work = await local.createWork({ title: 'Polish subject', kind: 'short-story' });
+ await local.saveDraftBody(work.id, body);
+ return work;
+}
+
+// Program the mocked runProsePass to answer per-kind.
+function programPasses({ baselineIssues, postIssues, cutFindings = [], revisedBody }) {
+ let evaluateCalls = 0;
+ runProsePass.mockImplementation(async (kind) => {
+ if (kind === 'evaluate') {
+ evaluateCalls += 1;
+ const issues = evaluateCalls === 1 ? baselineIssues : postIssues;
+ return { result: { issues, strengths: [], suggestions: [], themes: [], logline: 'x' } };
+ }
+ if (kind === 'cuts') {
+ return { result: { findings: cutFindings, fatPercentage: 5, tightestPassage: null, loosestPassage: null } };
+ }
+ if (kind === 'revise') {
+ return { result: { revisedBody } };
+ }
+ throw new Error(`unexpected kind ${kind}`);
+ });
+}
+
+describe('startPolish runner', () => {
+ it('keeps a revision that improves the score and writes it to the draft', async () => {
+ const original = 'The knight stood at the gate. He explained, needlessly, that he was afraid. '.repeat(6);
+ const revised = 'The knight stood at the gate, afraid.';
+ const work = await seedWork(original);
+
+ programPasses({
+ baselineIssues: [{ severity: 'major' }, { severity: 'major' }, { severity: 'major' }],
+ postIssues: [],
+ revisedBody: revised,
+ });
+
+ const { runId } = startPolish(work.id, { cycles: 1 });
+ const { res, frames, done } = makeFakeClient();
+ attachClient(work.id, res);
+ const terminal = await done;
+
+ expect(runId).toBeTruthy();
+ expect(terminal.type).toBe('complete');
+ // The runner flips `finished` in its finally block, one microtask after the
+ // terminal frame — let it settle before asserting the run is no longer active.
+ await new Promise((r) => setTimeout(r, 0));
+ expect(isPolishActive(work.id)).toBe(false);
+
+ const cycle = frames.find((f) => f.type === 'cycle');
+ expect(cycle.decision).toBe('keep');
+ expect(cycle.postScore).toBeGreaterThan(cycle.preScore);
+
+ const { body } = await local.getWorkWithBody(work.id);
+ expect(body).toBe(revised);
+
+ // 4 LLM passes for one cycle: baseline evaluate, cuts, revise, re-evaluate.
+ expect(runProsePass).toHaveBeenCalledTimes(4);
+ });
+
+ it('reverts a regressing revision back to the pre-cycle body', async () => {
+ const original = 'A clean, tight opening paragraph that says exactly what it needs to say.';
+ const worse = 'Slop slop slop. '.repeat(40);
+ const work = await seedWork(original);
+
+ programPasses({
+ baselineIssues: [],
+ postIssues: [{ severity: 'major' }, { severity: 'major' }, { severity: 'major' }, { severity: 'major' }, { severity: 'major' }],
+ revisedBody: worse,
+ });
+
+ startPolish(work.id, { cycles: 1 });
+ const { res, frames, done } = makeFakeClient();
+ attachClient(work.id, res);
+ await done;
+
+ const cycle = frames.find((f) => f.type === 'cycle');
+ expect(cycle.decision).toBe('revert');
+
+ // The regressing revision was rolled back — the draft is the original again.
+ const { body } = await local.getWorkWithBody(work.id);
+ expect(body).toBe(original);
+ });
+
+ it('snapshots each cycle and a manual revert round-trips the body', async () => {
+ const original = 'Original prose. '.repeat(10);
+ const revised = 'Revised prose that is better.';
+ const work = await seedWork(original);
+
+ programPasses({
+ baselineIssues: [{ severity: 'major' }, { severity: 'major' }],
+ postIssues: [],
+ revisedBody: revised,
+ });
+
+ startPolish(work.id, { cycles: 1 });
+ const { res, done } = makeFakeClient();
+ attachClient(work.id, res);
+ await done;
+
+ // Draft is now the kept revision.
+ expect((await local.getWorkWithBody(work.id)).body).toBe(revised);
+
+ const snaps = await listSnapshots(work.id);
+ // Baseline + pre-cycle snapshots exist, newest-first.
+ expect(snaps.length).toBeGreaterThanOrEqual(2);
+
+ // The pre-cycle snapshot holds the ORIGINAL body — reverting restores it.
+ const preCycle = snaps.find((s) => s.cycle === 1);
+ expect(preCycle).toBeTruthy();
+ const { body } = await revertToSnapshot(work.id, preCycle.id);
+ expect(body).toBe(original);
+ expect((await local.getWorkWithBody(work.id)).body).toBe(original);
+ });
+});