Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-2179]): Writers Room voice exemplar parity (the tuning fork)
Adam Eivyfcb49238de89
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 25ba60d59f..b3e3278263 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -47,6 +47,8 @@## Creative Writing Quality Engine+- **[issue-2179] The Writers Room now anchors a freeform work's voice with the same exemplar/anti-exemplar passages ("the tuning fork") the series pipeline already uses.** Completing #2179's Writers Room parity: a work can now carry `voiceExemplars` (1–3 short passages that nail its target voice, each with an optional note on what it demonstrates) and `voiceAntiExemplars` (passages in the wrong register, noted with what's wrong — "too ornate", "wrong temperature"), edited in a new **Voice exemplars** drawer on the work editor. On generation those render into the SAME "MATCH this voice / NEVER drift toward this" blocks as the series style guide — via the shared `renderVoiceExemplars`/`sanitizeVoiceExemplars` helpers now exported from `server/lib/styleGuide.js` (one sanitizer, one set of caps, no drift between surfaces) — and are injected into the two prose-generation paths: the **live-continuation** prompt (`writers-room-continue.md`, gated by a conditional `{{#voiceGuide}}` block so a work with no passages carries zero per-call overhead) and the **Phase 9 polish loop**'s revision brief (folded into VOICE RULES so the rewrite is held to the chosen voice, not just told to "match the existing voice"). The editor UI is the shared `VoiceExemplarEditor` component (extracted from the series style-guide editor and reused by both). Zod parity on `writersRoomWorkUpdateSchema` (each passage capped at 2000 chars, list at 3; an explicit `[]` clears); the server sanitizer drops empty passages and re-sanitizes on read. `writers-room-continue.md` is a shipped template, so the block ships to existing installs via a standard hash-keyed migration (179) with migration 166 resynced and the drift baseline updated. (Final slice of #2179 — the earlier slices shipped the series exemplar fields, the AI voice-discovery flow, and the voice-fingerprint baseline hook.) (`server/lib/styleGuide.js`, `server/lib/pipelineValidation.js`, `server/services/writersRoom/local.js`, `server/services/writersRoom/liveDirector.js`, `server/services/writersRoom/polish.js`, `data.reference/prompts/stages/writers-room-continue.md`, `scripts/migrations/179-writers-room-voice-exemplars.js`, `client/src/components/VoiceExemplarEditor.jsx`, `client/src/components/writers-room/WorkEditor.jsx`)+- **[issue-2169] Two comparative-quality mechanisms build on the calibrated judge — a multi-candidate draft gate, and head-to-head Elo ranking of a series' issues.** Both compose the Phase 3 judge (#2167) to escape autonovel's "rubric trap" (absolute 1-10 scores collapse into a 2-point band; comparison forces the discrimination the judge can't avoid). **(1) Multi-candidate draft gate** — a new opt-in per-stage config (`draftAttempts` 1–3, default **1 = off**; optional `draftGateThreshold`, schema parity added to `stageConfigUpdateSchema`) makes `generateStage` generate → judge → re-roll a FRESH draft while the composite `qualityScore` is below the threshold, up to the attempt cap, and keep the best-scoring attempt. Every attempt persists (rejected drafts stay recoverable in run history) and a per-attempt scorecard lands on `stage.draftGate` (`{ winner, threshold, attempts:[{ runId, qualityScore, rejected }] }`) — never silently discarded. Only the judgeable stages (prose/comicScript/teleplay) gate; the single-shot path is byte-for-byte unchanged when off. When run from Series Autopilot each re-roll bills one cos action and stops re-rolling when the daily budget is spent (keeping the best so far); a manual regenerate is never cos-billed. Canon extraction runs once, on the winning draft. **(2) Head-to-head Elo ranking** — a new `comparativeRank.js` + forced-pick `pipeline-judge-compare.md` stage prompt ("you are not allowed to call it a tie" — quote the deciding passage) runs a Swiss-style tournament (~4 rounds, K=32 Elo) across the series' drafted issues, each side truncated to a comparable budget via `contextBudget.js`. The ranking + per-match records persist at `data/pipeline-comparative-rank/{seriesId}.json`, content-hash-pinned for staleness (reuses `computeSourceContentHash`), with the weakest-N slice as the revision-priority order Phase 7 consumes. A tie/hedge/garbage pick from the judge falls through to a deterministic, balanced tiebreak. Surfaced as a new **Rankings** tab on the Reader Map page (`?tab=rank`) — an Elo table with the weakest issues flagged as revision priorities. Runs ONLY from the explicit "Rank issues" action or an autopilot step — never at boot (AI-provider policy). Pure Elo math + Swiss pairing + tie-refusal parsing + staleness are unit-tested. (`server/services/pipeline/editorial/comparativeRank.js`, `server/services/pipeline/textStages.js`, `server/services/pipeline/issues.js`, `server/services/pipeline/seriesAutopilot.js`, `server/lib/pipelineValidation.js`, `server/routes/pipeline/editorial.js`, `data.reference/prompts/stages/pipeline-judge-compare.md`, `client/src/components/pipeline/ComparativeRankView.jsx`, `client/src/pages/PipelineSeriesRoadmap.jsx`, `client/src/services/apiPipeline.js`)- **[issue-2167] A calibrated LLM quality judge now scores each drafted issue, with a writer/judge model split — `qualityScore = judge overall − deterministic slop penalty`.** PortOS had severity findings and a deterministic health score but no LLM quality *score* per issue — the keep/revert currency Phases 5 and 7 need. A new harsh, calibrated judge (`server/services/pipeline/pipelineJudge.js`, stage prompt `pipeline-judge-issue.md`) scores a drafted issue across **9 dimensions** (voice adherence, beat coverage, character voice, plants seeded, prose quality, continuity, canon compliance, lore integration, engagement) against the SAME contract the writer received — style guide, beat sheet, and **full canon** (no reveal-gating, so it can catch canon/continuity/premature-reveal issues the writer's horizon-filtered view hides). An anti-inflation **calibration ladder** ("the median competent AI-generated chapter is a 6; a 10 does not exist for a draft; err lower") plus a **QUOTE TEST** (3 strongest / 3 weakest exact sentences) and a scene-vs-summary ratio keep the judge honest. The composite `qualityScore = judgeOverall − computeSlopPenalty(text)` (the deterministic slop penalty from #2165, clamped ≥ 0) is the dual immune system — the mechanical layer catches what the LLM judge normalizes away. **Writer/judge split:** a new `resolveJudgeForStage()` (sibling of `resolveProviderForStage()` in `server/lib/stageRunner.js`) resolves a per-writer-stage `judgeProvider`/`judgeModel` pin (schema parity: added to `stageConfigUpdateSchema`), defaulting to the writer's own provider but with the UI encouraging a *different*, harsher judge model to avoid self-congratulation. Scores persist per issue+stage at `data/pipeline-judge/{issueId}.json` with a `sourceContentHash` so a later edit flips the score to `stale` (mirrors `editorialAnalysis.js`), and the judge run itself lands in run history via `runStagedLLM` (a malformed-JSON response is retried once). Surfaced as a score chip + dimension/quote/revision breakdown on the issue page (`IssueJudgePanel`) and a weakest-first quality column on the series Editorial Roadmap. Runs ONLY from an explicit user action or the already-consented autopilot — never at boot. (`server/services/pipeline/pipelineJudge.js`, `server/lib/stageRunner.js`, `server/routes/pipeline/editorial.js`, `data.reference/prompts/stages/pipeline-judge-issue.md`, `client/src/components/pipeline/IssueJudgePanel.jsx`, `client/src/pages/PipelineSeriesRoadmap.jsx`)diff --git a/client/src/components/VoiceExemplarEditor.jsx b/client/src/components/VoiceExemplarEditor.jsxnew file mode 100644index 0000000000..4fddf4e6c0--- /dev/null+++ b/client/src/components/VoiceExemplarEditor.jsx@@ -0,0 +1,71 @@+// Shared editor for voice exemplar / anti-exemplar passage lists (#2179 — "the+// tuning fork"). Each row is `{ passage, note }`: the passage textarea is+// required (an empty passage prunes the row server-side), the note is an+// optional one-liner (what the passage demonstrates, or what's wrong with it).+// Capped at VOICE_EXEMPLARS_MAX rows. All labels are htmlFor/id paired.+//+// Used by BOTH the series style-guide editor (PipelineSeries) and the Writers+// Room work voice drawer (WorkEditor) so a freeform work anchors its voice the+// same way a series does — one component, no drift between the two surfaces.+// Caps mirror STYLE_GUIDE_LIMITS in server/lib/styleGuide.js.++export const VOICE_EXEMPLARS_MAX = 3;+export const VOICE_EXEMPLAR_PASSAGE_MAX = 2000;+export const VOICE_EXEMPLAR_NOTE_MAX = 200;++export default function VoiceExemplarEditor({ idPrefix, title, hint, notePlaceholder, entries, onChange }) {+ const list = Array.isArray(entries) ? entries : [];+ const setEntry = (i, patch) => onChange(list.map((e, idx) => (idx === i ? { ...e, ...patch } : e)));+ const removeEntry = (i) => onChange(list.filter((_, idx) => idx !== i));+ const addEntry = () => onChange([...list, { passage: '', note: '' }]);++ return (+ <div className="mt-3">+ <h4 className="text-[11px] uppercase tracking-wider text-gray-500 mb-1">{title}</h4>+ <p className="text-[11px] text-gray-500 mb-2 -mt-0.5">{hint}</p>+ <div className="space-y-2">+ {list.map((entry, i) => (+ <div key={i} className="border border-port-border rounded p-2 bg-port-bg/50">+ <label htmlFor={`${idPrefix}-passage-${i}`} className="block text-[11px] text-gray-500 mb-1">Passage {i + 1}</label>+ <textarea+ id={`${idPrefix}-passage-${i}`}+ value={entry.passage || ''}+ onChange={(e) => setEntry(i, { passage: e.target.value })}+ rows={4}+ maxLength={VOICE_EXEMPLAR_PASSAGE_MAX}+ placeholder="Paste a short prose passage that captures the voice."+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm font-mono"+ />+ <div className="flex items-center gap-2 mt-1">+ <label htmlFor={`${idPrefix}-note-${i}`} className="sr-only">Note for passage {i + 1}</label>+ <input+ id={`${idPrefix}-note-${i}`}+ value={entry.note || ''}+ onChange={(e) => setEntry(i, { note: e.target.value })}+ maxLength={VOICE_EXEMPLAR_NOTE_MAX}+ placeholder={notePlaceholder}+ className="flex-1 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-xs"+ />+ <button+ type="button"+ onClick={() => removeEntry(i)}+ className="px-2 py-1 text-xs text-port-error hover:bg-port-error/10 rounded"+ >+ Remove+ </button>+ </div>+ </div>+ ))}+ </div>+ {list.length < VOICE_EXEMPLARS_MAX && (+ <button+ type="button"+ onClick={addEntry}+ className="mt-2 px-2 py-1 text-xs text-port-accent hover:bg-port-accent/10 rounded border border-port-border"+ >+ + Add passage+ </button>+ )}+ </div>+ );+}diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsxindex 73fb9f826d..51548fd638 100644--- a/client/src/components/writers-room/WorkEditor.jsx+++ b/client/src/components/writers-room/WorkEditor.jsx@@ -24,6 +24,7 @@ import {ExternalLink,Zap,Wand2,+ Quote,} from 'lucide-react';import toast from '../ui/Toast';import ProseEditor from '../ui/ProseEditor';@@ -55,10 +56,11 @@ import ProseReader from './ProseReader';import SyncedReview from './SyncedReview';import ProseTokenPopover from './ProseTokenPopover';import WritersRoomDock from './WritersRoomDock';+import VoiceExemplarEditor, { VOICE_EXEMPLARS_MAX } from '../VoiceExemplarEditor';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', POLISH: 'polish' };+const DRAWER = { VERSIONS: 'versions', HISTORY: 'history', POLISH: 'polish', VOICE: 'voice' };const MOBILE_TAB = { WRITING: 'writing', STORYBOARD: 'storyboard' };const ANALYSIS_LABELS = {@@ -163,6 +165,16 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO// render-preview budget is a distinct counter owned by LiveRenderPanel.const [liveUsage, setLiveUsage] = useState(liveMode?.usage || null);useEffect(() => { setLiveUsage(liveMode?.usage || null); }, [liveMode?.usage]);+ // Voice exemplars / anti-exemplars (#2179) — "the tuning fork" passages that+ // anchor the live-continuation prompt + the polish revision brief to the+ // chosen voice. Edited in the Voice drawer, persisted via updateWork on Save.+ // Hoisted here (not inside the drawer body) so switching works re-seeds it and+ // the drawer body can remount freely without losing in-progress edits.+ const [voiceExemplars, setVoiceExemplars] = useState(work.voiceExemplars || []);+ const [voiceAntiExemplars, setVoiceAntiExemplars] = useState(work.voiceAntiExemplars || []);+ const [savingVoice, setSavingVoice] = useState(false);+ useEffect(() => { setVoiceExemplars(work.voiceExemplars || []); }, [work.id, work.voiceExemplars]);+ useEffect(() => { setVoiceAntiExemplars(work.voiceAntiExemplars || []); }, [work.id, work.voiceAntiExemplars]);const liveTriggerRef = useRef(null);const liveTimerRef = useRef(null);const registerLiveTrigger = useCallback((fn) => { liveTriggerRef.current = fn; }, []);@@ -479,6 +491,33 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO}};+ // Persist the voice exemplars (#2179). Drop rows with a blank passage before+ // sending (the server prunes them too, but this keeps the round-tripped state+ // honest) and clear the drawer's dirty edits into the saved work.+ const saveVoice = async () => {+ const clean = (list) => (Array.isArray(list) ? list : [])+ .map((e) => ({ passage: (e.passage || '').trim(), note: (e.note || '').trim() }))+ .filter((e) => e.passage)+ .map((e) => (e.note ? e : { passage: e.passage }));+ setSavingVoice(true);+ const updated = await updateWritersRoomWork(work.id, {+ voiceExemplars: clean(voiceExemplars),+ voiceAntiExemplars: clean(voiceAntiExemplars),+ }).catch((err) => {+ if (mountedRef.current) toast.error(`Voice save failed: ${err.message}`);+ return null;+ });+ if (!mountedRef.current) return;+ setSavingVoice(false);+ if (updated) {+ setVoiceExemplars(updated.voiceExemplars || []);+ setVoiceAntiExemplars(updated.voiceAntiExemplars || []);+ onChange?.({ ...updated, activeDraftBody: body });+ toast.success('Voice exemplars saved');+ setDrawer(null);+ }+ };+// --- Phase 5 live mode ---const liveEnabled = liveMode?.enabled === true;@@ -883,6 +922,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO<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={Quote} label="Voice exemplars" onClick={closeOverflowAnd(() => setDrawer(DRAWER.VOICE))} /><MenuItem icon={Zap} label={liveEnabled ? 'Disable live director' : 'Enable live director'} active={liveEnabled} onClick={closeOverflowAnd(toggleLiveMode)} /></MenuSection><MenuSection label="Open">@@ -1112,6 +1152,40 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO<Drawer open={drawer === DRAWER.POLISH} onClose={() => setDrawer(null)} title="Polish" size="md"><PolishPanel work={work} dirty={dirty} onBodyChanged={reloadBodyFromServer} /></Drawer>+ <Drawer open={drawer === DRAWER.VOICE} onClose={() => setDrawer(null)} title="Voice exemplars" size="md">+ <div className="p-3">+ <p className="text-[11px] text-gray-500 mb-2">+ Concrete prose passages anchor this work’s voice far better than adjectives. Exemplars are injected into live continuation suggestions and the Polish revision brief as “MATCH this voice”; anti-exemplars as “NEVER drift toward this.” Up to {VOICE_EXEMPLARS_MAX} of each.+ </p>+ <VoiceExemplarEditor+ idPrefix="wr-voice-exemplar"+ title="Voice exemplars (the tuning fork)"+ hint="1–3 short passages (~150–300 words) that nail this work's voice. Injected as “MATCH this voice.”"+ notePlaceholder="what this demonstrates (e.g. spare, close-psychic)"+ entries={voiceExemplars}+ onChange={setVoiceExemplars}+ />+ <VoiceExemplarEditor+ idPrefix="wr-voice-anti"+ title="Anti-exemplars (never drift toward this)"+ hint="Passages in the wrong register, kept as negative examples. Injected as “NEVER drift toward this.”"+ notePlaceholder="what's wrong (e.g. too ornate, wrong temperature)"+ entries={voiceAntiExemplars}+ onChange={setVoiceAntiExemplars}+ />+ <div className="mt-4 flex justify-end">+ <button+ type="button"+ onClick={saveVoice}+ disabled={savingVoice}+ className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm rounded bg-port-accent text-white hover:bg-port-accent/90 disabled:opacity-50"+ >+ {savingVoice ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}+ {savingVoice ? 'Saving…' : 'Save voice'}+ </button>+ </div>+ </div>+ </Drawer></div>);}diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsxindex 7335efe6a2..d4a3a7604e 100644--- a/client/src/pages/PipelineSeries.jsx+++ b/client/src/pages/PipelineSeries.jsx@@ -31,6 +31,7 @@ import {SERIES_TITLE_LOGO_MAX,} from '../services/api';import AuthorPicker from '../components/pipeline/AuthorPicker';+import VoiceExemplarEditor, { VOICE_EXEMPLARS_MAX } from '../components/VoiceExemplarEditor';import { buildImporterLink } from '../lib/importerDeepLink';import { recommendStructure, describeStructure } from '../lib/seasonStructure';import { useLocalStorageBool } from '../hooks/useLocalStorageBool';@@ -82,11 +83,10 @@ const STYLE_GUIDE_FIELDS = [{ key: 'contentRating', label: 'Content rating', options: [['G', 'G'], ['PG', 'PG'], ['PG-13', 'PG-13'], ['R', 'R'], ['custom', 'Custom']] },{ key: 'profanity', label: 'Profanity', options: [['none', 'None'], ['mild', 'Mild'], ['moderate', 'Moderate'], ['strong', 'Strong']] },];-// Voice exemplar caps — mirror STYLE_GUIDE_LIMITS in server/lib/styleGuide.js-// so the editor bounds match the server sanitizer (#2179).-const STYLE_GUIDE_EXEMPLARS_MAX = 3;-const STYLE_GUIDE_EXEMPLAR_PASSAGE_MAX = 2000;-const STYLE_GUIDE_EXEMPLAR_NOTE_MAX = 200;+// Voice exemplar cap — mirror STYLE_GUIDE_LIMITS in server/lib/styleGuide.js so+// the editor bounds match the server sanitizer (#2179). The passage/note caps+// live on the shared VoiceExemplarEditor.+const STYLE_GUIDE_EXEMPLARS_MAX = VOICE_EXEMPLARS_MAX;// Tri-state boolean conventions rendered as —/Yes/No selects so "unset" stays// distinct from "No" (matches the server's tri-state sanitizer).const STYLE_GUIDE_TRISTATE = [@@ -743,66 +743,6 @@ function VoiceCandidateCard({ candidate, filedAs, onFileExemplar, onFileAntiExem);}-// Editor for the voice exemplar / anti-exemplar passage lists (#2179). Each row-// is `{ passage, note }`; the passage textarea is required (an empty passage-// prunes the row), the note is an optional one-liner. Capped at-// STYLE_GUIDE_EXEMPLARS_MAX rows. All labels are htmlFor/id paired.-function VoiceExemplarEditor({ idPrefix, title, hint, notePlaceholder, entries, onChange }) {- const setEntry = (i, patch) => onChange(entries.map((e, idx) => (idx === i ? { ...e, ...patch } : e)));- const removeEntry = (i) => onChange(entries.filter((_, idx) => idx !== i));- const addEntry = () => onChange([...entries, { passage: '', note: '' }]);-- return (- <div className="mt-3">- <h4 className="text-[11px] uppercase tracking-wider text-gray-500 mb-1">{title}</h4>- <p className="text-[11px] text-gray-500 mb-2 -mt-0.5">{hint}</p>- <div className="space-y-2">- {entries.map((entry, i) => (- <div key={i} className="border border-port-border rounded p-2 bg-port-bg/50">- <label htmlFor={`${idPrefix}-passage-${i}`} className="block text-[11px] text-gray-500 mb-1">Passage {i + 1}</label>- <textarea- id={`${idPrefix}-passage-${i}`}- value={entry.passage || ''}- onChange={(e) => setEntry(i, { passage: e.target.value })}- rows={4}- maxLength={STYLE_GUIDE_EXEMPLAR_PASSAGE_MAX}- placeholder="Paste a short prose passage that captures the voice."- className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm font-mono"- />- <div className="flex items-center gap-2 mt-1">- <label htmlFor={`${idPrefix}-note-${i}`} className="sr-only">Note for passage {i + 1}</label>- <input- id={`${idPrefix}-note-${i}`}- value={entry.note || ''}- onChange={(e) => setEntry(i, { note: e.target.value })}- maxLength={STYLE_GUIDE_EXEMPLAR_NOTE_MAX}- placeholder={notePlaceholder}- className="flex-1 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-xs"- />- <button- type="button"- onClick={() => removeEntry(i)}- className="px-2 py-1 text-xs text-port-error hover:bg-port-error/10 rounded"- >- Remove- </button>- </div>- </div>- ))}- </div>- {entries.length < STYLE_GUIDE_EXEMPLARS_MAX && (- <button- type="button"- onClick={addEntry}- className="mt-2 px-2 py-1 text-xs text-port-accent hover:bg-port-accent/10 rounded border border-port-border"- >- + Add passage- </button>- )}- </div>- );-}-// The change-beat kinds the arc.transitions editorial check recognizes — mirror// TRANSITION_KINDS in server/lib/seriesCharacterArc.js.const TRANSITION_KIND_OPTIONS = [diff --git a/data.reference/prompts/stages/writers-room-continue.md b/data.reference/prompts/stages/writers-room-continue.mdindex ca113154cd..f96b749bd5 100644--- a/data.reference/prompts/stages/writers-room-continue.md+++ b/data.reference/prompts/stages/writers-room-continue.md@@ -25,6 +25,14 @@ You are a Creative Director sitting beside the writer as they draft. They have p```{{selection}}```+{{#voiceGuide}}++## Voice (the tuning fork)++These passages define the target voice for this work. Any drafted prose you propose (`kind: "prose"` or `"dialogue"`) must echo their rhythm, diction, and register — do not copy their content.++{{voiceGuide}}+{{/voiceGuide}}## Taskdiff --git a/scripts/migrations/166-craft-knowledge-prompt-upgrades.js b/scripts/migrations/166-craft-knowledge-prompt-upgrades.jsindex 30e129380b..d6b388b61f 100644--- a/scripts/migrations/166-craft-knowledge-prompt-upgrades.js+++ b/scripts/migrations/166-craft-knowledge-prompt-upgrades.js@@ -38,7 +38,10 @@ import { makePromptReplaceMigration } from './_lib.js';// Pre-change shipped hashes (the current shipped bodies before #2172).export const ACCEPTED_OLD_MD5 = {'pipeline-prose.md': ['25e3d58c2741bd98acd5d08ba70d8a5e', '430d38ed2da59e0d4212e65edc499a74'],- 'writers-room-continue.md': ['93bfe80543ceca39842201a78b8393fa'],+ 'writers-room-continue.md': [+ '93bfe80543ceca39842201a78b8393fa',+ '67663696c97ebaeb23de25f7410cfdd4', // post-166 / pre-179 (voice exemplars)+ ],'pipeline-arc-overview.md': ['0a1f6ffa6908522e3690c5e9e53a6ee0','612f8b04950e2ff26dd350dd76a062fe', // post-166 / pre-173 (MICE thread nesting)@@ -50,7 +53,7 @@ export const ACCEPTED_OLD_MD5 = {// continuity, #2177) per the drift-cross-sync convention.export const NEW_SHIPPED_MD5 = {'pipeline-prose.md': '4cb3ef48309f3673570cf80e4d544b54',- 'writers-room-continue.md': '67663696c97ebaeb23de25f7410cfdd4',+ 'writers-room-continue.md': '458dc5ff4732befc1fb90890bdc885c2', // post-179 (voice exemplars)'pipeline-arc-overview.md': '74d6c26548660d85fc345b2099c63b6c', // post-173 (MICE thread nesting)};diff --git a/scripts/migrations/179-writers-room-voice-exemplars.js b/scripts/migrations/179-writers-room-voice-exemplars.jsnew file mode 100644index 0000000000..7d3831c9f9--- /dev/null+++ b/scripts/migrations/179-writers-room-voice-exemplars.js@@ -0,0 +1,58 @@+/**+ * CWQE Phase 14 — Writers Room voice exemplars (#2179 parity slice).+ *+ * `writers-room-continue.md` gained a conditional "Voice (the tuning fork)"+ * block (`{{#voiceGuide}} … {{voiceGuide}} … {{/voiceGuide}}`) that injects a+ * work's voice exemplar / anti-exemplar passages into the live-continuation+ * prompt — the same "the tuning fork" anchoring the series style guide already+ * ships to prose/revision prompts. Absent exemplars render nothing (the section+ * is gated), so works without a configured voice carry no per-call overhead.+ *+ * `scripts/setup-data.js` only copies *missing* prompt files, so existing+ * installs keep their old `writers-room-continue.md` until this migration+ * rewrites it. The template already has a migration lineage (065 seed / 166+ * craft-anti-patterns) — per the drift-cross-sync convention, migration 166 is+ * resynced in this same change: its previous current hash+ * (`67663696…`) moved into its `ACCEPTED_OLD_MD5` and its `NEW_SHIPPED_MD5`+ * bumped to the post-179 hash, so 166's "NEW matches live data.reference"+ * drift-catch test stays green. The drift baseline in `setup-data-drift.test.js`+ * was updated to match the merged sweep.+ *+ * Customization-safe: only installs whose copy still hashes to the prior 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 current shipped body before #2179 — post-166).+export const ACCEPTED_OLD_MD5 = {+ 'writers-room-continue.md': ['67663696c97ebaeb23de25f7410cfdd4'],+};++// Post-change shipped hash (voice-guide block added).+export const NEW_SHIPPED_MD5 = {+ 'writers-room-continue.md': '458dc5ff4732befc1fb90890bdc885c2',+};++const { applyMigration, up } = makePromptReplaceMigration({+ accepted: ACCEPTED_OLD_MD5,+ current: NEW_SHIPPED_MD5,+ label: 'writers-room voice exemplars',+ customizedHint: (filename) =>+ ` To upgrade it manually, diff:\n` ++ ` data.reference/prompts/stages/${filename}\n` ++ ` against your current:\n` ++ ` data/prompts/stages/${filename}\n` ++ ` and add the "Voice (the tuning fork)" block (the\n` ++ ` {{#voiceGuide}} / {{voiceGuide}} / {{/voiceGuide}} section).`,+ skipFooter: (count) =>+ `⚠️ ${count} live-continuation prompt(s) could not be auto-updated because\n` ++ ` they were customized. Live suggestions still work, but they will miss\n` ++ ` the work's voice exemplars (the tuning fork) until you merge the\n` ++ ` {{#voiceGuide}} block from data.reference/prompts/stages/writers-room-continue.md.`,+});++export { applyMigration };+export default { up };diff --git a/scripts/migrations/179-writers-room-voice-exemplars.test.js b/scripts/migrations/179-writers-room-voice-exemplars.test.jsnew file mode 100644index 0000000000..3fa38314a4--- /dev/null+++ b/scripts/migrations/179-writers-room-voice-exemplars.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 './179-writers-room-voice-exemplars.js';++describe('migration 179 — writers-room voice exemplars', () => {+ runPromptMigrationTests({+ migration,+ applyMigration,+ ACCEPTED_OLD_MD5,+ NEW_SHIPPED_MD5,+ prefix: 'migration-179-',+ });+});diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.jsindex c5501e7820..c8c1a92e72 100644--- a/scripts/setup-data-drift.test.js+++ b/scripts/setup-data-drift.test.js@@ -26,7 +26,7 @@ const migrationsDir = join(dirname(fileURLToPath(import.meta.url)), 'migrations'const EXPECTED_STAGE_OLD = {'pipeline-idea-expansion.md': ['1ee44cf95851ff8debf18729ebcd40b4', '1f3c5d077a5ef9a4b610335d5e3edd9c', '41facefbc0c0549d456bef9111f95ab9', '49a208628290543ba2607a5ed48fdc8c', '93e9552c6662811e597a97296f3776a4', 'aee25112b2c596f643b17c559b772c22', 'b5c47c94ffc74637983c95761ab0c66c', 'c50f016639d41cd8244f5ff13429f997'],'pipeline-prose.md': ['30ac30ec2b9d3e2a9eb869c181732cc6', '84523d531eeafa60959c65c553b2563f', 'bef1bc2767b78f585f2bd89f3d615130', 'bfea5aeeb471aae9749baee765b473a7', 'd1f8e3f1d214725b5aa67f309a81cd7d', '25e3d58c2741bd98acd5d08ba70d8a5e', '430d38ed2da59e0d4212e65edc499a74'],- 'writers-room-continue.md': ['93bfe80543ceca39842201a78b8393fa'],+ 'writers-room-continue.md': ['93bfe80543ceca39842201a78b8393fa', '67663696c97ebaeb23de25f7410cfdd4'],'pipeline-comic-script.md': ['133d200d069c2e8173b7c129eea58f53', '1e0af305c27d0c80c4b482d2ebcb4a0d', '40e5fdc1a1e68a7419b7dad936366c1a', '7c05ecde539f04c9fa91e87543057204', 'a4303016c34b65e4b0e641fe71252de3', 'beab031951859ca13579cdb9c4dbe769', 'dea7d497d1cb38e7574f236f4ff8e644', 'e530fc76b89cedaef848ad7ec99c934c', 'e9ee70bf18888492edada6633cd9928a'],'pipeline-teleplay.md': ['1280ef6b1ad68fa44070ca7478ec2a5f', '2568e14beaa574d43f8018a5def51d04', '376f779f4687b598f1c92ca4e770fd5a', '3f6fecc25573ed054b47db392250034a', 'afa4215330bf856429d70d7e2f856605'],'pipeline-season-episodes.md': ['6e349ad26bed8a0ccb042571f03f03eb', 'c4928e2a5f833358116b29d2d669888d', '50c68a29c3ebc275db3095d06bd87100'],@@ -52,7 +52,7 @@ const EXPECTED_STAGE_OLD = {const EXPECTED_STAGE_NEW = {'pipeline-idea-expansion.md': 'd6fa86a435f978336661dcabca67258f','pipeline-prose.md': '4cb3ef48309f3673570cf80e4d544b54',- 'writers-room-continue.md': '67663696c97ebaeb23de25f7410cfdd4',+ 'writers-room-continue.md': '458dc5ff4732befc1fb90890bdc885c2','pipeline-comic-script.md': '49af30c05f008b20f6998a0f113f7d87','pipeline-teleplay.md': '2ea9974ac3803658b2314db1f5818b77','pipeline-season-episodes.md': 'a88e8e78a949b7aaf500d03314e2ea0b',diff --git a/server/lib/pipelineValidation.js b/server/lib/pipelineValidation.jsindex f9473ebdf6..d8e6067bf9 100644--- a/server/lib/pipelineValidation.js+++ b/server/lib/pipelineValidation.js@@ -71,6 +71,20 @@ export const writersRoomLiveModeSchema = z.object({dailyRenderBudget: z.number().int().min(0).max(10_000).default(20),}).strict();+// Voice exemplar / anti-exemplar passages on a Writers Room work (#2179 Writers+// Room parity). Same shape + caps as the series style guide's voice fields+// (STYLE_GUIDE_LIMITS in styleGuide.js) — `passage` is the concrete prose+// anchor ("the tuning fork"), `note` a one-line gloss of what it demonstrates+// (exemplar) or what's wrong with it (anti-exemplar). `note` is optional; the+// service sanitizer (sanitizeVoiceExemplars) drops empty passages, trims to the+// caps, and caps the list at 3 — this wire gate just bounds the shape so a+// crafted PATCH can't ship an unbounded blob. An explicit `[]` clears the list.+const writersRoomVoiceExemplarSchema = z.object({+ passage: z.string().max(2000),+ note: z.string().max(200).optional(),+}).strict();+const writersRoomVoiceExemplarsSchema = z.array(writersRoomVoiceExemplarSchema).max(3);+export const writersRoomWorkUpdateSchema = z.object({title: z.string().trim().min(1).max(300).optional(),kind: writersRoomWorkKindSchema.optional(),@@ -81,6 +95,8 @@ export const writersRoomWorkUpdateSchema = z.object({// the other knobs' defaults and clobber their stored values (Zod 4 .partial()// keeps inner defaults — see zodCompat.js). The service field-merges each knob.liveMode: partialWithoutDefaults(writersRoomLiveModeSchema).optional(),+ voiceExemplars: writersRoomVoiceExemplarsSchema.optional(),+ voiceAntiExemplars: writersRoomVoiceExemplarsSchema.optional(),}).strict();// Cursor-context payload for the live continuation suggest route. The threediff --git a/server/lib/styleGuide.js b/server/lib/styleGuide.jsindex 5b868ccef1..47097302fa 100644--- a/server/lib/styleGuide.js+++ b/server/lib/styleGuide.js@@ -126,7 +126,12 @@ function cleanTone(raw) {// tuning fork), `note` a one-line gloss of what it demonstrates (exemplar) or// what's wrong with it (anti-exemplar). Drops entries with no passage, trims to// the char caps, and caps the list length. Returns `[]` when nothing usable.-function cleanExemplars(raw) {+//+// Exported so the Writers Room (`services/writersRoom/local.js`) can carry the+// SAME voice-exemplar shape on a freeform work as the series style guide does —+// one sanitizer, one set of caps, no drift between the two surfaces (#2179+// Writers Room parity).+export function sanitizeVoiceExemplars(raw) {if (!Array.isArray(raw)) return [];const out = [];for (const item of raw) {@@ -168,8 +173,8 @@ export function sanitizeStyleGuide(raw) {const readingLevel = optReadingLevel(raw.readingLevel);const tone = cleanTone(raw.tone);const conventions = sanitizeConventions(raw.conventions);- const voiceExemplars = cleanExemplars(raw.voiceExemplars);- const voiceAntiExemplars = cleanExemplars(raw.voiceAntiExemplars);+ const voiceExemplars = sanitizeVoiceExemplars(raw.voiceExemplars);+ const voiceAntiExemplars = sanitizeVoiceExemplars(raw.voiceAntiExemplars);if (tense == null && povPerson == null && targetAudience == null && contentRating == null&& profanity == null && readingLevel == null && tone.length === 0 && conventions == null@@ -189,10 +194,15 @@ export function sanitizeStyleGuide(raw) {// anti-exemplars are appended to the house-style directives. Both are// conditional: absent exemplars render nothing (so a guide with no passages// carries no empty husk in the prompt). Returns `''` when neither is present.-function renderVoiceExemplars(styleGuide) {+//+// `carrier` is any object exposing `voiceExemplars` / `voiceAntiExemplars`+// arrays — the series style guide OR a Writers Room work manifest — so the two+// surfaces render byte-identical voice blocks (#2179 Writers Room parity).+export function renderVoiceExemplars(carrier) {+ if (!carrier || typeof carrier !== 'object') return '';const blocks = [];- const exemplars = Array.isArray(styleGuide.voiceExemplars) ? styleGuide.voiceExemplars : [];- const antiExemplars = Array.isArray(styleGuide.voiceAntiExemplars) ? styleGuide.voiceAntiExemplars : [];+ const exemplars = Array.isArray(carrier.voiceExemplars) ? carrier.voiceExemplars : [];+ const antiExemplars = Array.isArray(carrier.voiceAntiExemplars) ? carrier.voiceAntiExemplars : [];const renderPassage = (e) => (e.note ? `> ${e.passage}\n> — ${e.note}` : `> ${e.passage}`);if (exemplars.length) {blocks.push(`MATCH this voice — these passages are the tuning fork for the series' prose. Echo their rhythm, diction, and register; do not copy their content:\n${exemplars.map(renderPassage).join('\n\n')}`);diff --git a/server/lib/styleGuide.test.js b/server/lib/styleGuide.test.jsindex 1b27ea4496..28a522fe1c 100644--- a/server/lib/styleGuide.test.js+++ b/server/lib/styleGuide.test.js@@ -3,12 +3,42 @@ import {sanitizeStyleGuide,renderStyleGuide,composeStyleNotes,+ sanitizeVoiceExemplars,+ renderVoiceExemplars,PROSE_CRAFT_DOCTRINE,STYLE_GUIDE_LIMITS,VOICE_REGISTERS,VOICE_REGISTER_IDS,} from './styleGuide.js';+describe('sanitizeVoiceExemplars / renderVoiceExemplars (shared with Writers Room — #2179)', () => {+ it('drops empty passages, trims to caps, and caps the list at 3', () => {+ const cleaned = sanitizeVoiceExemplars([+ { passage: ' a real passage ', note: ' what it shows ' },+ { passage: ' ' }, // dropped+ null, // dropped+ { passage: 'p2' }, { passage: 'p3' }, { passage: 'p4' }, // 4th capped off+ ]);+ expect(cleaned).toHaveLength(3);+ expect(cleaned[0]).toEqual({ passage: 'a real passage', note: 'what it shows' });+ expect(cleaned[1]).toEqual({ passage: 'p2' }); // no note key when absent+ expect(sanitizeVoiceExemplars('not-an-array')).toEqual([]);+ });++ it('renders MATCH / NEVER blocks from a plain carrier, and empty string when absent', () => {+ expect(renderVoiceExemplars(null)).toBe('');+ expect(renderVoiceExemplars({})).toBe('');+ const block = renderVoiceExemplars({+ voiceExemplars: [{ passage: 'terse, exact', note: 'the target' }],+ voiceAntiExemplars: [{ passage: 'ornate and purple', note: 'too much' }],+ });+ expect(block).toContain('MATCH this voice');+ expect(block).toContain('terse, exact');+ expect(block).toContain('NEVER drift toward this');+ expect(block).toContain('too much');+ });+});+describe('VOICE_REGISTERS (voice discovery — #2179)', () => {it('exposes a small, non-empty set of registers with stable ids + labels + hints', () => {expect(VOICE_REGISTERS.length).toBeGreaterThanOrEqual(3);diff --git a/server/services/writersRoom/liveDirector.js b/server/services/writersRoom/liveDirector.jsindex 5b7e9ebf35..ab51a85e26 100644--- a/server/services/writersRoom/liveDirector.js+++ b/server/services/writersRoom/liveDirector.js@@ -17,7 +17,7 @@ import { ServerError } from '../../lib/errorHandler.js';import { runStagedLLM } from '../../lib/stageRunner.js';import {getWork, resolveLiveMode, recordLiveModeUsage, recordLiveModeRenderUsage, utcDayKey,- linkToCreativeDirector,+ linkToCreativeDirector, renderWorkVoiceGuide,} from './local.js';import { createProject, setTreatment, deleteProject, updateProject } from '../creativeDirector/local.js';import { deleteCollection } from '../mediaCollections.js';@@ -95,6 +95,12 @@ export async function suggestContinuation(workId, { before = '', after = '', selconst variables = {work: { title: manifest.title, kind: manifest.kind, status: manifest.status },before, after, selection,+ // Voice exemplars (#2179) — the "tuning fork" passages anchor the drafted+ // continuation to the chosen voice far better than the template's generic+ // "match the established voice" line. Empty string when the work carries no+ // passages, so the continue template's {{#voiceGuide}} section renders+ // nothing (no per-call overhead for works that never set a voice).+ voiceGuide: renderWorkVoiceGuide(manifest),returnsJson: true,};const { content } = await runStagedLLM(STAGE, variables, {diff --git a/server/services/writersRoom/liveDirector.test.js b/server/services/writersRoom/liveDirector.test.jsindex 688546d122..7e0525a62e 100644--- a/server/services/writersRoom/liveDirector.test.js+++ b/server/services/writersRoom/liveDirector.test.js@@ -83,6 +83,24 @@ describe('suggestContinuation', () => {expect(runStagedLLM).toHaveBeenCalledOnce();});+ it('injects the work voice guide into the continue prompt when exemplars are set, empty otherwise (#2179)', async () => {+ runStagedLLM.mockResolvedValue(OPTIONS_RESPONSE);+ const work = await createWork({ title: 'Voiced' });+ await updateWork(work.id, { liveMode: { enabled: true } });++ // No exemplars → voiceGuide is empty (the template's {{#voiceGuide}} renders nothing).+ await suggestContinuation(work.id, { before: 'The door creaked open.' });+ expect(runStagedLLM.mock.calls[0][1].voiceGuide).toBe('');++ await updateWork(work.id, {+ voiceExemplars: [{ passage: 'She counted the exits, then the lies.', note: 'terse' }],+ });+ await suggestContinuation(work.id, { before: 'The door creaked open.' });+ const vars = runStagedLLM.mock.calls[1][1];+ expect(vars.voiceGuide).toContain('MATCH this voice');+ expect(vars.voiceGuide).toContain('She counted the exits, then the lies.');+ });+it('charges budget even when the model returns zero usable options', async () => {// The LLM cost is incurred regardless of whether the response parsed into// usable options — sparing zero-option calls would open an unbounded-calldiff --git a/server/services/writersRoom/local.js b/server/services/writersRoom/local.jsindex 3537179e72..329e1ffb76 100644--- a/server/services/writersRoom/local.js+++ b/server/services/writersRoom/local.js@@ -19,6 +19,7 @@ import { readFile, rm } from 'fs/promises';import { atomicWrite, ensureDir } from '../../lib/fileUtils.js';import { countWords } from '../../lib/textUtils.js';import { WORK_KINDS, WORK_STATUSES } from '../../lib/writersRoomPresets.js';+import { sanitizeVoiceExemplars, renderVoiceExemplars } from '../../lib/styleGuide.js';import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';import { nowIso, badRequest, notFound, wrWorkDir, wrDraftPath } from './_shared.js';import { writersRoomStore } from './store.js';@@ -363,6 +364,19 @@ export async function updateWork(id, patch) {renderUsage: current.renderUsage,};}+ // Voice exemplars / anti-exemplars (#2179 Writers Room parity). Sanitized+ // through the SAME helper the series style guide uses (drops empty passages,+ // trims to the char caps, caps the list at 3). Key present → replace (an+ // explicit `[]` clears); key absent → carry the stored value untouched. These+ // are consumed by the live-continuation prompt and the Phase 9 polish loop's+ // revision brief so a freeform work anchors its voice the same way a series+ // does.+ if (patch.voiceExemplars !== undefined) {+ next.voiceExemplars = sanitizeVoiceExemplars(patch.voiceExemplars);+ }+ if (patch.voiceAntiExemplars !== undefined) {+ next.voiceAntiExemplars = sanitizeVoiceExemplars(patch.voiceAntiExemplars);+ }// Trim title and reject if it becomes empty after trim — keeps parity with// createWork's "title required" guard so a PATCH can't blank a title out.if (patch.title !== undefined) {@@ -380,6 +394,21 @@ export async function updateWork(id, patch) {return next;}+/**+ * Resolve a work's voice exemplars into the rendered "MATCH this voice / NEVER+ * drift toward this" prompt block (#2179 Writers Room parity), or `''` when the+ * work carries no passages. Re-sanitizes on read (defense against a hand-edited+ * manifest) and delegates to the shared styleGuide renderer so the block is+ * byte-identical to the series pipeline's. Consumed by the live-continuation+ * suggest path (liveDirector.js) and the Phase 9 polish loop (polish.js).+ */+export function renderWorkVoiceGuide(manifest) {+ return renderVoiceExemplars({+ voiceExemplars: sanitizeVoiceExemplars(manifest?.voiceExemplars),+ voiceAntiExemplars: sanitizeVoiceExemplars(manifest?.voiceAntiExemplars),+ });+}+/*** Bidirectional bridge link: record that this work was promoted to a pipeline* series + first issue. Set once by `promoteToPipeline`; the WR side reads itdiff --git a/server/services/writersRoom/local.test.js b/server/services/writersRoom/local.test.jsindex 3dbf85014f..357ccecae5 100644--- a/server/services/writersRoom/local.test.js+++ b/server/services/writersRoom/local.test.js@@ -19,6 +19,7 @@ const {saveDraftBody, snapshotDraft, setActiveDraft, getDraftBody,listExercises, createExercise, finishExercise, discardExercise,resolveLiveMode, recordLiveModeUsage, recordLiveModeRenderUsage, DEFAULT_LIVE_MODE,+ renderWorkVoiceGuide,} = local;beforeEach(() => {@@ -155,6 +156,36 @@ describe('work CRUD', () => {expect(reloaded.title).toBe('Keep');});+ it('updateWork sanitizes and stores voice exemplars, and renders the voice guide (#2179)', async () => {+ const work = await createWork({ title: 'Voiced' });+ // renderWorkVoiceGuide is empty until exemplars are set.+ expect(renderWorkVoiceGuide(await getWork(work.id))).toBe('');++ const updated = await updateWork(work.id, {+ voiceExemplars: [+ { passage: 'She counted the exits, then the lies.', note: 'terse interiority' },+ { passage: ' ' }, // dropped: no usable passage+ ],+ voiceAntiExemplars: [+ { passage: 'The gossamer light danced upon the ancient stones of yore.', note: 'too ornate' },+ ],+ });+ expect(updated.voiceExemplars).toHaveLength(1);+ expect(updated.voiceExemplars[0]).toEqual({ passage: 'She counted the exits, then the lies.', note: 'terse interiority' });+ expect(updated.voiceAntiExemplars).toHaveLength(1);++ const guide = renderWorkVoiceGuide(await getWork(work.id));+ expect(guide).toContain('MATCH this voice');+ expect(guide).toContain('She counted the exits, then the lies.');+ expect(guide).toContain('NEVER drift toward this');+ expect(guide).toContain('too ornate');++ // An explicit empty array clears the list; an absent key leaves it untouched.+ const cleared = await updateWork(work.id, { voiceExemplars: [] });+ expect(cleared.voiceExemplars).toEqual([]);+ expect(cleared.voiceAntiExemplars).toHaveLength(1); // untouched+ });+it('updateWork rejects unknown folderId and accepts null', async () => {const work = await createWork({ title: 'Filed' });await expect(updateWork(work.id, { folderId: 'wr-folder-does-not-exist' }))diff --git a/server/services/writersRoom/polish.js b/server/services/writersRoom/polish.jsindex 6158f7c530..5feea0111a 100644--- a/server/services/writersRoom/polish.js+++ b/server/services/writersRoom/polish.js@@ -23,7 +23,7 @@ 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 { getWorkWithBody, saveDraftBody, countWords, renderWorkVoiceGuide } from './local.js';import { nowIso, badRequest, notFound, assertValidWorkId, wrWorkDir } from './_shared.js';// ---------- tunables ----------@@ -86,8 +86,14 @@ export function mapFindingsToCuts(findings) {* 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.+ *+ * `voiceGuide` (#2179 Writers Room parity) is the rendered "MATCH this voice /+ * NEVER drift toward this" exemplar block for the work — when present it's+ * folded into the VOICE RULES section so the rewrite is anchored to the chosen+ * voice (the tuning fork), not just told to "match the existing voice." Empty+ * string (a work with no exemplars) adds nothing.*/-export function buildRevisionBrief({ evaluate = {}, cuts = {}, wordCount = 0 } = {}) {+export function buildRevisionBrief({ evaluate = {}, cuts = {}, wordCount = 0, voiceGuide = '' } = {}) {const lines = [];const issues = Array.isArray(evaluate.issues) ? evaluate.issues : [];const strengths = Array.isArray(evaluate.strengths) ? evaluate.strengths : [];@@ -133,6 +139,9 @@ export function buildRevisionBrief({ evaluate = {}, cuts = {}, wordCount = 0 } =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.');+ if (typeof voiceGuide === 'string' && voiceGuide.trim()) {+ lines.push('', voiceGuide.trim());+ }lines.push('', '## TARGET');lines.push(`- Aim for roughly ${wordCount} words — tightened. Do NOT pad back the fat that was cut.`);@@ -274,6 +283,9 @@ export function startPolish(workId, opts = {}) {const loaded = await getWorkWithBody(workId);let body = loaded.body || '';const ctx = () => workContext(loaded.manifest, body);+ // The work's voice exemplars (#2179) — rendered once and folded into every+ // cycle's revision brief so the rewrite is anchored to the chosen voice.+ const voiceGuide = renderWorkVoiceGuide(loaded.manifest);// Baseline evaluation + snapshot.broadcast({ type: 'phase', cycle: 0, phase: 'evaluate', label: 'Baseline evaluation' });@@ -319,7 +331,7 @@ export function startPolish(workId, opts = {}) {// 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 brief = buildRevisionBrief({ evaluate: preEval, cuts: cutsResult, wordCount: countWords(cutBody), voiceGuide });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; }diff --git a/server/services/writersRoom/polish.test.js b/server/services/writersRoom/polish.test.jsindex 553807f2f2..bda8a43203 100644--- a/server/services/writersRoom/polish.test.js+++ b/server/services/writersRoom/polish.test.js@@ -123,6 +123,25 @@ describe('buildRevisionBrief', () => {// A safe-type cut is auto-applied elsewhere; only NON-safe types land in the brief.expect(brief).toContain('gilded gossamer glory');});++ it('folds the work voice guide into VOICE RULES when present (#2179)', () => {+ const voiceGuide = 'MATCH this voice — these passages are the tuning fork:\n> She counted the exits, then the lies.';+ const brief = buildRevisionBrief({ evaluate: {}, cuts: {}, wordCount: 800, voiceGuide });+ const voiceIdx = brief.indexOf('## VOICE RULES');+ expect(voiceIdx).toBeGreaterThan(-1);+ // The exemplar block lands inside the VOICE RULES section, after the generic+ // "match the existing voice" line — not spilling into TARGET.+ expect(brief.indexOf('the tuning fork')).toBeGreaterThan(voiceIdx);+ expect(brief.indexOf('the tuning fork')).toBeLessThan(brief.indexOf('## TARGET'));+ expect(brief).toContain('She counted the exits, then the lies.');+ });++ it('adds nothing to VOICE RULES when the voice guide is empty (#2179)', () => {+ const withEmpty = buildRevisionBrief({ evaluate: {}, cuts: {}, wordCount: 800, voiceGuide: ' ' });+ const without = buildRevisionBrief({ evaluate: {}, cuts: {}, wordCount: 800 });+ expect(withEmpty).toBe(without);+ expect(without).not.toContain('tuning fork');+ });});describe('resolvePolishOptions', () => {