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: add local character voice profiles (#5380)
[._.]/ Adam Eivy7d6aca5b6950
diff --git a/client/src/components/pipeline/CanonCard.jsx b/client/src/components/pipeline/CanonCard.jsxindex d1c006205b..316e87e146 100644--- a/client/src/components/pipeline/CanonCard.jsx+++ b/client/src/components/pipeline/CanonCard.jsx@@ -528,6 +528,7 @@ export default function CanonCard({<CharacterDetailsToggle><CharacterDetailEditorentry={entry}+ universeId={characterExtensions.universeId}characters={characterExtensions.castList || []}onPatch={(patch) => onPatchEntry(entry.id, patch)}onExpand={characterExtensions.onExpandCharacter ? () => characterExtensions.onExpandCharacter(entry.id) : null}diff --git a/client/src/components/universe/CharacterDetailEditor.jsx b/client/src/components/universe/CharacterDetailEditor.jsxindex b713ce82a4..f9261eb705 100644--- a/client/src/components/universe/CharacterDetailEditor.jsx+++ b/client/src/components/universe/CharacterDetailEditor.jsx@@ -10,16 +10,18 @@* only knows the field shape.*/-import { useState } from 'react';+import { useEffect, useRef, useState } from 'react';import {Plus, Trash2, WandSparkles, Loader2,Palette, Hand, Smile, Package, BookOpen, Eye, Activity, Users, Swords,- Drama, KeyRound, Mic, Images, BadgeCheck,+ Drama, KeyRound, Mic, Images, BadgeCheck, Play,} from 'lucide-react';import { BIBLE_LIMITS as L } from '../../lib/bibleLimits';import useFieldDraft from '../../hooks/useFieldDraft';import useRowDraft from '../../hooks/useRowDraft';import usePendingListRows from '../../hooks/usePendingListRows';+import useAsyncAction from '../../hooks/useAsyncAction';+import { listVoiceProfiles, promoteVoicePreset, renderVoiceProfileBenchmark } from '../../services/apiVoice';import VoicePicker from '../voice/VoicePicker';import CollapsibleSection from '../ui/CollapsibleSection';@@ -748,6 +750,94 @@ function VoiceCanonSection({ entry, onPatch, disabled }) {);}+function VoiceProfileSection({ universeId, entry, disabled }) {+ const [profile, setProfile] = useState(null);+ const [loading, setLoading] = useState(Boolean(universeId));+ const [loadError, setLoadError] = useState(null);+ const loadGeneration = useRef(0);+ useEffect(() => {+ let cancelled = false;+ const generation = ++loadGeneration.current;+ if (!universeId || !entry?.id) {+ setProfile(null);+ setLoading(false);+ return () => { cancelled = true; };+ }+ setLoading(true);+ listVoiceProfiles({ universeId, characterId: entry.id }, { silent: true })+ .then((result) => {+ if (cancelled || generation !== loadGeneration.current) return;+ setProfile(Array.isArray(result?.profiles) ? result.profiles[0] || null : null);+ setLoadError(null);+ })+ .catch((err) => {+ if (!cancelled && generation === loadGeneration.current) {+ setLoadError(err?.message || 'Failed to load the local voice profile');+ }+ })+ .finally(() => {+ if (!cancelled && generation === loadGeneration.current) setLoading(false);+ });+ return () => { cancelled = true; };+ }, [universeId, entry?.id]);++ const [promote, promoting] = useAsyncAction(async () => {+ // A pending initial fetch must not erase the user action that just won.+ loadGeneration.current += 1;+ const result = await promoteVoicePreset({+ universeId,+ characterId: entry.id,+ characterName: entry.name || '',+ voiceId: entry.voiceId,+ }, { silent: true });+ setProfile(result?.profile || null);+ return result;+ }, { errorMessage: 'Could not promote the selected preset' });++ const [renderBenchmark, renderingBenchmark] = useAsyncAction(async () => {+ const result = await renderVoiceProfileBenchmark(profile.id, { silent: true });+ setProfile(result?.profile || profile);+ return result;+ }, { errorMessage: 'Could not render the voice benchmark' });++ if (!universeId) return null;+ const approved = profile?.approval?.status === 'approved';+ const benchmarkCount = profile?.benchmark?.lines?.length || 0;+ const profileState = approved ? `approved v${profile.version}` : profile?.approval?.status || 'not promoted';+ return (+ <BoxedSection icon={Mic} label="Local voice profile" summary={loading ? 'loading' : profileState}>+ <p className="text-[10px] leading-snug text-gray-500">+ This machine-local profile wins over the portable preset binding. It never writes a profile id into the synced Universe record.+ </p>+ {loadError ? <p className="text-[10px] text-port-error">{loadError}</p> : null}+ {approved ? (+ <p className="text-[10px] text-gray-400">+ {profile.voiceId} · {profile.modelRevision} · rate {profile.delivery?.rate ?? 1} · benchmark {benchmarkCount ? `${benchmarkCount} lines rendered` : 'not rendered'}+ </p>+ ) : profile ? (+ <p className="text-[10px] text-gray-500">This local profile is {profileState}; it is unavailable for synthesis until explicitly approved.</p>+ ) : <p className="text-[10px] text-gray-500">Promote the selected Kokoro or Piper preset to give this character a stable local voice.</p>}+ <div className="flex flex-wrap gap-1.5">+ <button+ type="button" onClick={promote} disabled={disabled || promoting || !entry.voiceId}+ className="inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded border border-port-border text-gray-400 hover:text-white hover:border-gray-500 disabled:opacity-40"+ >+ <BadgeCheck size={10} /> {approved ? 'Re-promote selected preset' : 'Promote selected preset'}+ </button>+ <button+ type="button" onClick={renderBenchmark} disabled={disabled || renderingBenchmark || !approved}+ className="inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded border border-port-border text-gray-400 hover:text-white hover:border-gray-500 disabled:opacity-40"+ >+ {renderingBenchmark ? <Loader2 size={10} className="animate-spin" /> : <Play size={10} />} Render fixed benchmark+ </button>+ </div>+ <p className="text-[10px] leading-snug text-gray-500">+ Kokoro and Piper support preset selection plus rate only. Pitch and formant controls are intentionally unavailable until a compatible local backend and formant-preserving transform are installed.+ </p>+ </BoxedSection>+ );+}+function IdentityPackSection({ entry, onPatch, disabled }) {const pack = entry.identityPack || {};const assets = Array.isArray(pack.assets) ? pack.assets : [];@@ -817,7 +907,7 @@ function IdentityPackSection({ entry, onPatch, disabled }) {);}-export default function CharacterDetailEditor({ entry, onPatch, onExpand, expanding = false, disabled = false, characters = [] }) {+export default function CharacterDetailEditor({ entry, universeId = null, onPatch, onExpand, expanding = false, disabled = false, characters = [] }) {if (!entry) return null;const patchField = (name, value) => onPatch?.({ [name]: value });@@ -882,6 +972,8 @@ export default function CharacterDetailEditor({ entry, onPatch, onExpand, expand<VoiceCanonSection entry={entry} onPatch={onPatch} disabled={disabled} />+ <VoiceProfileSection universeId={universeId} entry={entry} disabled={disabled} />+<IdentityPackSection entry={entry} onPatch={onPatch} disabled={disabled} /><RelationshipsSectiondiff --git a/client/src/components/universe/CharacterDetailEditor.test.jsx b/client/src/components/universe/CharacterDetailEditor.test.jsxindex ed7baf409b..ab168e7f38 100644--- a/client/src/components/universe/CharacterDetailEditor.test.jsx+++ b/client/src/components/universe/CharacterDetailEditor.test.jsx@@ -1,10 +1,20 @@import { describe, it, expect, vi } from 'vitest';-import { render, screen, fireEvent } from '@testing-library/react';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';import CharacterDetailEditor from './CharacterDetailEditor';// Mock VoicePicker — it pulls in the voice API/socket layer the relationship// tests don't care about.vi.mock('../voice/VoicePicker', () => ({ default: () => null }));+vi.mock('../../services/apiVoice', () => ({+ listVoiceProfiles: vi.fn(),+ promoteVoicePreset: vi.fn(),+ renderVoiceProfileBenchmark: vi.fn(),+}));++import {+ listVoiceProfiles,+ promoteVoicePreset,+} from '../../services/apiVoice';const ARIA = { id: 'chr-aria', name: 'Aria' };const BRAM = { id: 'chr-bram', name: 'Bram' };@@ -165,6 +175,26 @@ describe('CharacterDetailEditor — character framework (#2175)', () => {});describe('CharacterDetailEditor — production package (#5378)', () => {+ it('keeps the empty local-profile state distinct and promotes a portable preset locally', async () => {+ listVoiceProfiles.mockResolvedValue({ profiles: [] });+ promoteVoicePreset.mockResolvedValueOnce({+ profile: {+ id: 'voice-profile-1', version: 1, voiceId: 'kokoro:af_heart', modelRevision: 'kokoro-test:q8',+ delivery: { rate: 1 }, approval: { status: 'approved' }, benchmark: null,+ },+ });+ render(<CharacterDetailEditor+ entry={{ ...ARIA, voiceId: 'kokoro:af_heart' }} universeId="uni-1" characters={[ARIA]} onPatch={() => {}}+ />);+ fireEvent.click(screen.getByRole('button', { name: /Local voice profile/i }));+ expect(await screen.findByText(/Promote the selected Kokoro or Piper preset/i)).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: /Promote selected preset/i }));+ await waitFor(() => expect(promoteVoicePreset).toHaveBeenCalledWith({+ universeId: 'uni-1', characterId: 'chr-aria', characterName: 'Aria', voiceId: 'kokoro:af_heart',+ }, { silent: true }));+ expect(await screen.findByRole('button', { name: /Re-promote selected preset/i })).toBeInTheDocument();+ });+it('marks a voice-canon revision as approved', () => {const onPatch = vi.fn();render(<CharacterDetailEditor entry={ARIA} characters={[ARIA]} onPatch={onPatch} />);diff --git a/client/src/services/apiVoice.js b/client/src/services/apiVoice.jsindex 41f288e45a..056a78a5fd 100644--- a/client/src/services/apiVoice.js+++ b/client/src/services/apiVoice.js@@ -9,6 +9,17 @@ export const getVoiceConfig = (options) => api.get('/voice/config', options);export const updateVoiceConfig = (patch, options) => api.put('/voice/config', patch, options);export const listVoices = (engine, options) => api.get(`/voice/voices${engine ? `?engine=${engine}` : ''}`, options);export const fetchPiperVoice = (voice, options) => api.post('/voice/piper/fetch', { voice }, options);+export const listVoiceProfiles = ({ universeId, characterId } = {}, options) => {+ const params = new URLSearchParams();+ if (universeId) params.set('universeId', universeId);+ if (characterId) params.set('characterId', characterId);+ const query = params.toString();+ return api.get(`/voice/profiles${query ? `?${query}` : ''}`, options);+};+export const promoteVoicePreset = (payload, options) => api.post('/voice/profiles/preset', payload, options);+export const renderVoiceProfileBenchmark = (profileId, options) => api.post(+ `/voice/profiles/${encodeURIComponent(profileId)}/benchmark`, {}, options,+);// Returns the raw WAV bytes of the test utterance. Optional `voice` and// `engine` overrides let the voice-picker preview audition a voice from adiff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex a9e35d45c1..dfb165bdf7 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -35,6 +35,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- `creative_director_projects` — Creative Director project/treatment/scene/run state, one row per project (`id`/`status`/timestamps as columns, the full record in `data` JSONB). Migrated from the monolithic `data/creative-director-projects.json` in Phase 3 (#997); CD is local-only, so the row carries no sync cursor/tombstone. Adapter: `server/services/creativeDirector/projectsDB.js`.- `catalog_user_types` — user-defined ingredient types (the registry that defines catalog row semantics), one row per type (`id` PK, the definition in `data` JSONB, `updated_at`/`deleted_at` mirroring the federation LWW clock + tombstone). Migrated from the `data/settings.json` `catalogUserTypes` slice in Phase 4 lead-in (#1001) so type evolution versions/syncs alongside the catalog data it governs. Federates via the catalog sync `catalogTypes` envelope block (wire shape unchanged by the move). Adapter: `server/services/catalogUserTypes/db.js`, dispatched via `store.js`.- `universes` / `universe_runs` — Universe Builder records (canon bibles, categories, composite sheets, locks, influences, and portable character production packages) one row per universe with the full sanitized record in `data` JSONB and `name`/`schema_version`/`ephemeral`/`updated_at`/`deleted`/`deleted_at` mirrored into columns; render-run history one row per run (local-only, capped 200, never federated). Character production packages carry only versioned voice direction and approved managed-image roles; local profiles, recordings, provider ids, and training artifacts are excluded from the federated wire. Migrated from `data/universes/{id}/index.json` (collectionStore) in Phase 3 Create slice 1 (#1014). **NO `sync_sequence`** — universes federate via the EXISTING `dataSync` snapshot/push model (LWW on the body's `updatedAt`), so the storage swap is invisible to peers (no schema-version bump). The store bumps an in-process mutation epoch on every write that `dataSync` folds into its checksum fingerprint, since a DB edit no longer changes the `data/universes/` directory the fingerprint used to watch. **`universe_runs` is intentionally never federated** — a regenerable render cache under a 200-row *global* cap that two producers would mutually evict, while the durable universe record already syncs (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724). Adapter: `server/services/universeBuilder/db.js`, dispatched via `store.js`.+- `voice_profiles` — one machine-local DB-primary record per approved `(universeId, characterId)` binding, storing the promoted Kokoro/Piper preset, profile revision, route availability, and benchmark provenance. The portable Universe character keeps only voice direction and its namespaced preset fallback; it never stores a local profile id. Rendered benchmark WAVs, safe-basename source-asset metadata, and future local engine artifacts live under `data/voice-profiles/<profileId>/`. Both the PostgreSQL dump and that managed directory are included in normal backup, while peer sync intentionally carries neither. Adapter: `server/services/voice/profiles.js`.- `tribe_people` / `tribe_touchpoints` / `tribe_memory_links` — the Tribe relationship/CRM graph (people + their care cadence, contact touchpoints, and cross-links into brain `memories`). **Intentionally machine-local — never federated** (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724): it is relationship-graph data, mirroring the deliberate "memory_links are instance-local" boundary in `memorySync.js` (memory *nodes* federate, the link graph does not), and is coupled to machine-local domains — `tribe_memory_links` extends the non-federated `memory_links` layer and `tribe_touchpoints` carry per-machine calendar-account refs. NO `sync_sequence`, no peer-sync record kind, no `dataSync` category. Adapter: `server/services/tribe.js`.- `creative_commissions` — Creative Commissions (Autonomous Creation Engine, #2657/#2686): standing recurring creative briefs that fire on a cron cadence and drive the Creative Director directive pipeline unattended. One row per commission, the full sanitized record in `data` JSONB with `name`/`enabled`/`created_at`/`updated_at` mirrored into columns for the scheduler's "arm every enabled commission" query. The brief/identity federates as `creativeCommission` so synced feedback can attach to the same commission; `schedule`, `runs`, `assignment`, `enabled`, and feedback view stay machine-local (the per-reaction `commissionFeedback` records federate separately). The opt-in Digital Twin music-taste configuration is bounded brief metadata; raw taste sources and per-run recipes never cross the wire. The file backend is the `NODE_ENV=test`/`MEMORY_BACKEND=file` escape hatch only. Adapter: `server/services/creativeCommissions/db.js`, selected pg-vs-file by `server/services/creativeCommissions/store.js` (file backend is the `NODE_ENV=test`/`MEMORY_BACKEND=file` escape hatch only).- `games` — Game studio workspaces (#3177): one row per managed-app asset plan, with the full reusable sprite/music binding set, current compiled-manifest pointer, compile history, and user-requested AI feedback history in `data` JSONB; `app_id`/`name`/`updated_at` are mirrored for list and relationship queries. The record is **machine-local** because managed-app registration, sprite atlases, and music-library bytes are machine-local; there is no peer-sync cursor or tombstone, and deletes are hard deletes. Compiled manifests are immutable, SHA-256-addressed artifacts under `data/games/{id}/manifests/`; their pointers and hashes live in the DB record. Adapter: `server/services/games/db.js`, selected pg-vs-collectionStore by `server/services/games/store.js` (collectionStore is test/unsupported file escape hatch only).diff --git a/scripts/migrations/315-voice-profiles-table.js b/scripts/migrations/315-voice-profiles-table.jsnew file mode 100644index 0000000000..a2f4186830--- /dev/null+++ b/scripts/migrations/315-voice-profiles-table.js@@ -0,0 +1,14 @@+/**+ * Register machine-local character voice profiles (issue #5380).+ *+ * The additive `voice_profiles` DDL lives in `ensureSchema()` and+ * `server/scripts/init-db.sql`: this runner is intentionally before the+ * database pool exists, so it only records the rollout in the migration+ * ledger. New installs receive the same idempotent schema at boot.+ */++export default {+ async up() {+ console.log('🎙️ voice_profiles: table created idempotently by ensureSchema at boot; nothing to do in the file runner');+ },+};diff --git a/server/lib/db.catalogDdlParity.test.js b/server/lib/db.catalogDdlParity.test.jsindex 9ed6d4463a..2f88ea5866 100644--- a/server/lib/db.catalogDdlParity.test.js+++ b/server/lib/db.catalogDdlParity.test.js@@ -276,6 +276,19 @@ describe('catalog DDL parity (init-db.sql ↔ db.js ensureSchema)', () => {expect(sqlIdx.size).toBeGreaterThan(0);});+ it('voice_profiles has the same columns and indexes in both files', () => {+ const sqlBody = extractCreateTable(INIT_SQL, 'voice_profiles');+ const jsBody = extractCreateTable(DB_JS, 'voice_profiles');+ expect(sqlBody, 'init-db.sql missing CREATE TABLE voice_profiles').toBeTruthy();+ expect(jsBody, 'db.js missing CREATE TABLE voice_profiles').toBeTruthy();+ expect([...new Set(extractColumnNames(sqlBody))].sort())+ .toEqual([...new Set(extractColumnNames(jsBody))].sort());+ const sqlIdx = extractIndexNames(INIT_SQL, 'idx_voice_profiles_');+ const jsIdx = extractIndexNames(DB_JS, 'idx_voice_profiles_');+ expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());+ expect(sqlIdx.size).toBeGreaterThan(0);+ });+// Pipeline series (#1015) — non-`catalog_`-prefixed table in BOTH DDL// sources, with non-`idx_catalog_`-prefixed indexes, so its own assertion.it('pipeline_series has the same columns and indexes in both files', () => {diff --git a/server/lib/db/schema/README.md b/server/lib/db/schema/README.mdindex 24b8fc470f..5ec06c0092 100644--- a/server/lib/db/schema/README.md+++ b/server/lib/db/schema/README.md@@ -25,7 +25,7 @@ Parity with `server/scripts/init-db.sql` (the fresh-install path) is locked by| `commissions.js` | `commissionsDdl` | Creative Commissions + feedback (machine-local) || `catalog.js` | `catalogDdl`, `catalogUserTypesDdl` | Catalog scraps/ingredients/tags/media + user-defined types || `media.js` | `mediaDdl` | Creative-director / music-video projects, mood boards, media assets |-| `universes.js` | `universesDdl` | Universes + universe run history |+| `universes.js` | `universesDdl` | Universes, machine-local character voice profiles, + universe run history || `library.js` | `libraryDdl` | Authors, artists, albums, tracks || `pipeline.js` | `pipelineDdl` | Pipeline series, issues, story-builder sessions || `writersRoom.js` | `writersRoomDdl` | Writers-Room folders, works, draft versions, exercises |diff --git a/server/lib/db/schema/universes.js b/server/lib/db/schema/universes.jsindex 38ec7db320..edbc7e3649 100644--- a/server/lib/db/schema/universes.js+++ b/server/lib/db/schema/universes.js@@ -1,4 +1,4 @@-// Universe DDL — universes + universe run history. Extracted verbatim from+// Universe DDL — universes, local character voice profiles, + universe run history. Extracted verbatim from// ensureSchemaImpl() in server/lib/db.js (#2832); idempotent, runs on every boot.export const universesDdl = [// Universe Builder records (Phase 3 Create migration, issue #1014). One row@@ -32,6 +32,23 @@ export const universesDdl = [`CREATE INDEX IF NOT EXISTS idx_universes_live ON universes (deleted) WHERE deleted = FALSE`,`CREATE INDEX IF NOT EXISTS idx_universes_updated ON universes (updated_at)`,+ // Machine-local character voice profiles (#5380). The portable character+ // canon remains inside the federated universe JSON; only a local binding+ // plus preset/artifact provenance live here. There is one approved profile+ // per universe/character pair, while the record's version tracks explicit+ // re-promotions of a preset.+ `CREATE TABLE IF NOT EXISTS voice_profiles (+ id TEXT PRIMARY KEY,+ universe_id TEXT NOT NULL,+ character_id TEXT NOT NULL,+ approval_status TEXT NOT NULL DEFAULT 'draft' CHECK (approval_status IN ('draft', 'approved', 'retired')),+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW()+ )`,+ `CREATE INDEX IF NOT EXISTS idx_voice_profiles_binding ON voice_profiles (universe_id, character_id, updated_at DESC)`,+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_voice_profiles_approved_binding ON voice_profiles (universe_id, character_id) WHERE approval_status = 'approved'`,+// Universe render-history log (issue #1014). The type-level `config.runs[]`// array collectionStore kept in data/universes/index.json (capped 200,// NEVER federated — per-peer local) becomes its own table. `universe_id` isdiff --git a/server/lib/paths.js b/server/lib/paths.jsindex 236621b81f..d44ff67d6e 100644--- a/server/lib/paths.js+++ b/server/lib/paths.js@@ -101,6 +101,10 @@ export const PATHS = {// LoRA training run artifacts (checkpoints/samples/cache per run). Run// RECORDS live in Postgres (lora_training_runs); only artifacts live here.trainingRuns: join(INSTALL_ROOT, 'data/training-runs'),+ // Character voice-profile metadata lives in PostgreSQL; this directory holds+ // the local benchmark WAVs and future engine artifacts referenced by it.+ // It deliberately stays machine-local and is included in normal data backups.+ voiceProfiles: join(INSTALL_ROOT, 'data/voice-profiles'),videos: join(INSTALL_ROOT, 'data/videos'),videoThumbnails: join(INSTALL_ROOT, 'data/video-thumbnails'),// Sprite Manager (issue #2895): per-record asset treesdiff --git a/server/routes/pipeline/audio.js b/server/routes/pipeline/audio.jsindex e5901f03fc..b903ef258d 100644--- a/server/routes/pipeline/audio.js+++ b/server/routes/pipeline/audio.js@@ -15,6 +15,7 @@ import { resolveSeriesLlmOverride } from '../../lib/seriesLlmOverride.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';+import { resolveCharacterVoice } from '../../services/voice/profiles.js';import {listMusicLibrary,importUploadedTrack,@@ -218,18 +219,34 @@ router.post('/issues/:id/stages/audio/lines/:lineIdx/render', asyncHandler(async// every per-line render pays two file reads it doesn't use.const needsCanon = !body.voiceId?.trim() && !line.voiceIdOverride && line.characterId;let canon = null;+ let series = null;if (needsCanon) {- const series = await seriesSvc.getSeries(issue.seriesId).catch(() => null);+ series = await seriesSvc.getSeries(issue.seriesId).catch(() => null);if (series) canon = await getSeriesCanon(series);}- const voiceId = resolveVoiceForLine(line, canon, { explicit: body.voiceId });- const synthResult = await synthesizeToFile({ text: line.text, voiceId })+ const characterVoiceId = resolveVoiceForLine(line, canon, { explicit: body.voiceId });+ const profileResolution = needsCanon && series?.universeId+ ? await resolveCharacterVoice({+ universeId: series.universeId,+ characterId: line.characterId,+ characterVoiceId,+ route: 'studio',+ })+ : null;+ const voiceId = profileResolution?.voiceId ?? characterVoiceId;+ const synthResult = await synthesizeToFile({+ text: line.text,+ voiceId,+ profileId: profileResolution?.profileId || undefined,+ route: 'studio',+ }).catch((err) => { throw mapServiceError(err); });const nextLines = [...lines];nextLines[lineIdx] = {...line,audioJobId: null,audioFilename: synthResult.filename,+ ...(synthResult.provenance ? { voiceProvenance: synthResult.provenance } : {}),};const { issue: updatedIssue, stage } = await issuesSvc.updateStage(req.params.id, 'audio', {status: 'edited',@@ -241,6 +258,10 @@ router.post('/issues/:id/stages/audio/lines/:lineIdx/render', asyncHandler(asyncfilename: synthResult.filename,engine: synthResult.engine,voiceId: synthResult.voiceId || voiceId,+ profileId: synthResult.profileId,+ profileRevision: synthResult.profileRevision,+ degradedVoiceBinding: profileResolution?.degraded || false,+ voiceWarning: profileResolution?.warning || null,});}));diff --git a/server/routes/voice.js b/server/routes/voice.jsindex 0ad91e6fcb..b956f73aad 100644--- a/server/routes/voice.js+++ b/server/routes/voice.js@@ -13,7 +13,9 @@ import { getVoiceConfig, updateVoiceConfig } from '../services/voice/config.js';import { checkAll, invalidateHealthCache } from '../services/voice/health.js';import * as facetimeBridge from '../services/voice/facetimeBridge.js';import { reconcile, verifyBinaries, verifyModels, downloadPiperVoice, startWhisper, stopWhisper } from '../services/voice/bootstrap.js';-import { synthesize, listVoices, VALID_ENGINES } from '../services/voice/tts.js';+import { synthesize, listVoices, listVoiceEngines, VALID_ENGINES } from '../services/voice/tts.js';+import { listVoiceProfiles, promotePresetProfile } from '../services/voice/profiles.js';+import { renderProfileBenchmark } from '../services/voice/profileBenchmarks.js';import { readyState as kokoroReadyState, unloadKokoro, loadedModelKey as kokoroLoadedKey } from '../services/voice/tts-kokoro.js';import { findPiperVoice } from '../services/voice/piper-voices.js';import { speakProactive, HHMM_RE, MAX_PROACTIVE_TEXT_LEN } from '../services/voice/proactiveSpeech.js';@@ -200,6 +202,51 @@ router.get('/voices', asyncHandler(async (req, res) => {res.json(await listVoices(validEngine(req.query?.engine)));}));+const voiceProfileListSchema = z.object({+ universeId: z.string().trim().min(1).max(160).optional(),+ characterId: z.string().trim().min(1).max(160).optional(),+}).strict();+const promotePresetProfileSchema = z.object({+ universeId: z.string().trim().min(1).max(160),+ characterId: z.string().trim().min(1).max(160),+ characterName: z.string().trim().max(160).optional(),+ voiceId: z.string().trim().min(1).max(160),+}).strict();+const profileIdParamsSchema = z.object({+ id: z.string().trim().regex(/^[a-z0-9][a-z0-9-]{0,79}$/),+}).strict();++// The profile endpoints live behind the normal /api/voice auth gate. Unlike+// `/api/voice/public`, they expose local binding metadata and benchmark+// artifacts, so they are never externally reopened by apiAccess.voice.+router.get('/engines', asyncHandler(async (_req, res) => {+ res.json({ engines: await listVoiceEngines() });+}));++router.get('/profiles', asyncHandler(async (req, res) => {+ const filters = validateRequest(voiceProfileListSchema, req.query || {});+ res.json({ profiles: await listVoiceProfiles(filters) });+}));++router.post('/profiles/preset', asyncHandler(async (req, res) => {+ const body = validateRequest(promotePresetProfileSchema, req.body || {});+ const cfg = await getVoiceConfig();+ const profile = await promotePresetProfile({+ ...body,+ modelRevision: /^kokoro:/i.test(body.voiceId)+ ? `${cfg.tts.kokoro?.modelId || 'configured'}:${cfg.tts.kokoro?.dtype || 'configured'}`+ : `piper:${body.voiceId.slice('piper:'.length)}`,+ delivery: { rate: cfg.tts?.rate },+ });+ res.status(201).json({ profile });+}));++router.post('/profiles/:id/benchmark', asyncHandler(async (req, res) => {+ const { id: profileId } = validateRequest(profileIdParamsSchema, req.params);+ const profile = await renderProfileBenchmark(profileId);+ res.json({ profile });+}));+// POST /api/voice/piper/fetch — download a single Piper voice on demand.// Validates against the curated catalog to keep shell interpolation safe.router.post('/piper/fetch', asyncHandler(async (req, res) => {diff --git a/server/routes/voice.test.js b/server/routes/voice.test.jsindex 2ea6bbcc61..1cc1560d78 100644--- a/server/routes/voice.test.js+++ b/server/routes/voice.test.js@@ -26,8 +26,16 @@ vi.mock('../services/voice/bootstrap.js', () => ({vi.mock('../services/voice/tts.js', () => ({synthesize: vi.fn(),listVoices: vi.fn(),+ listVoiceEngines: vi.fn(),VALID_ENGINES: new Set(['kokoro', 'piper']),}));+vi.mock('../services/voice/profiles.js', () => ({+ listVoiceProfiles: vi.fn(),+ promotePresetProfile: vi.fn(),+}));+vi.mock('../services/voice/profileBenchmarks.js', () => ({+ renderProfileBenchmark: vi.fn(),+}));// GET /api/voice/tts/status + POST /api/voice/tts/unload destructure these at// module load — mock them so the route resolves without spinning up Kokoro.vi.mock('../services/voice/tts-kokoro.js', () => ({@@ -56,6 +64,8 @@ import * as config from '../services/voice/config.js';import * as health from '../services/voice/health.js';import * as bootstrap from '../services/voice/bootstrap.js';import * as tts from '../services/voice/tts.js';+import * as voiceProfiles from '../services/voice/profiles.js';+import * as profileBenchmarks from '../services/voice/profileBenchmarks.js';import { ServerError } from '../lib/errorHandler.js';import * as piperVoices from '../services/voice/piper-voices.js';import * as proactiveSpeech from '../services/voice/proactiveSpeech.js';@@ -72,7 +82,7 @@ errorEvents.on('error', () => {});const DEFAULT_CFG = {enabled: false,stt: { engine: 'web-speech', endpoint: 'http://127.0.0.1:5562' },- tts: { engine: 'kokoro' },+ tts: { engine: 'kokoro', rate: 1, kokoro: { modelId: 'kokoro-test', dtype: 'q8' } },};const buildApp = ({ io = { emit: () => {} } } = {}) => {@@ -93,6 +103,42 @@ describe('Voice Routes', () => {config.getVoiceConfig.mockResolvedValue(DEFAULT_CFG);});+ describe('machine-local voice profiles', () => {+ it('reports the preset engine capability contract', async () => {+ tts.listVoiceEngines.mockResolvedValue([{ id: 'kokoro', capabilities: { preset: true, formant: false } }]);+ const res = await request(buildApp()).get('/api/voice/engines');+ expect(res.status).toBe(200);+ expect(res.body.engines).toEqual([{ id: 'kokoro', capabilities: { preset: true, formant: false } }]);+ });++ it('lists only the requested machine-local character binding', async () => {+ voiceProfiles.listVoiceProfiles.mockResolvedValue([{ id: 'voice-profile-1' }]);+ const res = await request(buildApp()).get('/api/voice/profiles?universeId=uni-1&characterId=char-1');+ expect(res.status).toBe(200);+ expect(voiceProfiles.listVoiceProfiles).toHaveBeenCalledWith({ universeId: 'uni-1', characterId: 'char-1' });+ expect(res.body.profiles).toEqual([{ id: 'voice-profile-1' }]);+ });++ it('promotes a preset with the current local model and delivery provenance', async () => {+ voiceProfiles.promotePresetProfile.mockResolvedValue({ id: 'voice-profile-1' });+ const res = await request(buildApp()).post('/api/voice/profiles/preset').send({+ universeId: 'uni-1', characterId: 'char-1', voiceId: 'kokoro:af_heart',+ });+ expect(res.status).toBe(201);+ expect(voiceProfiles.promotePresetProfile).toHaveBeenCalledWith(expect.objectContaining({+ modelRevision: 'kokoro-test:q8', delivery: { rate: 1 },+ }));+ expect(res.body).toEqual({ profile: { id: 'voice-profile-1' } });+ });++ it('runs fixed benchmarks only for a valid profile id', async () => {+ profileBenchmarks.renderProfileBenchmark.mockResolvedValue({ id: 'voice-profile-1' });+ const res = await request(buildApp()).post('/api/voice/profiles/voice-profile-1/benchmark').send({});+ expect(res.status).toBe(200);+ expect(profileBenchmarks.renderProfileBenchmark).toHaveBeenCalledWith('voice-profile-1');+ });+ });+describe('GET /api/voice/config', () => {it('returns the merged voice config', async () => {const res = await request(buildApp()).get('/api/voice/config');diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex 62a817118d..a56f75779a 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -922,6 +922,21 @@ CREATE TABLE IF NOT EXISTS universes (CREATE INDEX IF NOT EXISTS idx_universes_live ON universes (deleted) WHERE deleted = FALSE;CREATE INDEX IF NOT EXISTS idx_universes_updated ON universes (updated_at);+-- Machine-local character voice profiles (#5380). Portable character voice+-- direction stays in the federated universe record; profile bindings, local+-- preset/artifact metadata, and rendered benchmark provenance stay here.+CREATE TABLE IF NOT EXISTS voice_profiles (+ id TEXT PRIMARY KEY,+ universe_id TEXT NOT NULL,+ character_id TEXT NOT NULL,+ approval_status TEXT NOT NULL DEFAULT 'draft' CHECK (approval_status IN ('draft', 'approved', 'retired')),+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW()+);+CREATE INDEX IF NOT EXISTS idx_voice_profiles_binding ON voice_profiles (universe_id, character_id, updated_at DESC);+CREATE UNIQUE INDEX IF NOT EXISTS idx_voice_profiles_approved_binding ON voice_profiles (universe_id, character_id) WHERE approval_status = 'approved';+-- Universe render-history log (issue #1014). The type-level `config.runs[]` array-- collectionStore kept in data/universes/index.json (capped 200, NEVER federated-- — per-peer local) becomes its own table. `universe_id` is a soft ref (no FK):diff --git a/server/services/pipeline/audio.js b/server/services/pipeline/audio.jsindex 58d3a65cef..9b5d967cd8 100644--- a/server/services/pipeline/audio.js+++ b/server/services/pipeline/audio.js@@ -227,17 +227,24 @@ export function wavDurationMs(buffer) {return Math.round((dataSize / byteRate) * 1000);}-export async function synthesizeToFile({ text, voiceId, signal } = {}) {+export async function synthesizeToFile({ text, voiceId, profileId, route = 'studio', signal } = {}) {const trimmed = (text || '').trim();if (!trimmed) {throw new ServerError('text is required', { status: 400, code: 'PIPELINE_AUDIO_EMPTY_TEXT' });}const { engine, voice } = parseVoiceId(voiceId);const opts = { signal };+ if (profileId) {+ opts.profileId = profileId;+ opts.route = route;+ }if (engine) opts.engine = engine;if (voice) opts.voice = voice;- const { wav, latencyMs, engine: usedEngine } = await synthesize(trimmed, opts);+ const {+ wav, latencyMs, engine: usedEngine,+ profileId: usedProfileId, profileRevision, provenance,+ } = await synthesize(trimmed, opts);await ensureDir(PATHS.audio);// UUID filename keeps two simultaneous renders from colliding; the line's// audioJobId-or-audioFilename binding lives in stages.audio.lines[].@@ -249,5 +256,8 @@ export async function synthesizeToFile({ text, voiceId, signal } = {}) {durationMs: wavDurationMs(wav),engine: usedEngine,voiceId: voice ? `${usedEngine}:${voice}` : null,+ profileId: usedProfileId || null,+ profileRevision: profileRevision || null,+ provenance: provenance || null,};}diff --git a/server/services/pipeline/audio.test.js b/server/services/pipeline/audio.test.jsindex 445f785046..64cab8c65b 100644--- a/server/services/pipeline/audio.test.js+++ b/server/services/pipeline/audio.test.js@@ -144,6 +144,22 @@ describe('synthesizeToFile', () => {expect(passed).not.toHaveProperty('voice');});+ it('passes a resolved profile through and preserves its render provenance', async () => {+ synthesizeMock.mockResolvedValue({+ wav: Buffer.from('w'), latencyMs: 1, engine: 'kokoro',+ profileId: 'voice-profile-1', profileRevision: 2,+ provenance: { profileId: 'voice-profile-1', profileRevision: 2, engine: 'kokoro' },+ });+ const result = await synthesizeToFile({+ text: 'hi', voiceId: 'kokoro:af_heart', profileId: 'voice-profile-1', route: 'studio',+ });+ expect(synthesizeMock).toHaveBeenCalledWith('hi', expect.objectContaining({+ profileId: 'voice-profile-1', route: 'studio',+ }));+ expect(result).toMatchObject({ profileId: 'voice-profile-1', profileRevision: 2 });+ expect(result.provenance).toMatchObject({ profileId: 'voice-profile-1' });+ });+it('returns the measured WAV duration (ms) for the narration timeline', async () => {// 24000 samples of 16-bit mono @ 24kHz = exactly 1 second.synthesizeMock.mockResolvedValue({ wav: makeWav({ dataBytes: 24000 * 2 }), latencyMs: 5, engine: 'kokoro' });diff --git a/server/services/pipeline/issuesShared.js b/server/services/pipeline/issuesShared.jsindex 0ae7146784..c81ddc00fd 100644--- a/server/services/pipeline/issuesShared.js+++ b/server/services/pipeline/issuesShared.js@@ -461,11 +461,37 @@ export const sanitizeLineOffset = (raw) => {if (!Number.isFinite(n) || n < 0) return null;return Math.min(n, AUDIO_LINE_OFFSET_MAX_SEC);};++// Render provenance is local production evidence, not a portable voice binding:+// it records which approved local revision created a WAV without writing a+// machine-local profile id back into the federated Universe character record.+const sanitizeVoiceProvenance = (raw) => {+ if (!raw || typeof raw !== 'object') return null;+ const profileId = trimTo(raw.profileId, 80);+ const engine = trimTo(raw.engine, 32);+ if (!profileId || !engine) return null;+ return {+ profileId,+ profileRevision: Number.isInteger(raw.profileRevision) && raw.profileRevision > 0 ? raw.profileRevision : null,+ engine,+ modelRevision: trimTo(raw.modelRevision, 240) || null,+ effectiveControls: {+ rate: Number.isFinite(raw?.effectiveControls?.rate) ? raw.effectiveControls.rate : null,+ },+ mastering: {+ chain: Array.isArray(raw?.mastering?.chain)+ ? raw.mastering.chain.map((step) => trimTo(step, 80)).filter(Boolean).slice(0, 12)+ : [],+ },+ };+};+const sanitizeAudioLine = (raw, i) => {if (!raw || typeof raw !== 'object') return null;const text = trimTo(raw.text, AUDIO_LINE_TEXT_MAX);if (!text) return null;const id = trimTo(raw.id, AUDIO_LINE_ID_MAX) || `line-${String(i + 1).padStart(3, '0')}`;+ const voiceProvenance = sanitizeVoiceProvenance(raw.voiceProvenance);return {id,characterId: trimTo(raw.characterId, 80) || null,@@ -479,6 +505,7 @@ const sanitizeAudioLine = (raw, i) => {// Per-line start offset for muxing VO into the stitched episode (Phase// 4d.2). null until the user (or a future auto-spacer) places it.offsetSec: sanitizeLineOffset(raw.offsetSec),+ ...(voiceProvenance ? { voiceProvenance } : {}),};};diff --git a/server/services/voice/profileBenchmarks.js b/server/services/voice/profileBenchmarks.jsnew file mode 100644index 0000000000..abf91a95e9--- /dev/null+++ b/server/services/voice/profileBenchmarks.js@@ -0,0 +1,63 @@+/** Fixed, reproducible benchmark rendering for approved local voice profiles. */++import { mkdir, writeFile } from 'node:fs/promises';+import { join } from 'node:path';+import { synthesize } from './tts.js';+import {+ getProfileForSynthesis,+ profileArtifactDirectory,+ saveProfileBenchmark,+} from './profiles.js';++export const VOICE_PROFILE_BENCHMARK_LINES = Object.freeze([+ { key: 'identity', text: 'This is {character}. I will keep my voice clear, steady, and recognizably mine.' },+ { key: 'articulation', text: 'At 7:15, six silver ships crossed the station with crisp, patient precision.' },+ { key: 'calm', text: 'Take a breath. We have time to look carefully before we decide what comes next.' },+ { key: 'amused', text: 'That was almost convincing. Almost is doing an impressive amount of work today.' },+ { key: 'urgent', text: 'Listen closely: move now, stay together, and do not lose sight of the exit.' },+ { key: 'long-form', text: 'I remember the promise, the weather, and the exact moment the room became quiet. That is why I am still here.' },+]);++const benchmarkLinesFor = (profile) => {+ const character = profile.label || 'this character';+ return VOICE_PROFILE_BENCHMARK_LINES.map((line) => ({+ ...line,+ text: line.text.replace('{character}', character),+ }));+};++/**+ * Render each benchmark line sequentially. Local engines are intentionally+ * serialized: Kokoro has one resident model and Piper spawns one process per+ * line, so concurrency only increases contention and muddles timings.+ */+export async function renderProfileBenchmark(profileId, { signal } = {}) {+ const profile = await getProfileForSynthesis(profileId, 'studio');+ const directory = join(profileArtifactDirectory(profile.id), 'benchmarks', `v${profile.version}`);+ await mkdir(directory, { recursive: true });+ const lines = [];+ for (const [index, line] of benchmarkLinesFor(profile).entries()) {+ const result = await synthesize(line.text, {+ profileId: profile.id,+ route: 'studio',+ signal,+ });+ const filename = `${String(index + 1).padStart(2, '0')}-${line.key}.wav`;+ await writeFile(join(directory, filename), result.wav);+ lines.push({+ key: line.key,+ text: line.text,+ filename: `voice-profiles/${profile.id}/benchmarks/v${profile.version}/${filename}`,+ latencyMs: result.latencyMs,+ engine: result.engine,+ modelRevision: result.provenance?.modelRevision || profile.modelRevision,+ effectiveControls: result.provenance?.effectiveControls || { rate: null },+ });+ }+ return saveProfileBenchmark(profile, {+ profileRevision: profile.version,+ renderedAt: new Date().toISOString(),+ lines,+ mastering: profile.mastering,+ });+}diff --git a/server/services/voice/profileBenchmarks.test.js b/server/services/voice/profileBenchmarks.test.jsnew file mode 100644index 0000000000..827cc7c964--- /dev/null+++ b/server/services/voice/profileBenchmarks.test.js@@ -0,0 +1,52 @@+import { describe, expect, it, vi } from 'vitest';++vi.mock('./tts.js', () => ({ synthesize: vi.fn() }));+vi.mock('./profiles.js', () => ({+ getProfileForSynthesis: vi.fn(),+ profileArtifactDirectory: vi.fn((id) => `/tmp/${id}`),+ saveProfileBenchmark: vi.fn(),+}));+vi.mock('node:fs/promises', () => ({ mkdir: vi.fn(), writeFile: vi.fn() }));++import { mkdir, writeFile } from 'node:fs/promises';+import { synthesize } from './tts.js';+import {+ getProfileForSynthesis,+ profileArtifactDirectory,+ saveProfileBenchmark,+} from './profiles.js';+import { VOICE_PROFILE_BENCHMARK_LINES, renderProfileBenchmark } from './profileBenchmarks.js';++const PROFILE = {+ id: 'voice-profile-1', version: 2, label: 'Example Character',+ mastering: { chain: ['preset-output:unprocessed'] },+};++describe('voice profile benchmarks', () => {+ it('renders the fixed script sequentially and records profile-scoped provenance', async () => {+ getProfileForSynthesis.mockResolvedValue(PROFILE);+ synthesize.mockResolvedValue({+ wav: Buffer.from('wav'), latencyMs: 24, engine: 'kokoro',+ provenance: { modelRevision: 'kokoro-test:q8', effectiveControls: { rate: 1 } },+ });+ saveProfileBenchmark.mockImplementation(async (_profile, benchmark) => ({ ...PROFILE, benchmark }));++ const result = await renderProfileBenchmark(PROFILE.id);++ expect(getProfileForSynthesis).toHaveBeenCalledWith(PROFILE.id, 'studio');+ expect(profileArtifactDirectory).toHaveBeenCalledWith(PROFILE.id);+ expect(mkdir).toHaveBeenCalledWith(`/tmp/${PROFILE.id}/benchmarks/v2`, { recursive: true });+ expect(synthesize).toHaveBeenCalledTimes(VOICE_PROFILE_BENCHMARK_LINES.length);+ expect(synthesize).toHaveBeenNthCalledWith(1, expect.stringContaining('Example Character'), {+ profileId: PROFILE.id, route: 'studio', signal: undefined,+ });+ expect(writeFile).toHaveBeenCalledTimes(VOICE_PROFILE_BENCHMARK_LINES.length);+ expect(result.benchmark).toMatchObject({+ profileRevision: 2,+ mastering: PROFILE.mastering,+ });+ expect(result.benchmark.lines[0]).toMatchObject({+ filename: `voice-profiles/${PROFILE.id}/benchmarks/v2/01-identity.wav`, modelRevision: 'kokoro-test:q8',+ });+ });+});diff --git a/server/services/voice/profiles.js b/server/services/voice/profiles.jsnew file mode 100644index 0000000000..6c8b6ac43c--- /dev/null+++ b/server/services/voice/profiles.js@@ -0,0 +1,362 @@+/**+ * Machine-local character voice profiles (#5380).+ *+ * Universe characters retain only portable voice direction and their legacy+ * namespaced preset id. This module owns the local, DB-primary binding that+ * can be promoted independently on each install, plus the managed directory+ * that holds benchmark renders and future engine artifacts.+ */++import { randomUUID } from 'node:crypto';+import { mkdir } from 'node:fs/promises';+import { join } from 'node:path';+import { query } from '../../lib/db.js';+import { ServerError } from '../../lib/errorHandler.js';+import { PATHS } from '../../lib/paths.js';++export const VOICE_PROFILE_ENGINES = new Set(['kokoro', 'piper']);+export const VOICE_PROFILE_ROUTES = new Set(['studio', 'interactive']);++const PROFILE_ID_RE = /^[a-z0-9][a-z0-9-]{0,79}$/;+const MAX_ID = 160;+const MAX_LABEL = 160;+const MAX_REVISION = 240;+const MAX_BENCHMARK_LINES = 12;+const DEFAULT_DELIVERY = Object.freeze({ rate: 1, pitchSemitones: null, formantSemitones: null });+// This initial preset wrapper deliberately makes no opaque DSP changes. Naming+// the no-op is still useful provenance: an old render can be distinguished+// from a later profile revision that does add a supported mastering step.+const DEFAULT_MASTERING = Object.freeze({ chain: ['preset-output:unprocessed'] });+const SAFE_ASSET_BASENAME = /^[a-z0-9][a-z0-9._-]{0,159}$/i;++const trim = (value, max) => typeof value === 'string' ? value.trim().slice(0, max) : '';+const timestamp = () => new Date().toISOString();+const positiveInteger = (value, fallback = 1) =>+ Number.isInteger(value) && value > 0 ? value : fallback;++export function parsePresetVoiceId(voiceId) {+ const value = trim(voiceId, MAX_ID);+ const match = /^([a-z][a-z0-9-]*):([^:\s]+)$/i.exec(value);+ if (!match) return null;+ const engine = match[1].toLowerCase();+ if (!VOICE_PROFILE_ENGINES.has(engine)) return null;+ return { engine, voice: match[2], voiceId: `${engine}:${match[2]}` };+}++const sanitizeRoutes = (raw) => Object.fromEntries(+ [...VOICE_PROFILE_ROUTES].map((route) => [route, {+ enabled: raw?.[route]?.enabled === true,+ }]),+);++const boundedNumber = (value, min, max, fallback) =>+ Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : fallback;++const sanitizeDelivery = (raw) => ({+ // Rate is implemented by both preset engines. Pitch/formant are intentionally+ // represented as null rather than zero: zero would claim that an unavailable+ // transform was applied, while null makes the disabled state explicit.+ rate: boundedNumber(raw?.rate, 0.25, 4, DEFAULT_DELIVERY.rate),+ pitchSemitones: null,+ formantSemitones: null,+});++const sanitizeMastering = (raw) => ({+ // An explicit empty chain means the initial preset wrapper applies no hidden+ // mastering. That is distinct from an absent profile and keeps provenance+ // honest until a capability-probed mastering adapter is added.+ chain: Array.isArray(raw?.chain)+ ? raw.chain.map((step) => trim(step, 80)).filter(Boolean).slice(0, 12)+ : [...DEFAULT_MASTERING.chain],+});++const sanitizeBenchmark = (raw) => {+ if (!raw || typeof raw !== 'object') return null;+ const renderedAt = trim(raw.renderedAt, 64);+ const lines = Array.isArray(raw.lines) ? raw.lines.map((line) => {+ const filename = trim(line?.filename, 200);+ if (!filename) return null;+ return {+ key: trim(line.key, 64),+ text: trim(line.text, 1000),+ filename,+ latencyMs: Number.isFinite(line.latencyMs) ? Math.max(0, Math.round(line.latencyMs)) : null,+ engine: VOICE_PROFILE_ENGINES.has(line.engine) ? line.engine : null,+ modelRevision: trim(line.modelRevision, MAX_REVISION) || null,+ effectiveControls: {+ rate: Number.isFinite(line?.effectiveControls?.rate) ? line.effectiveControls.rate : null,+ },+ };+ }).filter(Boolean).slice(0, MAX_BENCHMARK_LINES) : [];+ if (!renderedAt || lines.length === 0) return null;+ return {+ profileRevision: positiveInteger(raw.profileRevision),+ renderedAt,+ lines,+ mastering: sanitizeMastering(raw.mastering),+ };+};++const sanitizeSourceAssets = (raw) => Array.isArray(raw)+ ? raw.map((asset) => {+ const filename = trim(asset?.filename, 160);+ if (!SAFE_ASSET_BASENAME.test(filename)) return null;+ return {+ filename,+ sha256: /^[a-f0-9]{64}$/i.test(trim(asset?.sha256, 64)) ? trim(asset.sha256, 64).toLowerCase() : null,+ transcript: trim(asset?.transcript, 4000) || null,+ rightsConfirmedAt: trim(asset?.rightsConfirmedAt, 64) || null,+ };+ }).filter(Boolean).slice(0, 24)+ : [];++/** Turn a raw DB JSON payload into the durable public profile shape. */+export function sanitizeVoiceProfile(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const id = trim(raw.id, 80);+ const universeId = trim(raw?.binding?.universeId, MAX_ID);+ const characterId = trim(raw?.binding?.characterId, MAX_ID);+ const preset = parsePresetVoiceId(raw.voiceId);+ if (!PROFILE_ID_RE.test(id) || !universeId || !characterId || !preset) return null;++ const approvalStatus = raw?.approval?.status === 'approved'+ ? 'approved'+ : raw?.approval?.status === 'retired' ? 'retired' : 'draft';+ const createdAt = trim(raw.createdAt, 64) || timestamp();+ const updatedAt = trim(raw.updatedAt, 64) || createdAt;+ return {+ id,+ version: positiveInteger(raw.version),+ binding: { universeId, characterId },+ label: trim(raw.label, MAX_LABEL) || null,+ kind: 'preset',+ engine: preset.engine,+ voiceId: preset.voiceId,+ modelRevision: trim(raw.modelRevision, MAX_REVISION) || 'configured-preset',+ // Preset profiles start empty. The same shape is ready for future,+ // user-supplied source recordings without ever accepting a path string.+ sourceAssets: sanitizeSourceAssets(raw.sourceAssets),+ routes: sanitizeRoutes(raw.routes),+ delivery: sanitizeDelivery(raw.delivery),+ mastering: sanitizeMastering(raw.mastering),+ approval: {+ status: approvalStatus,+ approvedAt: approvalStatus === 'approved' ? trim(raw?.approval?.approvedAt, 64) || updatedAt : null,+ benchmarkRevision: positiveInteger(raw?.approval?.benchmarkRevision),+ },+ benchmark: sanitizeBenchmark(raw.benchmark),+ createdAt,+ updatedAt,+ };+}++const profileDirectory = (id) => join(PATHS.voiceProfiles, id);++export function profileArtifactDirectory(id) {+ if (!PROFILE_ID_RE.test(id || '')) {+ throw new ServerError('invalid voice profile id', { status: 400, code: 'VOICE_PROFILE_INVALID_ID' });+ }+ return profileDirectory(id);+}++const persist = async (profile) => {+ await query(+ `INSERT INTO voice_profiles (id, universe_id, character_id, approval_status, data, created_at, updated_at)+ VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7)+ ON CONFLICT (id) DO UPDATE SET+ universe_id = EXCLUDED.universe_id,+ character_id = EXCLUDED.character_id,+ approval_status = EXCLUDED.approval_status,+ data = EXCLUDED.data,+ updated_at = EXCLUDED.updated_at`,+ [+ profile.id,+ profile.binding.universeId,+ profile.binding.characterId,+ profile.approval.status,+ JSON.stringify(profile),+ profile.createdAt,+ profile.updatedAt,+ ],+ );+ return profile;+};++export async function getVoiceProfile(id) {+ const profileId = trim(id, 80);+ if (!PROFILE_ID_RE.test(profileId)) return null;+ const { rows } = await query('SELECT data FROM voice_profiles WHERE id = $1', [profileId]);+ return sanitizeVoiceProfile(rows[0]?.data);+}++export async function getVoiceProfileRequired(id) {+ const profile = await getVoiceProfile(id);+ if (!profile) {+ throw new ServerError('Voice profile not found', { status: 404, code: 'VOICE_PROFILE_NOT_FOUND' });+ }+ return profile;+}++export async function listVoiceProfiles({ universeId, characterId } = {}) {+ const clauses = [];+ const params = [];+ const universe = trim(universeId, MAX_ID);+ const character = trim(characterId, MAX_ID);+ if (universe) { params.push(universe); clauses.push(`universe_id = $${params.length}`); }+ if (character) { params.push(character); clauses.push(`character_id = $${params.length}`); }+ const { rows } = await query(+ `SELECT data FROM voice_profiles ${clauses.length ? `WHERE ${clauses.join(' AND ')}` : ''}+ ORDER BY updated_at DESC, id DESC`,+ params,+ );+ return rows.map((row) => sanitizeVoiceProfile(row.data)).filter(Boolean);+}++async function getBoundProfile(universeId, characterId) {+ const { rows } = await query(+ `SELECT data FROM voice_profiles+ WHERE universe_id = $1 AND character_id = $2+ ORDER BY updated_at DESC, id DESC LIMIT 1`,+ [universeId, characterId],+ );+ return sanitizeVoiceProfile(rows[0]?.data);+}++/**+ * Explicitly promote a selected Kokoro/Piper preset to the local character+ * binding. Re-promoting a different preset increments its reproducible+ * revision; the universe record itself remains untouched and federatable.+ */+export async function promotePresetProfile({+ universeId,+ characterId,+ characterName = '',+ voiceId,+ modelRevision = 'configured-preset',+ delivery = DEFAULT_DELIVERY,+} = {}) {+ const universe = trim(universeId, MAX_ID);+ const character = trim(characterId, MAX_ID);+ const preset = parsePresetVoiceId(voiceId);+ if (!universe || !character || !preset) {+ throw new ServerError('A universe, character, and Kokoro/Piper preset are required', {+ status: 400,+ code: 'VOICE_PROFILE_INVALID_PRESET',+ });+ }+ const current = await getBoundProfile(universe, character);+ const samePreset = current?.voiceId === preset.voiceId;+ const now = timestamp();+ const next = sanitizeVoiceProfile({+ ...current,+ id: current?.id || randomUUID(),+ version: current ? (samePreset ? current.version : current.version + 1) : 1,+ binding: { universeId: universe, characterId: character },+ label: trim(characterName, MAX_LABEL) || current?.label || null,+ kind: 'preset',+ engine: preset.engine,+ voiceId: preset.voiceId,+ modelRevision: trim(modelRevision, MAX_REVISION) || 'configured-preset',+ routes: current?.routes || { studio: { enabled: true }, interactive: { enabled: true } },+ delivery: current?.delivery || delivery,+ mastering: current?.mastering || DEFAULT_MASTERING,+ approval: {+ status: 'approved',+ approvedAt: now,+ benchmarkRevision: current ? (samePreset ? current.approval.benchmarkRevision : current.approval.benchmarkRevision + 1) : 1,+ },+ benchmark: samePreset ? current?.benchmark : null,+ createdAt: current?.createdAt || now,+ updatedAt: now,+ });+ await mkdir(profileDirectory(next.id), { recursive: true });+ return persist(next);+}++export async function saveProfileBenchmark(profile, benchmark) {+ const current = await getVoiceProfileRequired(profile?.id);+ const next = sanitizeVoiceProfile({+ ...current,+ benchmark,+ updatedAt: timestamp(),+ });+ return persist(next);+}++const assertRoute = (route) => {+ if (!VOICE_PROFILE_ROUTES.has(route)) {+ throw new ServerError('Unsupported voice profile route', { status: 400, code: 'VOICE_PROFILE_INVALID_ROUTE' });+ }+};++export async function getProfileForSynthesis(id, route = 'studio') {+ assertRoute(route);+ const profile = await getVoiceProfileRequired(id);+ if (profile.approval.status !== 'approved') {+ throw new ServerError('Voice profile is not approved', { status: 409, code: 'VOICE_PROFILE_UNAPPROVED' });+ }+ if (profile.routes[route]?.enabled !== true) {+ throw new ServerError(`Voice profile is not enabled for ${route}`, {+ status: 409,+ code: 'VOICE_PROFILE_ROUTE_DISABLED',+ });+ }+ return profile;+}++/**+ * Resolve a local profile before portable character/default voice fallbacks.+ * `degraded` is explicit so a peer without the local profile never looks like+ * it has silently honoured a character's approved local voice.+ */+export async function resolveCharacterVoice({+ universeId,+ characterId,+ characterVoiceId = null,+ route = 'studio',+} = {}) {+ assertRoute(route);+ const universe = trim(universeId, MAX_ID);+ const character = trim(characterId, MAX_ID);+ let unavailableProfile = null;+ if (universe && character) {+ const profiles = await listVoiceProfiles({ universeId: universe, characterId: character });+ const profile = profiles.find((item) =>+ item.approval.status === 'approved' && item.routes[route]?.enabled === true,+ );+ if (profile) {+ return {+ source: 'profile',+ profileId: profile.id,+ profileRevision: profile.version,+ voiceId: profile.voiceId,+ degraded: false,+ warning: null,+ };+ }+ unavailableProfile = profiles.find((item) => item.approval.status === 'approved') || null;+ }+ const preset = parsePresetVoiceId(characterVoiceId);+ if (preset) {+ return {+ source: 'character-preset',+ profileId: null,+ profileRevision: null,+ voiceId: preset.voiceId,+ degraded: Boolean(unavailableProfile),+ warning: unavailableProfile+ ? `The approved local voice profile is unavailable for ${route}; using the portable character preset.`+ : null,+ };+ }+ return {+ source: 'project-default',+ profileId: null,+ profileRevision: null,+ voiceId: null,+ degraded: true,+ warning: unavailableProfile+ ? `The approved local voice profile is unavailable for ${route} and has no portable character preset; using the project default.`+ : 'No approved local voice profile or character preset is available; using the project default.',+ };+}diff --git a/server/services/voice/profiles.test.js b/server/services/voice/profiles.test.jsnew file mode 100644index 0000000000..4df950bbf7--- /dev/null+++ b/server/services/voice/profiles.test.js@@ -0,0 +1,134 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++let voiceProfilesRoot = '';+const queryMock = vi.fn();++vi.mock('../../lib/db.js', () => ({ query: (...args) => queryMock(...args) }));+vi.mock('../../lib/paths.js', async () => {+ const actual = await vi.importActual('../../lib/paths.js');+ return { ...actual, PATHS: { ...actual.PATHS, get voiceProfiles() { return voiceProfilesRoot; } } };+});++const {+ parsePresetVoiceId,+ sanitizeVoiceProfile,+ promotePresetProfile,+ resolveCharacterVoice,+ getProfileForSynthesis,+ profileArtifactDirectory,+} = await import('./profiles.js');++const PROFILE = {+ id: 'voice-profile-1',+ version: 2,+ binding: { universeId: 'universe-1', characterId: 'character-1' },+ label: 'Example Character',+ kind: 'preset',+ engine: 'kokoro',+ voiceId: 'kokoro:af_heart',+ modelRevision: 'kokoro-test:q8',+ routes: { studio: { enabled: true }, interactive: { enabled: false } },+ delivery: { rate: 0.9, pitchSemitones: null, formantSemitones: null },+ mastering: { chain: ['preset-output:unprocessed'] },+ approval: { status: 'approved', approvedAt: '2026-08-29T00:00:00.000Z', benchmarkRevision: 2 },+ createdAt: '2026-08-29T00:00:00.000Z',+ updatedAt: '2026-08-29T00:00:00.000Z',+};++beforeEach(async () => {+ voiceProfilesRoot = await mkdtemp(join(tmpdir(), 'portos-voice-profiles-'));+ queryMock.mockReset();+});++afterEach(async () => {+ await rm(voiceProfilesRoot, { recursive: true, force: true });+});++describe('voice profile contract', () => {+ it('only accepts the initially supported namespaced preset engines', () => {+ expect(parsePresetVoiceId('kokoro:af_heart')).toEqual({+ engine: 'kokoro', voice: 'af_heart', voiceId: 'kokoro:af_heart',+ });+ expect(parsePresetVoiceId('piper:en_GB-jenny_dioco-medium')).toMatchObject({ engine: 'piper' });+ expect(parsePresetVoiceId('qwen3:designed')).toBeNull();+ expect(parsePresetVoiceId('af_heart')).toBeNull();+ });++ it('keeps local binding data valid while rejecting path-like profile ids', () => {+ expect(sanitizeVoiceProfile(PROFILE)).toMatchObject({+ id: 'voice-profile-1',+ binding: { universeId: 'universe-1', characterId: 'character-1' },+ routes: { studio: { enabled: true }, interactive: { enabled: false } },+ delivery: { rate: 0.9, pitchSemitones: null, formantSemitones: null },+ });+ expect(sanitizeVoiceProfile({ ...PROFILE, id: '../outside' })).toBeNull();+ expect(sanitizeVoiceProfile({+ ...PROFILE,+ sourceAssets: [+ { filename: 'approved-reference.wav', sha256: 'A'.repeat(64) },+ { filename: '../outside.wav', sha256: 'b'.repeat(64) },+ ],+ }).sourceAssets).toEqual([{+ filename: 'approved-reference.wav', sha256: 'a'.repeat(64), transcript: null, rightsConfirmedAt: null,+ }]);+ expect(() => profileArtifactDirectory('../outside')).toThrow(/invalid voice profile/i);+ });++ it('promotes a preset into a DB-primary local profile and creates its managed directory', async () => {+ queryMock+ .mockResolvedValueOnce({ rows: [] })+ .mockResolvedValueOnce({ rows: [] });+ const profile = await promotePresetProfile({+ universeId: 'universe-1',+ characterId: 'character-1',+ characterName: 'Example Character',+ voiceId: 'kokoro:af_heart',+ modelRevision: 'kokoro-test:q8',+ });+ expect(profile).toMatchObject({+ version: 1,+ voiceId: 'kokoro:af_heart',+ approval: { status: 'approved', benchmarkRevision: 1 },+ routes: { studio: { enabled: true }, interactive: { enabled: true } },+ delivery: { rate: 1, pitchSemitones: null, formantSemitones: null },+ });+ const { stat } = await import('node:fs/promises');+ expect((await stat(profileArtifactDirectory(profile.id))).isDirectory()).toBe(true);+ expect(queryMock.mock.calls.at(-1)[0]).toContain('INSERT INTO voice_profiles');+ });++ it('prefers an approved local profile and visibly degrades to a character preset or project default', async () => {+ queryMock.mockResolvedValueOnce({ rows: [{ data: PROFILE }] });+ await expect(resolveCharacterVoice({+ universeId: 'universe-1', characterId: 'character-1', characterVoiceId: 'piper:en_GB-jenny_dioco-medium',+ })).resolves.toMatchObject({ source: 'profile', profileId: PROFILE.id, degraded: false });++ queryMock.mockResolvedValueOnce({ rows: [] });+ await expect(resolveCharacterVoice({+ universeId: 'universe-1', characterId: 'character-1', characterVoiceId: 'piper:en_GB-jenny_dioco-medium',+ })).resolves.toMatchObject({ source: 'character-preset', degraded: false });++ queryMock.mockResolvedValueOnce({ rows: [] });+ await expect(resolveCharacterVoice({ universeId: 'universe-1', characterId: 'character-1' }))+ .resolves.toMatchObject({ source: 'project-default', degraded: true });+ });++ it('reports a route-disabled approved profile as unavailable before using the portable fallback', async () => {+ queryMock.mockResolvedValueOnce({ rows: [{ data: PROFILE }] });+ await expect(resolveCharacterVoice({+ universeId: 'universe-1', characterId: 'character-1',+ characterVoiceId: 'piper:en_GB-jenny_dioco-medium', route: 'interactive',+ })).resolves.toMatchObject({+ source: 'character-preset', degraded: true, warning: expect.stringMatching(/unavailable for interactive/i),+ });+ });++ it('rejects a profile on a disabled route instead of silently synthesizing it', async () => {+ queryMock.mockResolvedValueOnce({ rows: [{ data: PROFILE }] });+ await expect(getProfileForSynthesis(PROFILE.id, 'interactive'))+ .rejects.toMatchObject({ code: 'VOICE_PROFILE_ROUTE_DISABLED' });+ });+});diff --git a/server/services/voice/tts.js b/server/services/voice/tts.jsindex 788784f508..391f2b3892 100644--- a/server/services/voice/tts.js+++ b/server/services/voice/tts.js@@ -5,6 +5,8 @@ import { synthesizeKokoro, listKokoroVoices } from './tts-kokoro.js';import { synthesizePiper, listPiperVoices } from './tts-piper.js';import { findPiperVoice } from './piper-voices.js';import { isKokoroVoice } from './kokoro-voices.js';+import { getProfileForSynthesis } from './profiles.js';+import { which } from './bootstrap.js';import { ServerError } from '../../lib/errorHandler.js';// Single source of truth for the supported TTS engine names. Imported by@@ -12,6 +14,51 @@ import { ServerError } from '../../lib/errorHandler.js';// new engine (e.g. ElevenLabs) shows up in every consumer with one edit.export const VALID_ENGINES = new Set(['kokoro', 'piper']);+// Capability discovery is deliberately honest about the first two backends:+// they can wrap stable presets and honour a rate, but do not offer voice+// design/cloning, pitch/formant transforms, or streaming controls. A future+// engine can expand this contract without making the Voice Lab expose a knob+// that the selected backend silently ignores.+let voiceTransformProbe = null;++const probeVoiceTransforms = () => {+ if (!voiceTransformProbe) {+ voiceTransformProbe = which('rubberband').then((rubberband) => ({+ rubberband: Boolean(rubberband),+ }));+ }+ return voiceTransformProbe;+};++export const listVoiceEngines = async () => {+ const transforms = await probeVoiceTransforms();+ const unavailableControls = transforms.rubberband+ ? 'Rubber Band is installed, but PortOS has no approved formant-preserving adapter yet. Pitch and formant controls remain disabled until that adapter is enabled.'+ : 'Install Rubber Band to enable a future formant-preserving transform. Pitch and formant controls remain disabled rather than approximated by sample-rate changes.';+ return [+ {+ id: 'kokoro',+ capabilities: {+ preset: true, voiceDesign: false, instantClone: false, fineTune: false,+ streaming: false, instructionControl: false, emotionControl: false,+ seed: false, wordTimings: false, rate: true, pitch: false, formant: false,+ },+ unavailableControls,+ transformProbe: transforms,+ },+ {+ id: 'piper',+ capabilities: {+ preset: true, voiceDesign: false, instantClone: false, fineTune: false,+ streaming: false, instructionControl: false, emotionControl: false,+ seed: false, wordTimings: false, rate: true, pitch: false, formant: false,+ },+ unavailableControls,+ transformProbe: transforms,+ },+ ];+};+// Normalize `engine` against the allowlist so an invalid value can't silently// produce Kokoro audio while the response reports `engine: 'elevenlabs'`.const resolveEngine = (engine) => VALID_ENGINES.has(engine) ? engine : 'kokoro';@@ -35,36 +82,46 @@ const backend = (engine) => {*/export const synthesize = async (text, opts = {}) => {const cfg = await getVoiceConfig();- const engine = resolveEngine(opts.engine || cfg.tts.engine);+ const profile = opts.profileId+ ? await getProfileForSynthesis(opts.profileId, opts.route || 'studio')+ : null;+ const profileVoice = profile?.voiceId?.split(':')[1] || null;+ // An approved profile owns its engine/preset. Letting a caller override one+ // would render the wrong character while claiming profile provenance.+ const engine = profile ? profile.engine : resolveEngine(opts.engine || cfg.tts.engine);const { synth } = backend(engine);- let ttsCfg = cfg.tts;+ // A profile snapshots the delivery rate at its explicit promotion. It is+ // therefore immune to later project-default changes, while legacy preset+ // synthesis keeps the old config-driven behavior.+ let ttsCfg = profile ? { ...cfg.tts, rate: profile.delivery.rate } : cfg.tts;// Transient rate override (external public API lets a caller set speed per// request without persisting it). Clamp defensively even though the route// schema already bounds it — direct in-process callers bypass the route.if (typeof opts.rate === 'number' && Number.isFinite(opts.rate)) {ttsCfg = { ...ttsCfg, rate: Math.min(4, Math.max(0.25, opts.rate)) };}- if (opts.voice) {+ const voice = profileVoice || opts.voice;+ if (voice) {// Spread from `ttsCfg` (not `cfg.tts`) so a transient rate override applied// above is preserved alongside the voice override.if (engine === 'kokoro') {// Reject unknown Kokoro voice overrides (symmetric with the Piper branch// below) so the public synth API returns the documented 400 UNKNOWN_VOICE// instead of forwarding a bogus id to the model and erroring/wrong-voicing.- if (!isKokoroVoice(opts.voice)) {- throw new ServerError(`unknown kokoro voice: ${opts.voice}`, {+ if (!isKokoroVoice(voice)) {+ throw new ServerError(`unknown kokoro voice: ${voice}`, {status: 400,code: 'UNKNOWN_VOICE',});}- ttsCfg = { ...ttsCfg, kokoro: { ...ttsCfg.kokoro, voice: opts.voice } };+ ttsCfg = { ...ttsCfg, kokoro: { ...ttsCfg.kokoro, voice } };} else {// Reject Piper voice overrides that aren't in the curated catalog —// otherwise `voice` would change but `voicePath` would remain the// previous config value, silently synthesizing the wrong voice.- const catalog = findPiperVoice(opts.voice);+ const catalog = findPiperVoice(voice);if (!catalog) {- throw new ServerError(`unknown piper voice: ${opts.voice}`, {+ throw new ServerError(`unknown piper voice: ${voice}`, {status: 400,code: 'UNKNOWN_VOICE',});@@ -73,15 +130,33 @@ export const synthesize = async (text, opts = {}) => {...ttsCfg,piper: {...ttsCfg.piper,- voice: opts.voice,- voicePath: piperVoiceTildePath(opts.voice),+ voice,+ voicePath: piperVoiceTildePath(voice),speakerId: null,},};}}const result = await synth(text, ttsCfg, opts.signal);- return { ...result, engine };+ const modelRevision = engine === 'kokoro'+ ? `${ttsCfg.kokoro.modelId}:${ttsCfg.kokoro.dtype}`+ : `piper:${ttsCfg.piper.voice}`;+ return {+ ...result,+ engine,+ ...(profile ? {+ profileId: profile.id,+ profileRevision: profile.version,+ provenance: {+ profileId: profile.id,+ profileRevision: profile.version,+ engine,+ modelRevision,+ effectiveControls: { rate: ttsCfg.rate },+ mastering: profile.mastering,+ },+ } : {}),+ };};/**diff --git a/server/services/voice/tts.test.js b/server/services/voice/tts.test.jsnew file mode 100644index 0000000000..5abc69ef53--- /dev/null+++ b/server/services/voice/tts.test.js@@ -0,0 +1,57 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('./config.js', () => ({+ getVoiceConfig: vi.fn(),+ piperVoiceTildePath: vi.fn((voice) => `~/.portos/voice/voices/${voice}.onnx`),+}));+vi.mock('./tts-kokoro.js', () => ({ synthesizeKokoro: vi.fn(), listKokoroVoices: vi.fn() }));+vi.mock('./tts-piper.js', () => ({ synthesizePiper: vi.fn(), listPiperVoices: vi.fn() }));+vi.mock('./piper-voices.js', () => ({ findPiperVoice: vi.fn() }));+vi.mock('./kokoro-voices.js', () => ({ isKokoroVoice: vi.fn(() => true) }));+vi.mock('./profiles.js', () => ({ getProfileForSynthesis: vi.fn() }));+vi.mock('./bootstrap.js', () => ({ which: vi.fn() }));++import { getVoiceConfig } from './config.js';+import { synthesizeKokoro } from './tts-kokoro.js';+import { getProfileForSynthesis } from './profiles.js';+import { synthesize } from './tts.js';++const CONFIG = {+ tts: {+ engine: 'kokoro',+ rate: 1.7,+ kokoro: { modelId: 'configured-model', dtype: 'q8', voice: 'af_bella' },+ piper: { voice: 'en_US-lessac-medium', voicePath: '~/.portos/voice/voices/en_US-lessac-medium.onnx' },+ },+};++describe('profile-aware TTS', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getVoiceConfig.mockResolvedValue(CONFIG);+ synthesizeKokoro.mockResolvedValue({ wav: Buffer.from('wav'), latencyMs: 12 });+ });++ it('uses the approved profile voice and promoted delivery rate instead of later project defaults', async () => {+ getProfileForSynthesis.mockResolvedValue({+ id: 'voice-profile-1', version: 3, engine: 'kokoro', voiceId: 'kokoro:af_heart',+ delivery: { rate: 0.85, pitchSemitones: null, formantSemitones: null },+ mastering: { chain: ['preset-output:unprocessed'] },+ });++ const result = await synthesize('A stable character line.', { profileId: 'voice-profile-1', route: 'studio' });++ expect(synthesizeKokoro).toHaveBeenCalledWith('A stable character line.', expect.objectContaining({+ rate: 0.85,+ kokoro: expect.objectContaining({ voice: 'af_heart' }),+ }), undefined);+ expect(result).toMatchObject({+ engine: 'kokoro', profileId: 'voice-profile-1', profileRevision: 3,+ provenance: {+ modelRevision: 'configured-model:q8',+ effectiveControls: { rate: 0.85 },+ mastering: { chain: ['preset-output:unprocessed'] },+ },+ });+ });+});