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: check each synthesized voice-over line against the script by transcribing it back (#10250)
[._.]/ Adam Eivy0383e82bdaf6
diff --git a/client/src/components/pipeline/SpokenCheckChip.jsx b/client/src/components/pipeline/SpokenCheckChip.jsxnew file mode 100644index 0000000000..7841a0c236--- /dev/null+++ b/client/src/components/pipeline/SpokenCheckChip.jsx@@ -0,0 +1,46 @@+/**+ * Spoken-text check chip (#10250). Shows whether a rendered voice line, played+ * back through speech-to-text, matched its script: matched / heard "…" /+ * unverified. A mismatch warns only — the user may prefer the read — and can+ * offer Re-render and "Accept as spoken" (records what was heard as expected).+ */+import { Check, AlertTriangle, HelpCircle } from 'lucide-react';++export const countLinesNeedingListen = (items) =>+ (Array.isArray(items) ? items : []).filter((item) => item?.verification?.status === 'mismatch').length;++export default function SpokenCheckChip({ verification, onRerender, onAccept, busy = false }) {+ if (!verification?.status) return null;+ const { status, heard } = verification;+ if (status === 'matched') {+ return (+ <span className="inline-flex items-center gap-1 text-[11px] text-port-success" title="Speech-to-text heard the script">+ <Check size={11} /> matched+ </span>+ );+ }+ if (status === 'unverified') {+ return (+ <span className="inline-flex items-center gap-1 text-[11px] text-gray-500" title="Speech-to-text was not available, so this line was not checked">+ <HelpCircle size={11} /> unverified+ </span>+ );+ }+ return (+ <span className="inline-flex items-center gap-2 flex-wrap text-[11px] text-port-warning">+ <span className="inline-flex items-center gap-1" title="Speech-to-text heard something different from the script">+ <AlertTriangle size={11} /> heard “{heard || '(nothing)'}”+ </span>+ {onRerender ? (+ <button type="button" onClick={onRerender} disabled={busy} className="underline hover:text-white disabled:opacity-50">+ Re-render+ </button>+ ) : null}+ {onAccept && heard ? (+ <button type="button" onClick={onAccept} disabled={busy} className="underline hover:text-white disabled:opacity-50">+ Accept as spoken+ </button>+ ) : null}+ </span>+ );+}diff --git a/client/src/components/pipeline/SpokenCheckChip.test.jsx b/client/src/components/pipeline/SpokenCheckChip.test.jsxnew file mode 100644index 0000000000..145f2cb9b5--- /dev/null+++ b/client/src/components/pipeline/SpokenCheckChip.test.jsx@@ -0,0 +1,34 @@+import { describe, it, expect, vi } from 'vitest';+import { render, screen, fireEvent } from '@testing-library/react';+import SpokenCheckChip, { countLinesNeedingListen } from './SpokenCheckChip';++describe('SpokenCheckChip', () => {+ it('renders nothing without a verification', () => {+ const { container } = render(<SpokenCheckChip verification={null} />);+ expect(container).toBeEmptyDOMElement();+ });++ it('shows matched and unverified states', () => {+ const { rerender } = render(<SpokenCheckChip verification={{ status: 'matched' }} />);+ expect(screen.getByText(/matched/)).toBeInTheDocument();+ rerender(<SpokenCheckChip verification={{ status: 'unverified' }} />);+ expect(screen.getByText(/unverified/)).toBeInTheDocument();+ });++ it('shows what was heard on a mismatch and wires Re-render and Accept as spoken', () => {+ const onRerender = vi.fn();+ const onAccept = vi.fn();+ render(<SpokenCheckChip verification={{ status: 'mismatch', heard: 'Ay-Ai rules' }} onRerender={onRerender} onAccept={onAccept} />);+ expect(screen.getByText(/Ay-Ai rules/)).toBeInTheDocument();+ fireEvent.click(screen.getByText('Re-render'));+ fireEvent.click(screen.getByText('Accept as spoken'));+ expect(onRerender).toHaveBeenCalledTimes(1);+ expect(onAccept).toHaveBeenCalledTimes(1);+ });++ it('counts only mismatches', () => {+ expect(countLinesNeedingListen([+ { verification: { status: 'mismatch' } }, { verification: { status: 'matched' } }, {}, null,+ ])).toBe(1);+ });+});diff --git a/client/src/components/pipeline/manuscript/ManuscriptReadAloud.jsx b/client/src/components/pipeline/manuscript/ManuscriptReadAloud.jsxindex 3ceb664be7..35b4c9a217 100644--- a/client/src/components/pipeline/manuscript/ManuscriptReadAloud.jsx+++ b/client/src/components/pipeline/manuscript/ManuscriptReadAloud.jsx@@ -24,6 +24,7 @@ import VoicePicker from '../../voice/VoicePicker';import toast from '../../ui/Toast';import ProgressBar from '../../ui/ProgressBar';import { formatDurationMs } from '../../../utils/formatters';+import { countLinesNeedingListen } from '../SpokenCheckChip';import { narratePipelineProse } from '../../../services/api';import { STAGE_LABEL } from './constants';import { clickableProps, onActivateKeyDown } from '../../../lib/a11yKeyboard';@@ -79,6 +80,7 @@ export default function ManuscriptReadAloud({ open, onClose, section }) {return { cumulative: cum, totalMs: acc };}, [segments]);+ const listenCount = useMemo(() => countLinesNeedingListen(segments), [segments]);const hardCount = useMemo(() => (segments || []).filter((s) => s.readability?.hard).length,[segments],@@ -195,17 +197,18 @@ export default function ManuscriptReadAloud({ open, onClose, section }) {const active = seg.index === currentIndex;const reasons = seg.readability?.reasons || [];const hard = seg.readability?.hard;+ const misheard = seg.verification?.status === 'mismatch';nodes.push(<spankey={`seg-${seg.index}`}{...clickableProps(() => jumpTo(seg.index))}onClick={() => jumpTo(seg.index)}onKeyDown={onActivateKeyDown(() => jumpTo(seg.index))}- title={hard ? `Hard to say: ${reasons.join('; ')}` : undefined}+ title={misheard ? `Speech-to-text heard: "${seg.verification.heard || ''}"` : (hard ? `Hard to say: ${reasons.join('; ')}` : undefined)}className={['cursor-pointer rounded transition-colors',active ? 'bg-port-accent/30 text-white' : 'hover:bg-port-border/40',- hard ? 'underline decoration-wavy decoration-port-warning/70 underline-offset-2' : '',+ hard || misheard ? 'underline decoration-wavy decoration-port-warning/70 underline-offset-2' : '',].join(' ')}>{content.slice(seg.start, seg.end)}@@ -303,6 +306,12 @@ export default function ManuscriptReadAloud({ open, onClose, section }) {</span><span>{formatDurationMs(elapsedMs)} / {formatDurationMs(totalMs)}</span></div>+ {listenCount > 0 ? (+ <p className="flex items-center gap-1.5 text-[11px] text-port-warning">+ <AlertTriangle size={11} />+ {listenCount} of {segments.length} sentence{segments.length === 1 ? '' : 's'} need a listen — speech-to-text heard something different from the text.+ </p>+ ) : null}{hardCount > 0 ? (<p className="flex items-center gap-1.5 text-[11px] text-port-warning"><AlertTriangle size={11} />diff --git a/client/src/components/pipeline/stages/AudioStage.jsx b/client/src/components/pipeline/stages/AudioStage.jsxindex 9dd74d8895..c4143b4e25 100644--- a/client/src/components/pipeline/stages/AudioStage.jsx+++ b/client/src/components/pipeline/stages/AudioStage.jsx@@ -18,6 +18,7 @@ import toast from '../../ui/Toast';import InlineConfirmRow from '../../ui/InlineConfirmRow';import FilePickerButton from '../../ui/FilePickerButton';import VoicePicker from '../../voice/VoicePicker';+import SpokenCheckChip, { countLinesNeedingListen } from '../SpokenCheckChip';import {extractPipelineAudioLines,renderPipelineAudioLine,@@ -51,6 +52,7 @@ const AUDIO_MODES = [export default function AudioStage({ issue, onStageUpdate }) {const stage = issue.stages?.audio || { status: 'empty', lines: [], music: null };const lines = Array.isArray(stage.lines) ? stage.lines : [];+ const needListenCount = countLinesNeedingListen(lines);const music = stage.music || null;const audioMode = AUDIO_MODES.some((m) => m.id === stage.audioMode) ? stage.audioMode : 'per-clip';// Memoized so the `latestCuesRef` sync effect keys on the lifted array's@@ -582,6 +584,13 @@ export default function AudioStage({ issue, onStageUpdate }) {dropDraft();};+ // "Accept as spoken": record what speech-to-text heard as the expected read so+ // this line (and its next render) counts as matched.+ const handleAcceptSpoken = (lineIdx) => {+ const heard = lines[lineIdx]?.verification?.heard;+ if (heard) void saveLinePatch(lineIdx, { expectedSpeech: heard });+ };+const handleRender = async (lineIdx) => {// Snapshot + await every outstanding PATCH for this line — both text// and voice-override saves can be in flight at once (e.g. textarea@@ -631,6 +640,11 @@ export default function AudioStage({ issue, onStageUpdate }) {{lines.length > 0 ? (<span className="text-xs text-gray-500">{lines.length} line{lines.length === 1 ? '' : 's'}</span>) : null}+ {needListenCount > 0 ? (+ <span className="text-xs text-port-warning">+ {needListenCount} of {lines.length} line{lines.length === 1 ? '' : 's'} need a listen+ </span>+ ) : null}</div><div className="flex items-center gap-2"><button@@ -902,6 +916,16 @@ export default function AudioStage({ issue, onStageUpdate }) {previewText={textValue?.trim() ? textValue.slice(0, 200) : undefined}/></div>+ {line.audioFilename ? (+ <div className="mt-2">+ <SpokenCheckChip+ verification={line.verification}+ busy={isRendering}+ onRerender={() => handleRender(i)}+ onAccept={() => handleAcceptSpoken(i)}+ />+ </div>+ ) : null}{line.audioFilename ? (<audiocontrolsdiff --git a/server/lib/README.md b/server/lib/README.mdindex fb24622307..c8b58c9a68 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -53,6 +53,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `fableLoomPlaytest.js` | FableLoom branching-playthrough harness: bounded exhaustive path enumeration, ending/loop/coverage diagnostics, aggregate loom reports, and compact traces for narrative-quality review. || `postCognitiveConfig.js` | Browser-safe limits and joint constraints (`COGNITIVE_PAIR_CONSTRAINTS`, `validateCognitivePair`, `dependentMin`) for the POST cognitive drills with related manual pairs — digit-span start/max length, reaction-time delay window, Go/No-Go stimulus/deadline — shared by the config UI, route validation, and generators. || `postDrillTypes.js` | MeatSpace POST drill vocabularies (`LLM_DRILL_TYPES`, `CACHEABLE_TYPES`, `COGNITIVE_DRILL_TYPES`, `POST_SUPPORTED_MEMORY_TYPES`), kept below validation so a route schema never pulls in the POST services (and, through them, the LLM drill generator). |+| `speechMatch.js` | `compareSpeech(script, heard)` / `normalizeSpeech` — normalize case, punctuation and number words, then score word-level (character-level for CJK) edit distance; `matched` at similarity >= 0.90. Used to verify rendered voice-over lines against a speech-to-text pass. || `spriteVocabulary.js` | Sprite id pattern, record kinds, the canonical 8-direction order + derived anchor set, `TURNAROUND_ID`, and the animation provider ids — the alphabets the sprite route schemas enumerate, kept below the sprite services. || `spriteChromaKey.js` | Chroma-key selection color math (`CHROMA_KEYS`, `CHROMA_KEY_HEXES`, `DEFAULT_CHROMA_KEY`, hue-distance picking). Pure color math, no image I/O — that lives in `services/sprites/normalize.js`. || `spriteAnimationTracks.js` | The animation-track registry (`ANIMATION_TRACKS`, `WALK_TRACK`, `TRACK_BOUND_TRIPLES`, `AUTHORED_TRACK_FIELDS`) — a zero-import table of per-track frame/fps bounds. |diff --git a/server/lib/index.js b/server/lib/index.jsindex f95518df49..a015e780eb 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -833,3 +833,4 @@ export * from './forgeMaintenanceTasks.js';export * from './maintenanceAdmission.js';export * as peerAdminValidation from './peerAdminValidation.js';+export * from './speechMatch.js';diff --git a/server/lib/speechMatch.js b/server/lib/speechMatch.jsnew file mode 100644index 0000000000..a751348993--- /dev/null+++ b/server/lib/speechMatch.js@@ -0,0 +1,117 @@+/**+ * Speech match — compare what a TTS line was SUPPOSED to say with what a+ * speech-to-text pass heard. Pure: normalizes case, punctuation and number+ * words, then scores word-level (character-level for CJK) edit distance.+ */++export const SPEECH_MATCH_THRESHOLD = 0.9;++const ONES = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten',+ 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];+const TENS = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];+const SCALES = [[1e9, 'billion'], [1e6, 'million'], [1e3, 'thousand']];+const MAX_NUMBER = 999_999_999_999;++const CJK_RE = /[-ヿ㐀-䶿一-鿿가-]/u;++function below1000(n) {+ const words = [];+ if (n >= 100) {+ words.push(ONES[Math.floor(n / 100)], 'hundred');+ n %= 100;+ }+ if (n >= 20) {+ words.push(TENS[Math.floor(n / 10)]);+ n %= 10;+ if (n) words.push(ONES[n]);+ } else if (n > 0) {+ words.push(ONES[n]);+ }+ return words;+}++/** Spell a non-negative integer as English cardinal words ("12" -> "twelve"). */+export function numberToWords(n) {+ if (!Number.isInteger(n) || n < 0 || n > MAX_NUMBER) return String(n);+ if (n === 0) return 'zero';+ const words = [];+ let rest = n;+ for (const [size, name] of SCALES) {+ if (rest >= size) {+ words.push(...below1000(Math.floor(rest / size)), name);+ rest %= size;+ }+ }+ words.push(...below1000(rest));+ return words.join(' ');+}++// "1999" is read "nineteen ninety nine" as often as "one thousand ...".+function yearWords(n) {+ if (n < 1100 || n > 2099 || n % 100 === 0) return null;+ const tail = n % 100;+ const head = below1000(Math.floor(n / 100)).join(' ');+ return tail < 10 ? `${head} oh ${ONES[tail]}` : `${head} ${below1000(tail).join(' ')}`;+}++function normalizeBase(text, numberReader) {+ return String(text ?? '')+ .normalize('NFKC')+ .toLowerCase()+ .replace(/(\d),(?=\d{3}\b)/g, '$1')+ .replace(/(\d+)\.(\d+)/g, (_m, a, b) => `${a} point ${[...b].join(' ')}`)+ .replace(/\d+/g, (m) => numberReader(m))+ .replace(/['’`]/g, '')+ .replace(/[^\p{L}\p{N}\p{M}]+/gu, ' ')+ .trim();+}++const cardinal = (m) => ` ${numberToWords(Number(m))} `;+const year = (m) => ` ${yearWords(Number(m)) ?? numberToWords(Number(m))} `;++function tokenize(normalized) {+ if (CJK_RE.test(normalized)) return [...normalized.replace(/\s+/g, '')];+ return normalized.split(/\s+/).filter(Boolean);+}++/** Normalized token list for a line (digits spelled out, punctuation dropped). */+export function normalizeSpeech(text) {+ return tokenize(normalizeBase(text, cardinal));+}++function editDistance(a, b) {+ if (a.length === 0) return b.length;+ if (b.length === 0) return a.length;+ let prev = Array.from({ length: b.length + 1 }, (_, j) => j);+ for (let i = 1; i <= a.length; i += 1) {+ const cur = [i];+ for (let j = 1; j <= b.length; j += 1) {+ cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));+ }+ prev = cur;+ }+ return prev[b.length];+}++function similarityOf(expected, heard) {+ if (expected.length === 0 && heard.length === 0) return 1;+ return 1 - editDistance(expected, heard) / Math.max(expected.length, heard.length);+}++/**+ * Compare the script text with what was heard. A number may be read as a+ * cardinal or as a year, so the better of the two readings of each side wins.+ * @returns {{ status: 'matched'|'mismatch', similarity: number }}+ */+export function compareSpeech(expected, heard) {+ const readers = [cardinal, year];+ let best = 0;+ for (const ex of readers) {+ for (const he of readers) {+ const s = similarityOf(tokenize(normalizeBase(expected, ex)), tokenize(normalizeBase(heard, he)));+ if (s > best) best = s;+ }+ }+ const similarity = Math.round(best * 1000) / 1000;+ return { status: similarity >= SPEECH_MATCH_THRESHOLD ? 'matched' : 'mismatch', similarity };+}diff --git a/server/lib/speechMatch.test.js b/server/lib/speechMatch.test.jsnew file mode 100644index 0000000000..c71aa1a04d--- /dev/null+++ b/server/lib/speechMatch.test.js@@ -0,0 +1,37 @@+import { describe, it, expect } from 'vitest';+import { compareSpeech, normalizeSpeech, numberToWords } from './speechMatch.js';++describe('speechMatch', () => {+ it('spells numbers', () => {+ expect(numberToWords(12)).toBe('twelve');+ expect(numberToWords(0)).toBe('zero');+ expect(numberToWords(2024)).toBe('two thousand twenty four');+ expect(numberToWords(1_250_300)).toBe('one million two hundred fifty thousand three hundred');+ });++ it.each([+ ['I have 12 apples.', 'I have twelve apples'],+ ['Hello, World!', 'hello world'],+ ["Don't go.", 'Dont go'],+ ['It cost 1,200 dollars', 'it cost one thousand two hundred dollars'],+ ['In 1999 we left', 'In nineteen ninety nine we left'],+ ['3.5 miles', 'three point five miles'],+ ['你好,世界!', '你好 世界'],+ ])('matches %j against %j', (script, heard) => {+ expect(compareSpeech(script, heard).status).toBe('matched');+ });++ it.each([+ ['I have 12 apples', 'I have fifteen apples'],+ ['The quick brown fox jumps over the lazy dog', 'The quick brown fox jumps'],+ ['你好世界今天天气很好', '你好世界明天下雨'],+ ['Say something', ''],+ ])('flags %j heard as %j', (script, heard) => {+ expect(compareSpeech(script, heard).status).toBe('mismatch');+ });++ it('tokenizes CJK per character and Latin per word', () => {+ expect(normalizeSpeech('你好 世界')).toEqual(['你', '好', '世', '界']);+ expect(normalizeSpeech('Hi, there')).toEqual(['hi', 'there']);+ });+});diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.jsindex cd96c7d7ab..006cc8c1d3 100644--- a/server/routes/pipeline.test.js+++ b/server/routes/pipeline.test.js@@ -317,6 +317,8 @@ vi.mock('../services/voice/tts.js', () => ({normalizeVoiceEngine: (engine) => engine === 'qwen3' ? 'qwen3-tts' : engine,VALID_ENGINES: new Set(['kokoro', 'piper', 'qwen3-tts']),}));+const transcribeMock = vi.fn();+vi.mock('../services/voice/stt.js', () => ({ transcribe: (...a) => transcribeMock(...a) }));vi.mock('../services/voice/profiles.js', () => ({clearVoiceProfileRender: vi.fn(),recordVoiceProfileRender: vi.fn(),@@ -2804,6 +2806,70 @@ describe('pipeline routes', () => {expect(issAfter.body.stages.audio.lines[0].audioFilename).toMatch(/^vo-mock-/);});++ describe('spoken-text verification (#10250)', () => {+ // Run the real verifyRenderedLine behind the mocked synthesizeToFile so the+ // route's expectedSpeech hand-off and verification persistence are exercised.+ const renderWithVerification = async (app, iss) => {+ const audio = await import('../services/pipeline/audio.js');+ audio.synthesizeToFile.mockImplementationOnce(async ({ text, expectedSpeech }) => ({+ filename: `vo-mock-${++uuidCounter}.wav`, latencyMs: 1, engine: 'kokoro',+ verification: await audio.verifyRenderedLine({ wav: Buffer.from('w'), text, expectedSpeech }),+ }));+ return request(app).post(`/api/pipeline/issues/${iss.id}/stages/audio/lines/0/render`).send({});+ };+ const seed = async (app) => {+ const iss = await seedIssueWithStoryboards(app);+ await request(app).post(`/api/pipeline/issues/${iss.id}/stages/audio/extract-lines`).send({});+ return iss;+ };++ it('marks a read that matches the script as matched', async () => {+ const app = makeApp();+ const iss = await seed(app);+ const script = (await request(app).get(`/api/pipeline/issues/${iss.id}`)).body.stages.audio.lines[0].text;+ transcribeMock.mockResolvedValueOnce({ text: script });+ const r = await renderWithVerification(app, iss);+ expect(r.body.verification).toMatchObject({ status: 'matched', similarity: 1 });+ expect(transcribeMock).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ prompt: '' }));+ });++ it('marks a different read as mismatch, keeps what was heard, and accepts it via expectedSpeech', async () => {+ const app = makeApp();+ const iss = await seed(app);+ transcribeMock.mockResolvedValue({ text: 'completely different words about nothing at all' });+ const r = await renderWithVerification(app, iss);+ expect(r.status).toBe(200);+ expect(r.body.verification).toMatchObject({ status: 'mismatch', heard: 'completely different words about nothing at all' });+ const stored = (await request(app).get(`/api/pipeline/issues/${iss.id}`)).body.stages.audio.lines[0];+ expect(stored.verification.status).toBe('mismatch');++ // "Accept as spoken": the heard text becomes the expectation and the chip flips.+ const accepted = await request(app)+ .patch(`/api/pipeline/issues/${iss.id}/stages/audio/lines/0`)+ .send({ expectedSpeech: 'completely different words about nothing at all' });+ expect(accepted.status).toBe(200);+ expect(accepted.body.stage.lines[0].verification.status).toBe('matched');++ // The next render compares against expectedSpeech.+ const again = await renderWithVerification(app, iss);+ expect(again.body.verification.status).toBe('matched');+ transcribeMock.mockReset();+ });++ it('is unverified, and the render still succeeds, when STT is down', async () => {+ const app = makeApp();+ const iss = await seed(app);+ transcribeMock.mockRejectedValueOnce(new Error('connect ECONNREFUSED'));+ const r = await renderWithVerification(app, iss);+ expect(r.status).toBe(200);+ expect(r.body.verification).toEqual({ status: 'unverified', similarity: null, heard: '' });+ const stored = (await request(app).get(`/api/pipeline/issues/${iss.id}`)).body.stages.audio.lines[0];+ expect(stored.audioFilename).toMatch(/^vo-mock-/);+ expect(stored.verification.status).toBe('unverified');+ });+ });+it('keeps local voice profile provenance out of the federated issue record', async () => {const audio = await import('../services/pipeline/audio.js');const profiles = await import('../services/voice/profiles.js');diff --git a/server/routes/pipeline/audio.js b/server/routes/pipeline/audio.jsindex 825307b069..6d9c21cc37 100644--- a/server/routes/pipeline/audio.js+++ b/server/routes/pipeline/audio.js@@ -12,6 +12,7 @@ import * as seriesSvc from '../../services/pipeline/series.js';import * as issuesSvc from '../../services/pipeline/issues.js';import { getSeriesCanon } from '../../services/pipeline/seriesCanon.js';import { resolveSeriesLlmOverride } from '../../lib/seriesLlmOverride.js';+import { compareSpeech } from '../../lib/speechMatch.js';import { listAllVoices, synthesizeToFile, parseVoiceId, extractDialogueLines, resolveVoiceForLine } from '../../services/pipeline/audio.js';import { narrateProse } from '../../services/pipeline/manuscriptNarration.js';import { synthesize as synthesizeVoice } from '../../services/voice/tts.js';@@ -162,6 +163,8 @@ const lineEditSchema = z.object({// Per-line VO start offset (seconds into the stitched episode). null clears// the placement so the muxer skips the line. The sanitizer clamps the range.offsetSec: z.number().min(0).max(7200).nullable().optional(),+ // Accepted recognizer spelling ("Ay-Ai" for "AI"); null clears it (#10250).+ expectedSpeech: z.string().trim().max(4000).nullable().optional(),});router.patch('/issues/:id/stages/audio/lines/:lineIdx', asyncHandler(async (req, res) => {const lineIdx = Number(req.params.lineIdx);@@ -187,6 +190,14 @@ router.patch('/issues/:id/stages/audio/lines/:lineIdx', asyncHandler(async (req,if ('text' in body) next.text = body.text;if ('voiceIdOverride' in body) next.voiceIdOverride = body.voiceIdOverride;if ('offsetSec' in body) next.offsetSec = body.offsetSec;+ if ('expectedSpeech' in body) {+ next.expectedSpeech = body.expectedSpeech || null;+ // Re-score the last heard text against the new target; no STT call.+ if (next.verification && next.verification.status !== 'unverified') {+ const { status, similarity } = compareSpeech(next.expectedSpeech || next.text, next.verification.heard);+ next.verification = { ...next.verification, status, similarity };+ }+ }const nextLines = [...lines];nextLines[lineIdx] = next;return { status: 'edited', lines: nextLines };@@ -245,6 +256,7 @@ router.post('/issues/:id/stages/audio/lines/:lineIdx/render', asyncHandler(asyncvoiceId,profileId: profileResolution?.profileId || undefined,route: 'studio',+ expectedSpeech: line.expectedSpeech || undefined,}).catch((err) => { throw mapServiceError(err); });// The WAV is already on disk. The render provenance row and the stage row@@ -268,6 +280,7 @@ router.post('/issues/:id/stages/audio/lines/:lineIdx/render', asyncHandler(async...line,audioJobId: null,audioFilename: synthResult.filename,+ verification: synthResult.verification,};return issuesSvc.updateStage(req.params.id, 'audio', {status: 'edited',@@ -278,6 +291,7 @@ router.post('/issues/:id/stages/audio/lines/:lineIdx/render', asyncHandler(asyncres.json({issue: updatedIssue, stage, lineIdx,filename: synthResult.filename,+ verification: synthResult.verification,engine: synthResult.engine,voiceId: synthResult.voiceId || voiceId,profileId: synthResult.profileId,diff --git a/server/services/pipeline/audio.js b/server/services/pipeline/audio.jsindex 5be7b9a670..9b61d236cc 100644--- a/server/services/pipeline/audio.js+++ b/server/services/pipeline/audio.js@@ -26,6 +26,8 @@ import {} from '../voice/tts.js';import { ServerError } from '../../lib/errorHandler.js';import { wavDurationMs } from '../../lib/wavAudioFile.js';+import { compareSpeech } from '../../lib/speechMatch.js';+import { transcribe } from '../voice/stt.js';const VOICE_ID_RE = /^([a-z][a-z0-9-]*):(.+)$/i;@@ -196,6 +198,8 @@ export function extractDialogueLines(issue, canon, { preserveFrom = [] } = {}) {voiceIdOverride: carryover?.voiceIdOverride || null,audioJobId: carryover?.audioJobId || null,audioFilename: carryover?.audioFilename || null,+ verification: carryover?.verification || null,+ expectedSpeech: carryover?.expectedSpeech || null,});lineNumber += 1;}@@ -206,7 +210,26 @@ export function extractDialogueLines(issue, canon, { preserveFrom = [] } = {}) {// wavDurationMs moved to lib/wavAudioFile.js (shared with the Music Designer code engine).export { wavDurationMs };-export async function synthesizeToFile({ text, voiceId, profileId, route = 'studio', signal } = {}) {+/**+ * Round-trip a rendered WAV through speech-to-text and compare it with the+ * script (#10250). The empty decoder prompt keeps vocabulary bias from masking+ * a mispronunciation. `expectedSpeech` is the user's accepted recognizer+ * spelling and replaces the script text as the comparison target. STT being+ * down or slow yields `unverified` — never an error, never blocks a render.+ * @returns {Promise<{ status: 'matched'|'mismatch'|'unverified', similarity: number|null, heard: string }>}+ */+export async function verifyRenderedLine({ wav, text, expectedSpeech, signal } = {}) {+ const heardResult = await transcribe(wav, { prompt: '', signal }).catch((err) => {+ console.warn(`⚠️ voice-over verification skipped: ${err?.message || err}`);+ return null;+ });+ if (!heardResult) return { status: 'unverified', similarity: null, heard: '' };+ const heard = heardResult.text;+ const { status, similarity } = compareSpeech(expectedSpeech || text, heard);+ return { status, similarity, heard };+}++export async function synthesizeToFile({ text, voiceId, profileId, route = 'studio', signal, expectedSpeech } = {}) {const trimmed = (text || '').trim();if (!trimmed) {throw new ServerError('text is required', { status: 400, code: 'PIPELINE_AUDIO_EMPTY_TEXT' });@@ -229,8 +252,10 @@ export async function synthesizeToFile({ text, voiceId, profileId, route = 'stud// audioJobId-or-audioFilename binding lives in stages.audio.lines[].const filename = `vo-${randomUUID()}.wav`;await atomicWrite(join(PATHS.audio, filename), wav);+ const verification = await verifyRenderedLine({ wav, text: trimmed, expectedSpeech, signal });return {filename,+ verification,latencyMs,durationMs: wavDurationMs(wav),engine: usedEngine,diff --git a/server/services/pipeline/audio.test.js b/server/services/pipeline/audio.test.jsindex 92237a0569..df8e2493f0 100644--- a/server/services/pipeline/audio.test.js+++ b/server/services/pipeline/audio.test.js@@ -25,6 +25,8 @@ vi.mock('../voice/tts.js', () => ({VALID_ENGINES: new Set(['kokoro', 'piper', 'qwen3-tts']),}));+vi.mock('../voice/stt.js', () => ({ transcribe: vi.fn().mockRejectedValue(new Error('stt down')) }));+const { parseVoiceId, listAllVoices, synthesizeToFile, extractDialogueLines, resolveVoiceForLine, wavDurationMs } = await import('./audio.js');// Build a minimal canonical PCM WAV header for `dataBytes` of audio at the givendiff --git a/server/services/pipeline/issuesShared.js b/server/services/pipeline/issuesShared.jsindex fa2efe3225..cddb80667f 100644--- a/server/services/pipeline/issuesShared.js+++ b/server/services/pipeline/issuesShared.js@@ -448,6 +448,19 @@ export const sanitizeLineOffset = (raw) => {return Math.min(n, AUDIO_LINE_OFFSET_MAX_SEC);};+const AUDIO_VERIFICATION_STATUSES = new Set(['matched', 'mismatch', 'unverified']);+// Spoken-text check from the last render (#10250): what speech-to-text heard+// versus the script. Advisory only — never gates the mux.+const sanitizeAudioVerification = (raw) => {+ if (!raw || typeof raw !== 'object' || !AUDIO_VERIFICATION_STATUSES.has(raw.status)) return null;+ const similarity = Number(raw.similarity);+ return {+ status: raw.status,+ similarity: raw.similarity != null && Number.isFinite(similarity) ? Math.min(Math.max(similarity, 0), 1) : null,+ heard: trimTo(raw.heard, AUDIO_LINE_TEXT_MAX) || '',+ };+};+const sanitizeAudioLine = (raw, i) => {if (!raw || typeof raw !== 'object') return null;const text = trimTo(raw.text, AUDIO_LINE_TEXT_MAX);@@ -459,6 +472,8 @@ const sanitizeAudioLine = (raw, i) => {characterName: trimTo(raw.characterName, 120) || null,text,voiceIdOverride: trimTo(raw.voiceIdOverride, 200) || null,+ expectedSpeech: trimTo(raw.expectedSpeech, AUDIO_LINE_TEXT_MAX) || null,+ verification: sanitizeAudioVerification(raw.verification),audioJobId: isStr(raw.audioJobId) && raw.audioJobId ? raw.audioJobId : null,audioFilename: isStr(raw.audioFilename) && raw.audioFilename? raw.audioFilename.slice(0, AUDIO_FILENAME_MAX)diff --git a/server/services/pipeline/manuscriptNarration.js b/server/services/pipeline/manuscriptNarration.jsindex bdc2461a11..34dd4e8a3a 100644--- a/server/services/pipeline/manuscriptNarration.js+++ b/server/services/pipeline/manuscriptNarration.js@@ -245,6 +245,7 @@ export async function narrateProse({ text, voiceId, signal } = {}) {end: seg.end,filename: result.filename,durationMs: result.durationMs,+ verification: result.verification,readability: analyzeSentenceReadability(seg.text),});}