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: AI voice-discovery flow for series style guide (#2179)
Adam Eivye3252b72c0be
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex ac27feefff..7b7459b946 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -36,6 +36,8 @@- **[issue-2177] Prose drafts now flow across issue boundaries instead of each issue opening and closing in a vacuum.** When drafting an issue's prose, the generator now injects the previous issue's actual closing prose (its last ~2000 characters) and the next issue's opening beats into the draft prompt — with guidance to open so it flows from the previous ending (without repeating its closing image or re-explaining what the reader just read) and to land the ending so it hands off to the next issue's beats. This is what keeps the narrative voice carrying across units and prevents the "every issue opens/closes the same way" tic, improving the autonomous first draft so the editorial loop has less to fix. Both blocks are token-budgeted (they degrade by trimming on a small-context local model rather than erroring), and when the previous issue hasn't been drafted yet — non-linear or parallel generation, or the first issue of a volume — the block simply doesn't render, so there's never any fabricated continuity. Every full prose (re)generation path gets it: the manual draft button, the auto-runner, and Series Autopilot. Existing installs auto-upgrade their prose prompt (a customized prompt is left untouched and flagged).- **[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-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- **[issue-2150] Activity timeline** — a new `/timeline` page shows a unified, day-by-day view of your activity (emails sent/received and calendar events, with more sources coming), backed by a machine-local `human_activity_events` store that your existing message and calendar syncs populate automatically. Pick any day (deep-linkable via `/timeline/:date`), see an hourly activity histogram and per-source tallies, and browse the day's events. Only metadata and a short summary line are stored — full message bodies stay in their per-source caches — and the timeline is machine-local (never federated to peers), like Tribe.diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsxindex 5b7d6b9f3a..56b8ad3a24 100644--- a/client/src/pages/PipelineSeries.jsx+++ b/client/src/pages/PipelineSeries.jsx@@ -15,7 +15,7 @@ import { Link, useParams, useNavigate } from 'react-router-dom';import {ArrowLeft, Save, Loader2, Workflow as WorkflowIcon, Globe, NotebookPen,PanelLeftClose, PanelLeftOpen, Sparkles, BookOpen, FileInput, Compass, BookMarked,- Fingerprint, Plus, Trash2,+ Fingerprint, Plus, Trash2, Wand2, Check, X,} from 'lucide-react';import toast from '../components/ui/Toast';import ArcCanvas from '../components/pipeline/ArcCanvas';@@ -27,6 +27,7 @@ import {listPipelineIssues,listUniverses,generateSeriesTitleLogo,+ discoverSeriesVoice,SERIES_TITLE_LOGO_MAX,} from '../services/api';import AuthorPicker from '../components/pipeline/AuthorPicker';@@ -402,7 +403,7 @@ function BibleSidebar({ series, universes, patchSeries, onSeriesUpdate, onFlushP/></Field>- <StyleGuideSection series={series} patchSeries={patchSeries} />+ <StyleGuideSection series={series} patchSeries={patchSeries} onFlushPending={onFlushPending} /><FactReferenceSection series={series} patchSeries={patchSeries} />@@ -520,12 +521,64 @@ function BibleSidebar({ series, universes, patchSeries, onSeriesUpdate, onFlushP// persisted on Save (styleGuide is in ARC_FLUSH_FIELDS). Picking the blank// option clears a field to null; the server collapses an all-empty guide to// null. Each control is htmlFor/id paired for screen readers + click-to-focus.-function StyleGuideSection({ series, patchSeries }) {+function StyleGuideSection({ series, patchSeries, onFlushPending }) {const sg = series.styleGuide || {};const conv = sg.conventions || {};const setSG = (patch) => patchSeries({ styleGuide: pruneEmpty({ ...sg, ...patch }) });const setConv = (patch) => setSG({ conventions: pruneEmpty({ ...conv, ...patch }) });+ const exemplars = Array.isArray(sg.voiceExemplars) ? sg.voiceExemplars : [];+ const antiExemplars = Array.isArray(sg.voiceAntiExemplars) ? sg.voiceAntiExemplars : [];+ const setExemplars = (next) => setSG({ voiceExemplars: next.length ? next : null });+ const setAntiExemplars = (next) => setSG({ voiceAntiExemplars: next.length ? next : null });++ // Voice discovery (#2179) — generate ~5 trial passages in distinct registers,+ // hold them locally, let the user file each one into exemplars / anti-exemplars.+ const [discovering, setDiscovering] = useState(false);+ const [candidates, setCandidates] = useState([]);+ // Track which candidate registers the user has already filed so a second click+ // doesn't silently duplicate a row (and the button reads "Added").+ const [filed, setFiled] = useState({});++ const runDiscover = async () => {+ // The server reads the series from disk — flush dirty premise/style edits so+ // the trial passages reflect what the user is actually looking at.+ if (onFlushPending) await onFlushPending();+ setDiscovering(true);+ const result = await discoverSeriesVoice(series.id, {}, { silent: true }).catch((err) => {+ toast.error(err.message || 'Voice discovery failed — try again or pick a different provider.');+ return null;+ });+ setDiscovering(false);+ if (!result) return;+ setCandidates(Array.isArray(result.candidates) ? result.candidates : []);+ setFiled({});+ if (!result.candidates?.length) toast.error('No usable passages came back — try again.');+ };++ // Convert a discovery candidate to a `{ passage, note }` exemplar row. The note+ // records the register so a picked passage carries a self-describing gloss.+ const toEntry = (cand) => {+ const note = cand.note || (cand.label ? cand.label.toLowerCase() : '');+ return note ? { passage: cand.passage, note } : { passage: cand.passage };+ };+ const fileExemplar = (cand) => {+ if (exemplars.length >= STYLE_GUIDE_EXEMPLARS_MAX) {+ toast.error(`Voice exemplars are capped at ${STYLE_GUIDE_EXEMPLARS_MAX} — remove one first.`);+ return;+ }+ setExemplars([...exemplars, toEntry(cand)]);+ setFiled((f) => ({ ...f, [cand.register]: 'exemplar' }));+ };+ const fileAntiExemplar = (cand) => {+ if (antiExemplars.length >= STYLE_GUIDE_EXEMPLARS_MAX) {+ toast.error(`Anti-exemplars are capped at ${STYLE_GUIDE_EXEMPLARS_MAX} — remove one first.`);+ return;+ }+ setAntiExemplars([...antiExemplars, toEntry(cand)]);+ setFiled((f) => ({ ...f, [cand.register]: 'anti' }));+ };+return (<div className="block"><h3 className="text-xs uppercase tracking-wider text-gray-500 mb-2">Style guide (house style)</h3>@@ -594,13 +647,44 @@ function StyleGuideSection({ series, patchSeries }) {))}</div>+ <div className="mt-3 pt-3 border-t border-port-border/60">+ <div className="flex items-center justify-between gap-2">+ <div>+ <h4 className="text-[11px] uppercase tracking-wider text-gray-500">Discover voice</h4>+ <p className="text-[11px] text-gray-500 -mt-0.5">Write the same scene beat in distinct registers, then file the one you like as an exemplar.</p>+ </div>+ <button+ type="button"+ onClick={runDiscover}+ disabled={discovering}+ className="shrink-0 inline-flex items-center gap-1.5 px-2 py-1 text-xs rounded border border-port-border text-port-accent hover:bg-port-accent/10 disabled:opacity-50"+ >+ {discovering ? <Loader2 size={12} className="animate-spin" /> : <Wand2 size={12} />}+ {discovering ? 'Writing…' : 'Discover voice'}+ </button>+ </div>+ {candidates.length > 0 && (+ <div className="mt-2 space-y-2">+ {candidates.map((cand) => (+ <VoiceCandidateCard+ key={cand.register}+ candidate={cand}+ filedAs={filed[cand.register]}+ onFileExemplar={() => fileExemplar(cand)}+ onFileAntiExemplar={() => fileAntiExemplar(cand)}+ />+ ))}+ </div>+ )}+ </div>+<VoiceExemplarEditoridPrefix="sg-voice-exemplar"title="Voice exemplars (the tuning fork)"hint="1–3 short passages (~150–300 words) that nail the series' voice. Injected into every draft/revision prompt as “MATCH this voice”. A concrete anchor beats any adjective list."notePlaceholder="what this demonstrates (e.g. spare, close-psychic)"- entries={Array.isArray(sg.voiceExemplars) ? sg.voiceExemplars : []}- onChange={(next) => setSG({ voiceExemplars: next.length ? next : null })}+ entries={exemplars}+ onChange={setExemplars}/><VoiceExemplarEditor@@ -608,13 +692,50 @@ function StyleGuideSection({ series, patchSeries }) {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={Array.isArray(sg.voiceAntiExemplars) ? sg.voiceAntiExemplars : []}- onChange={(next) => setSG({ voiceAntiExemplars: next.length ? next : null })}+ entries={antiExemplars}+ onChange={setAntiExemplars}/></div>);}+// One discovered voice candidate (#2179) — a register-labeled trial passage the+// user can file into the exemplar or anti-exemplar list. Once filed, the buttons+// collapse to a confirmation so a second click can't silently duplicate the row.+function VoiceCandidateCard({ candidate, filedAs, onFileExemplar, onFileAntiExemplar }) {+ return (+ <div className="border border-port-border rounded p-2 bg-port-bg/50">+ <div className="flex items-center justify-between gap-2 mb-1">+ <span className="text-[11px] font-medium text-port-accent">{candidate.label || candidate.register}</span>+ {filedAs ? (+ <span className="inline-flex items-center gap-1 text-[11px] text-port-success">+ <Check size={11} /> {filedAs === 'anti' ? 'Added as anti-exemplar' : 'Added as exemplar'}+ </span>+ ) : (+ <div className="flex items-center gap-1">+ <button+ type="button"+ onClick={onFileExemplar}+ className="inline-flex items-center gap-1 px-1.5 py-0.5 text-[11px] rounded text-port-success hover:bg-port-success/10"+ >+ <Check size={11} /> Exemplar+ </button>+ <button+ type="button"+ onClick={onFileAntiExemplar}+ className="inline-flex items-center gap-1 px-1.5 py-0.5 text-[11px] rounded text-port-error hover:bg-port-error/10"+ >+ <X size={11} /> Anti+ </button>+ </div>+ )}+ </div>+ <p className="text-xs text-gray-300 whitespace-pre-wrap font-mono leading-snug max-h-40 overflow-y-auto">{candidate.passage}</p>+ {candidate.note && <p className="text-[11px] text-gray-500 mt-1 italic">{candidate.note}</p>}+ </div>+ );+}+// 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 atdiff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex 29dab034c0..40ba7632f8 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -112,6 +112,18 @@ export const generateSeriesConcept = (universeId, opts = {}, requestOptions = {}...requestOptions,});+// Voice discovery (#2179): write the same scene beat in several distinct+// registers so the author picks the series voice by ear. Returns+// `{ candidates: [{ register, label, passage, note }] }` WITHOUT persisting —+// the picked passage is committed via the ordinary series PATCH+// (styleGuide.voiceExemplars).+export const discoverSeriesVoice = (id, opts = {}, requestOptions = {}) =>+ request(`/pipeline/series/${encodeURIComponent(id)}/discover-voice`, {+ method: 'POST',+ body: JSON.stringify(opts),+ ...requestOptions,+ });+// Mirror server caps in `server/services/pipeline/series.js` — bump both sides.export const SERIES_TITLE_LOGO_MAX = 2000;export const SERIES_AUTHOR_MAX = 120;diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex a822219cfd..975fdf1922 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -464,6 +464,13 @@"returnsJson": true,"variables": []},+ "pipeline-series-voice-discover": {+ "name": "Pipeline — Discover Series Voice",+ "description": "Voice discovery (#2179, CWQE Phase 14): writes the SAME short scene beat in several distinct registers (spare / lyric / wry / close-psychic / cinematic) so the author picks the series voice by ear. Returns a {candidates:[{register, passage, note}]} JSON payload; the picked passage lands in the style guide's voiceExemplars, rejected ones can drop into voiceAntiExemplars. Explicit user-triggered action — does NOT persist and does NOT fire on boot.",+ "model": "default",+ "returnsJson": true,+ "variables": []+ },"pipeline-comic-panel-image-prompt": {"name": "Pipeline — Comic Panel Image Prompt","description": "Refine a single comic panel's description into a richer image-gen-ready prompt. Uses caption / dialogue / sfx context + neighboring-panel continuity to elaborate without re-imagining the scene.",diff --git a/data.reference/prompts/stages/pipeline-series-voice-discover.md b/data.reference/prompts/stages/pipeline-series-voice-discover.mdnew file mode 100644index 0000000000..01103c55d7--- /dev/null+++ b/data.reference/prompts/stages/pipeline-series-voice-discover.md@@ -0,0 +1,55 @@+# Pipeline — Discover Series Voice++You are a prose stylist helping an author *find* the voice for a series. A concrete prose passage anchors a voice far better than any adjective list ("witty, atmospheric") — so instead of describing the voice, you will **write it**, several ways, and let the author pick by ear.++Write the **same short scene beat** — one small, self-contained moment invented to fit the series below (a character arriving somewhere, noticing something, a brief exchange; ~150–250 words) — once in **each** of the registers listed. Same beat, same content, same character(s): only the *voice* changes between passages, so the author is comparing pure register, not different scenes.++## Series++- **Name:** {{series.name}}+- **Logline:** {{series.logline}}+- **Premise:** {{series.premise}}++{{#series.styleContext}}+### Established tone / house style (honor this — the register is a variation *within* it, not a contradiction of it)++{{series.styleContext}}+{{/series.styleContext}}++{{#hasUniverse}}+## Universe (the shared world this series lives in)++- **Name:** {{universe.name}}+- **Premise:** {{universe.premise}}+- **Embrace influences:** {{universe.embrace}}+- **Avoid influences:** {{universe.avoid}}+{{/hasUniverse}}++## Registers — write one passage for each++{{registers}}++## Rules++- **Same beat in every passage.** Do not invent a different scene per register — the author is auditioning *voice*, so hold the content fixed and vary only diction, rhythm, and register.+- Stay inside the series' premise and (if present) the established tone — the register is a *lens* on the world, not a genre swap.+- Each passage is standalone prose (no headings, no "Register:" labels inside the text) of roughly 150–250 words, and never longer than {{passageMaxChars}} characters.+- Write real prose the author could paste straight into the style guide as an exemplar — not a description of how the passage *would* sound.+- Emit exactly one candidate per register id below, using the id verbatim.++## Output++Return ONLY valid JSON in this exact shape:++```json+{+ "candidates": [+ {+ "register": "<one register id from the list above>",+ "passage": "<the scene beat written in that register, ~150–250 words>",+ "note": "<one short phrase on what this register does for the series, e.g. 'spare, close-psychic'>"+ }+ ],+ "rationale": "<one short sentence for the author on which register you'd lean toward and why — not stored>"+}+```diff --git a/server/lib/styleGuide.js b/server/lib/styleGuide.jsindex a16c9a1ab3..5b868ccef1 100644--- a/server/lib/styleGuide.js+++ b/server/lib/styleGuide.js@@ -55,6 +55,22 @@ export const PROSE_CRAFT_DOCTRINE = Object.freeze(['- Vary sentence length and rhythm on purpose — short for impact, longer to build; never let every sentence fall into the same cadence.',].join('\n'));+// Voice-discovery registers (#2179, CWQE Phase 14) — the distinct prose voices+// the "Discover voice" flow renders the SAME scene beat in, so the user (or the+// autonomous judge) can pick the one that fits by ear rather than by adjective.+// `id` is stable (persisted into the discovery result); `label`/`hint` steer+// the LLM and the side-by-side UI. Kept small and opinionated — 5 registers is+// the autonovel "~5 trial passages" default, enough contrast without a wall of+// near-identical drafts.+export const VOICE_REGISTERS = Object.freeze([+ { id: 'spare', label: 'Spare', hint: 'lean, plain, Hemingway-terse — short declaratives, concrete nouns, almost no adjectives' },+ { id: 'lyric', label: 'Lyric', hint: 'lush and musical — rhythmic, image-dense, sentences that build and breathe' },+ { id: 'wry', label: 'Wry', hint: 'dry, ironic, quietly funny — understatement and a knowing narrator' },+ { id: 'close-psychic', label: 'Close-psychic', hint: 'deep interiority — the narration lives inside the POV character\'s thoughts and sensations' },+ { id: 'cinematic', label: 'Cinematic', hint: 'camera-eye, present and kinetic — blocking, motion, and sensory cuts like a shooting script' },+]);+export const VOICE_REGISTER_IDS = Object.freeze(VOICE_REGISTERS.map((r) => r.id));+export const STYLE_GUIDE_TENSES = Object.freeze(['past', 'present']);export const STYLE_GUIDE_POV_PERSONS = Object.freeze(['first', 'third-limited', 'third-omniscient', 'second']);export const STYLE_GUIDE_AUDIENCES = Object.freeze(['children', 'middle-grade', 'YA', 'adult']);diff --git a/server/lib/styleGuide.test.js b/server/lib/styleGuide.test.jsindex 02e74fcf34..1b27ea4496 100644--- a/server/lib/styleGuide.test.js+++ b/server/lib/styleGuide.test.js@@ -5,8 +5,28 @@ import {composeStyleNotes,PROSE_CRAFT_DOCTRINE,STYLE_GUIDE_LIMITS,+ VOICE_REGISTERS,+ VOICE_REGISTER_IDS,} from './styleGuide.js';+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);+ for (const r of VOICE_REGISTERS) {+ expect(typeof r.id).toBe('string');+ expect(r.id).toMatch(/^[a-z-]+$/);+ expect(r.label.length).toBeGreaterThan(0);+ expect(r.hint.length).toBeGreaterThan(0);+ }+ });++ it('has unique register ids that VOICE_REGISTER_IDS mirrors in order', () => {+ const ids = VOICE_REGISTERS.map((r) => r.id);+ expect(new Set(ids).size).toBe(ids.length);+ expect(VOICE_REGISTER_IDS).toEqual(ids);+ });+});+describe('sanitizeStyleGuide', () => {it('returns null for absent / non-object / empty input (legacy-tolerant)', () => {expect(sanitizeStyleGuide(undefined)).toBeNull();diff --git a/server/routes/pipeline/series.js b/server/routes/pipeline/series.jsindex c6bde729e3..79112807c8 100644--- a/server/routes/pipeline/series.js+++ b/server/routes/pipeline/series.js@@ -16,6 +16,7 @@ import { mergeSeries } from '../../services/recordMerge.js';import { mergeFieldsWithAI } from '../../services/recordMergeAI.js';import { generateSeriesTitleLogo } from '../../services/pipeline/seriesTitleLogo.js';import { generateSeriesConcept } from '../../services/pipeline/seriesGenerate.js';+import { discoverSeriesVoice } from '../../services/pipeline/seriesVoiceDiscover.js';import {LENGTH_PROFILE_NAMES,CUSTOM_PAGE_MIN, CUSTOM_PAGE_MAX, CUSTOM_MINUTE_MIN, CUSTOM_MINUTE_MAX,@@ -456,6 +457,22 @@ router.post('/series/:id/generate-title-logo', asyncHandler(async (req, res) =>res.json(result);}));+// Voice discovery (#2179, CWQE Phase 14): write the same scene beat in several+// distinct registers so the author picks the series voice by ear. Returns the+// candidate passages WITHOUT persisting — the user's pick is committed via the+// ordinary series PATCH (styleGuide.voiceExemplars). Reuses the LLM+// provider/model override shape.+const voiceDiscoverSchema = z.object({+ providerId: z.string().trim().max(80).optional(),+ model: z.string().trim().max(200).optional(),+});+router.post('/series/:id/discover-voice', asyncHandler(async (req, res) => {+ const body = validateRequest(voiceDiscoverSchema, req.body ?? {});+ const result = await discoverSeriesVoice(req.params.id, body)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));+router.get('/series/:id/issues', asyncHandler(async (req, res) => {// Validate the series exists so a typo returns 404 instead of [] (less// confusing for the UI).diff --git a/server/services/pipeline/seriesVoiceDiscover.js b/server/services/pipeline/seriesVoiceDiscover.jsnew file mode 100644index 0000000000..15b62bdc25--- /dev/null+++ b/server/services/pipeline/seriesVoiceDiscover.js@@ -0,0 +1,136 @@+/**+ * Pipeline — Series Voice Discovery (#2179, CWQE Phase 14).+ *+ * The phase headline: concrete prose anchors the voice far better than an+ * adjective list ("witty, atmospheric") ever can, so instead of asking the user+ * to *describe* the voice we let them *hear* it. Given a series + its linked+ * universe, this runs ONE LLM call that writes the SAME short scene beat in each+ * of the distinct registers in `VOICE_REGISTERS` (spare / lyric / wry /+ * close-psychic / cinematic). The user (or, in autonomous mode, the calibrated+ * judge) picks the passage that fits by ear — the picked one lands in+ * `voiceExemplars` ("the tuning fork"), rejected ones can drop into+ * `voiceAntiExemplars`.+ *+ * Like `generateSeriesConcept`, this does NOT persist anything — it returns+ * candidates the UI presents side-by-side; the user's pick is committed via the+ * ordinary series PATCH (styleGuide.voiceExemplars). This is an explicit+ * user-triggered action, so it satisfies the "no cold-bootstrap LLM calls" AI+ * policy — nothing here fires on boot or in a background job.+ *+ * Throws ServerError(502, PIPELINE_VOICE_DISCOVER_EMPTY) on unusable output —+ * matches the other refine helpers' error shape so the UI surfaces a uniform+ * "try again" toast.+ */++import { getSeries, NAME_MAX } from './series.js';+import { getUniverse, joinInfluenceList } from '../universeBuilder.js';+import { runPromptRefineRaw } from './refineHelpers.js';+import { ServerError } from '../../lib/errorHandler.js';+import {+ VOICE_REGISTERS, VOICE_REGISTER_IDS, STYLE_GUIDE_LIMITS, composeStyleNotes,+} from '../../lib/styleGuide.js';++// Render the register menu into the prompt: one bullet per register the model+// must write a passage for, keyed by the stable id it echoes back.+const REGISTERS_BLOCK = VOICE_REGISTERS+ .map((r) => `- \`${r.id}\` (${r.label}): ${r.hint}`)+ .join('\n');++function buildContext(series, universe) {+ // The composed style guide + free-text notes give the model the world's tone —+ // but we strip any EXISTING voice exemplars/anti-exemplars first. composeStyleNotes+ // otherwise folds them in as "MATCH this voice" / "NEVER drift toward this"+ // blocks, which would homogenize a re-run's trial passages toward the+ // already-picked voice — the opposite of discovery, whose whole point is to+ // surface deliberately contrasting registers. So the register hints supply the+ // contrast; the tone/notes supply the world.+ const guide = series?.styleGuide;+ const seriesForContext = guide+ ? { ...series, styleGuide: { ...guide, voiceExemplars: [], voiceAntiExemplars: [] } }+ : series;+ const styleContext = composeStyleNotes(seriesForContext) || '';+ return {+ series: {+ name: (series.name || '').slice(0, NAME_MAX),+ logline: (series.logline || '').slice(0, 500),+ premise: (series.premise || '').slice(0, 4000),+ styleContext: styleContext.slice(0, 4000),+ },+ hasUniverse: !!universe,+ universe: {+ name: (universe?.name || '').slice(0, 200),+ premise: (universe?.premise || '').slice(0, 2000),+ embrace: joinInfluenceList(universe?.influences?.embrace) || '(none)',+ avoid: joinInfluenceList(universe?.influences?.avoid) || '(none)',+ },+ registers: REGISTERS_BLOCK,+ // Passages are exemplar-length by construction — reuse the exemplar cap so a+ // picked candidate never overflows the styleGuide sanitizer on commit.+ passageMaxChars: STYLE_GUIDE_LIMITS.EXEMPLAR_PASSAGE_MAX,+ };+}++// Normalize one LLM candidate to `{ register, label, passage, note }`. Drops a+// candidate whose register id we don't recognize or whose passage is empty —+// the caller filters nulls out. `passage` is clamped to the exemplar char cap+// so a committed pick round-trips cleanly through `cleanExemplars`.+function normalizeCandidate(raw) {+ if (raw == null || typeof raw !== 'object') return null;+ const registerId = typeof raw.register === 'string' ? raw.register.trim() : '';+ const meta = VOICE_REGISTERS.find((r) => r.id === registerId);+ if (!meta) return null;+ const passage = typeof raw.passage === 'string'+ ? raw.passage.trim().slice(0, STYLE_GUIDE_LIMITS.EXEMPLAR_PASSAGE_MAX)+ : '';+ if (!passage) return null;+ const note = typeof raw.note === 'string'+ ? raw.note.trim().slice(0, STYLE_GUIDE_LIMITS.EXEMPLAR_NOTE_MAX)+ : '';+ return note ? { register: meta.id, label: meta.label, passage, note }+ : { register: meta.id, label: meta.label, passage };+}++export async function discoverSeriesVoice(seriesId, options = {}) {+ // getSeries throws the pipeline series NOT_FOUND code, which the route's+ // mapServiceError already translates to a 404 — so a stale id reads as bad+ // input, not a server fault.+ const series = await getSeries(seriesId);+ const universe = series.universeId+ ? await getUniverse(series.universeId).catch(() => null)+ : null;+ const emptyError = {+ code: 'PIPELINE_VOICE_DISCOVER_EMPTY',+ message: 'LLM returned no usable voice passages — try again or pick a different provider.',+ };+ const { content, rationale, runId, providerId, model } = await runPromptRefineRaw({+ templateName: 'pipeline-series-voice-discover',+ variables: buildContext(series, universe),+ options,+ source: 'pipeline-series-voice-discover',+ logTag: `Voice discovery — series=${seriesId.slice(0, 8)}`,+ emptyError,+ validateContent: (c) => {+ if (!Array.isArray(c?.candidates)) {+ throw new ServerError(emptyError.message, { status: 502, code: emptyError.code });+ }+ },+ });+ // Dedupe by register (a model that emits two `spare` passages should not+ // crowd out a missing one) and keep the canonical register order so the+ // side-by-side UI is stable across runs.+ const seen = new Set();+ const byRegister = new Map();+ for (const raw of content.candidates) {+ const cand = normalizeCandidate(raw);+ if (!cand || seen.has(cand.register)) continue;+ seen.add(cand.register);+ byRegister.set(cand.register, cand);+ }+ const candidates = VOICE_REGISTER_IDS+ .map((id) => byRegister.get(id))+ .filter(Boolean);+ if (!candidates.length) {+ throw new ServerError(emptyError.message, { status: 502, code: emptyError.code });+ }+ return { candidates, rationale, runId, providerId, model };+}diff --git a/server/services/pipeline/seriesVoiceDiscover.test.js b/server/services/pipeline/seriesVoiceDiscover.test.jsnew file mode 100644index 0000000000..e52c94f9bc--- /dev/null+++ b/server/services/pipeline/seriesVoiceDiscover.test.js@@ -0,0 +1,166 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Mock the three dependencies discoverSeriesVoice reaches: the series store, the+// universe store, and the LLM runner. We control `runPromptRefineRaw`'s returned+// `content` so we can assert the register normalization / dedupe / ordering+// without a real DB or provider.+vi.mock('./series.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, getSeries: vi.fn() };+});+vi.mock('../universeBuilder.js', () => ({+ getUniverse: vi.fn(),+ joinInfluenceList: (a) => (Array.isArray(a) ? a.filter(Boolean).join(', ') : ''),+}));+vi.mock('./refineHelpers.js', () => ({ runPromptRefineRaw: vi.fn() }));++import { discoverSeriesVoice } from './seriesVoiceDiscover.js';+import { getSeries } from './series.js';+import { getUniverse } from '../universeBuilder.js';+import { runPromptRefineRaw } from './refineHelpers.js';+import { VOICE_REGISTER_IDS, STYLE_GUIDE_LIMITS } from '../../lib/styleGuide.js';++const baseSeries = {+ id: 'ser-1',+ name: 'Salt Run',+ logline: 'A child survives the foundry.',+ premise: 'A gritty foundry world.',+ styleNotes: 'noir, sepia',+ universeId: 'uni-1',+ styleGuide: { tense: 'past', tone: ['bleak'] },+};++function mockLLM(candidates, meta = {}) {+ runPromptRefineRaw.mockResolvedValue({+ content: { candidates, rationale: meta.rationale || '' },+ rationale: meta.rationale || 'lean toward spare',+ runId: 'run-1',+ providerId: 'p1',+ model: 'm1',+ });+}++beforeEach(() => {+ vi.clearAllMocks();+ getSeries.mockResolvedValue(baseSeries);+ getUniverse.mockResolvedValue({ id: 'uni-1', name: 'Saltworks', premise: 'foundry world', influences: { embrace: ['noir'], avoid: ['camp'] } });+});++describe('discoverSeriesVoice', () => {+ it('returns normalized candidates in canonical register order', async () => {+ // Emit out of canonical order — the service must re-sort to VOICE_REGISTER_IDS.+ mockLLM([+ { register: 'wry', passage: 'A dry line.', note: 'ironic' },+ { register: 'spare', passage: 'Short. Flat.', note: 'lean' },+ ]);+ const out = await discoverSeriesVoice('ser-1');+ expect(out.candidates.map((c) => c.register)).toEqual(['spare', 'wry']);+ expect(out.candidates[0]).toMatchObject({ register: 'spare', label: 'Spare', passage: 'Short. Flat.', note: 'lean' });+ expect(out).toMatchObject({ providerId: 'p1', model: 'm1', rationale: 'lean toward spare' });+ });++ it('drops candidates with an unknown register id', async () => {+ mockLLM([+ { register: 'made-up', passage: 'nope' },+ { register: 'lyric', passage: 'A song of salt.' },+ ]);+ const out = await discoverSeriesVoice('ser-1');+ expect(out.candidates).toHaveLength(1);+ expect(out.candidates[0].register).toBe('lyric');+ });++ it('drops candidates with an empty or non-string passage', async () => {+ mockLLM([+ { register: 'spare', passage: ' ' },+ { register: 'lyric', passage: 42 },+ { register: 'wry', passage: 'Real prose.' },+ ]);+ const out = await discoverSeriesVoice('ser-1');+ expect(out.candidates).toHaveLength(1);+ expect(out.candidates[0].register).toBe('wry');+ });++ it('dedupes a repeated register, keeping the first', async () => {+ mockLLM([+ { register: 'spare', passage: 'First spare.' },+ { register: 'spare', passage: 'Second spare.' },+ ]);+ const out = await discoverSeriesVoice('ser-1');+ expect(out.candidates).toHaveLength(1);+ expect(out.candidates[0].passage).toBe('First spare.');+ });++ it('clamps an overlong passage to the exemplar char cap', async () => {+ mockLLM([{ register: 'spare', passage: 'x'.repeat(STYLE_GUIDE_LIMITS.EXEMPLAR_PASSAGE_MAX + 500) }]);+ const out = await discoverSeriesVoice('ser-1');+ expect(out.candidates[0].passage).toHaveLength(STYLE_GUIDE_LIMITS.EXEMPLAR_PASSAGE_MAX);+ });++ it('omits the note when the LLM gives none', async () => {+ mockLLM([{ register: 'spare', passage: 'No note here.' }]);+ const out = await discoverSeriesVoice('ser-1');+ expect(out.candidates[0]).not.toHaveProperty('note');+ });++ it('throws PIPELINE_VOICE_DISCOVER_EMPTY when candidates is not an array', async () => {+ // The array gate runs inside the validateContent hook we pass to the runner.+ runPromptRefineRaw.mockImplementation(async ({ validateContent }) => {+ validateContent({ candidates: 'nope' });+ return { content: { candidates: 'nope' }, rationale: '', runId: 'r', providerId: 'p', model: 'm' };+ });+ await expect(discoverSeriesVoice('ser-1')).rejects.toMatchObject({+ code: 'PIPELINE_VOICE_DISCOVER_EMPTY',+ });+ });++ it('throws PIPELINE_VOICE_DISCOVER_EMPTY when every candidate is unusable', async () => {+ mockLLM([{ register: 'bogus', passage: 'x' }, { register: 'spare', passage: '' }]);+ await expect(discoverSeriesVoice('ser-1')).rejects.toMatchObject({+ code: 'PIPELINE_VOICE_DISCOVER_EMPTY',+ });+ });++ it('passes the series + universe context and the register menu into the prompt', async () => {+ mockLLM([{ register: 'spare', passage: 'ok' }]);+ await discoverSeriesVoice('ser-1');+ const call = runPromptRefineRaw.mock.calls[0][0];+ expect(call.templateName).toBe('pipeline-series-voice-discover');+ expect(call.variables.series.name).toBe('Salt Run');+ expect(call.variables.hasUniverse).toBe(true);+ expect(call.variables.universe.name).toBe('Saltworks');+ // Every register id must appear in the rendered menu so the model writes one each.+ for (const id of VOICE_REGISTER_IDS) expect(call.variables.registers).toContain(id);+ expect(call.variables.passageMaxChars).toBe(STYLE_GUIDE_LIMITS.EXEMPLAR_PASSAGE_MAX);+ // The composed style context (tone/tense) seeds the prompt so registers vary WITHIN the tone.+ expect(call.variables.series.styleContext).toContain('past tense');+ });++ it('does NOT leak existing voice exemplars into the discovery prompt (would homogenize a re-run)', async () => {+ getSeries.mockResolvedValue({+ ...baseSeries,+ styleGuide: {+ tense: 'past',+ voiceExemplars: [{ passage: 'ALREADY_PICKED_EXEMPLAR_PROSE', note: 'spare' }],+ voiceAntiExemplars: [{ passage: 'THE_WRONG_REGISTER_PROSE', note: 'ornate' }],+ },+ });+ mockLLM([{ register: 'spare', passage: 'ok' }]);+ await discoverSeriesVoice('ser-1');+ const call = runPromptRefineRaw.mock.calls[0][0];+ // The tone/tense still seeds the prompt...+ expect(call.variables.series.styleContext).toContain('past tense');+ // ...but the already-picked exemplar prose must not, or a re-run just echoes it back.+ expect(call.variables.series.styleContext).not.toContain('ALREADY_PICKED_EXEMPLAR_PROSE');+ expect(call.variables.series.styleContext).not.toContain('THE_WRONG_REGISTER_PROSE');+ });++ it('tolerates a series with no linked universe', async () => {+ getSeries.mockResolvedValue({ ...baseSeries, universeId: null });+ mockLLM([{ register: 'spare', passage: 'ok' }]);+ const out = await discoverSeriesVoice('ser-1');+ expect(getUniverse).not.toHaveBeenCalled();+ expect(out.candidates).toHaveLength(1);+ const call = runPromptRefineRaw.mock.calls[0][0];+ expect(call.variables.hasUniverse).toBe(false);+ });+});