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
fix: record local voice render provenance (#5380)
[._.]/ Adam Eivy024aedff2e6e
diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex dfb165bdf7..a4a961614e 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -35,7 +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`.+- `voice_profiles` / `voice_profile_renders` — machine-local DB-primary records for approved `(universeId, characterId)` bindings and the latest rendered dialogue line per `(issueId, lineId)`. They store the promoted Kokoro/Piper preset, profile revision, route availability, benchmark provenance, and reproducible dialogue delivery details (engine/model revision, timing, controls, and mastering). The portable Universe character and federated pipeline issue keep only portable voice data and audio filenames; they never store 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.jsindex a2f4186830..7c3157ca23 100644--- a/scripts/migrations/315-voice-profiles-table.js+++ b/scripts/migrations/315-voice-profiles-table.js@@ -1,7 +1,7 @@/*** Register machine-local character voice profiles (issue #5380).*- * The additive `voice_profiles` DDL lives in `ensureSchema()` and+ * The additive `voice_profiles` / `voice_profile_renders` 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.@@ -9,6 +9,6 @@export default {async up() {- console.log('🎙️ voice_profiles: table created idempotently by ensureSchema at boot; nothing to do in the file runner');+ console.log('🎙️ voice profile tables 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 2f88ea5866..0224b1bf2d 100644--- a/server/lib/db.catalogDdlParity.test.js+++ b/server/lib/db.catalogDdlParity.test.js@@ -289,6 +289,19 @@ describe('catalog DDL parity (init-db.sql ↔ db.js ensureSchema)', () => {expect(sqlIdx.size).toBeGreaterThan(0);});+ it('voice_profile_renders has the same columns and indexes in both files', () => {+ const sqlBody = extractCreateTable(INIT_SQL, 'voice_profile_renders');+ const jsBody = extractCreateTable(DB_JS, 'voice_profile_renders');+ expect(sqlBody, 'init-db.sql missing CREATE TABLE voice_profile_renders').toBeTruthy();+ expect(jsBody, 'db.js missing CREATE TABLE voice_profile_renders').toBeTruthy();+ expect([...new Set(extractColumnNames(sqlBody))].sort())+ .toEqual([...new Set(extractColumnNames(jsBody))].sort());+ const sqlIdx = extractIndexNames(INIT_SQL, 'idx_voice_profile_renders_');+ const jsIdx = extractIndexNames(DB_JS, 'idx_voice_profile_renders_');+ 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 5ec06c0092..8d54bfdfaa 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, machine-local character voice profiles, + universe run history |+| `universes.js` | `universesDdl` | Universes, machine-local character voice profiles/renders, + 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 edbc7e3649..0277e18667 100644--- a/server/lib/db/schema/universes.js+++ b/server/lib/db/schema/universes.js@@ -49,6 +49,22 @@ export const universesDdl = [`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'`,+ // Render provenance is deliberately separate from the federated pipeline+ // issue record. It keeps the local profile revision and precise delivery+ // data attached to a rendered dialogue line without exporting a+ // machine-local profile id to a peer.+ `CREATE TABLE IF NOT EXISTS voice_profile_renders (+ issue_id TEXT NOT NULL,+ line_id TEXT NOT NULL,+ profile_id TEXT NOT NULL,+ profile_revision INTEGER NOT NULL,+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ PRIMARY KEY (issue_id, line_id)+ )`,+ `CREATE INDEX IF NOT EXISTS idx_voice_profile_renders_profile ON voice_profile_renders (profile_id, profile_revision, updated_at DESC)`,+// 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/routes/pipeline.test.js b/server/routes/pipeline.test.jsindex b3d7c867b0..dfa14e2cee 100644--- a/server/routes/pipeline.test.js+++ b/server/routes/pipeline.test.js@@ -316,6 +316,11 @@ vi.mock('../services/voice/tts.js', () => ({listVoices: vi.fn(async () => ({ engine: 'kokoro', voices: [] })),VALID_ENGINES: new Set(['kokoro', 'piper']),}));+vi.mock('../services/voice/profiles.js', () => ({+ clearVoiceProfileRender: vi.fn(),+ recordVoiceProfileRender: vi.fn(),+ resolveCharacterVoice: vi.fn(),+}));const musicLibraryStore = new Map();let lastImportedName = null;@@ -2737,6 +2742,7 @@ describe('pipeline routes', () => {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');audio.synthesizeToFile.mockResolvedValueOnce({filename: 'vo-local-profile.wav', latencyMs: 5, engine: 'kokoro',provenance: {@@ -2753,6 +2759,14 @@ describe('pipeline routes', () => {expect(rendered.status).toBe(200);const reread = await request(app).get(`/api/pipeline/issues/${iss.id}`);expect(reread.body.stages.audio.lines[0]).not.toHaveProperty('voiceProvenance');+ expect(reread.body.stages.audio.lines[0]).not.toHaveProperty('profileId');+ expect(reread.body.stages.audio.lines[0]).not.toHaveProperty('profileRevision');+ expect(profiles.recordVoiceProfileRender).toHaveBeenCalledWith(expect.objectContaining({+ issueId: iss.id,+ lineId: 'line-001',+ audioFilename: 'vo-local-profile.wav',+ provenance: expect.objectContaining({ profileId: 'voice-profile-1', profileRevision: 2 }),+ }));});it('POST /audio/lines/:idx/render 404s for out-of-range index', async () => {diff --git a/server/routes/pipeline/audio.js b/server/routes/pipeline/audio.jsindex cd20f1bfa5..b6ad132135 100644--- a/server/routes/pipeline/audio.js+++ b/server/routes/pipeline/audio.js@@ -15,7 +15,11 @@ 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 {+ clearVoiceProfileRender,+ recordVoiceProfileRender,+ resolveCharacterVoice,+} from '../../services/voice/profiles.js';import {listMusicLibrary,importUploadedTrack,@@ -241,6 +245,18 @@ router.post('/issues/:id/stages/audio/lines/:lineIdx/render', asyncHandler(asyncroute: 'studio',}).catch((err) => { throw mapServiceError(err); });+ if (synthResult.provenance) {+ await recordVoiceProfileRender({+ issueId: issue.id,+ lineId: line.id,+ audioFilename: synthResult.filename,+ latencyMs: synthResult.latencyMs,+ durationMs: synthResult.durationMs,+ provenance: synthResult.provenance,+ });+ } else {+ await clearVoiceProfileRender({ issueId: issue.id, lineId: line.id });+ }const nextLines = [...lines];nextLines[lineIdx] = {...line,diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex a56f75779a..f4b8c57d95 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -937,6 +937,21 @@ CREATE TABLE IF NOT EXISTS voice_profiles (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';+-- Machine-local dialogue render provenance. Pipeline issues federate, so their+-- audio lines keep only a portable filename while profile identity and delivery+-- details remain in this local table.+CREATE TABLE IF NOT EXISTS voice_profile_renders (+ issue_id TEXT NOT NULL,+ line_id TEXT NOT NULL,+ profile_id TEXT NOT NULL,+ profile_revision INTEGER NOT NULL,+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ PRIMARY KEY (issue_id, line_id)+);+CREATE INDEX IF NOT EXISTS idx_voice_profile_renders_profile ON voice_profile_renders (profile_id, profile_revision, updated_at DESC);+-- 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/voice/profiles.js b/server/services/voice/profiles.jsindex 8c3aa89cab..26a0502a23 100644--- a/server/services/voice/profiles.js+++ b/server/services/voice/profiles.js@@ -22,6 +22,7 @@ const MAX_ID = 160;const MAX_LABEL = 160;const MAX_REVISION = 240;const MAX_BENCHMARK_LINES = 12;+const MAX_RENDER_ID = 160;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@@ -62,9 +63,9 @@ const sanitizeDelivery = (raw) => ({});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.+ // An explicit empty chain means the profile applies no extra mastering;+ // an absent chain gets the named initial preset-output wrapper. Keeping the+ // two states distinct makes future mastering adapters reproducible.chain: Array.isArray(raw?.chain)? raw.chain.map((step) => trim(step, 80)).filter(Boolean).slice(0, 12): [...DEFAULT_MASTERING.chain],@@ -283,6 +284,68 @@ export async function saveProfileBenchmark(profile, benchmark) {return persist(next);}+/**+ * Keep line-level profile provenance in the local database rather than in a+ * federated pipeline issue. One row follows the latest render of each line,+ * including the output filename so it cannot be mistaken for an older WAV.+ */+export async function recordVoiceProfileRender({+ issueId,+ lineId,+ audioFilename,+ latencyMs,+ durationMs,+ provenance,+} = {}) {+ const issue = trim(issueId, MAX_RENDER_ID);+ const line = trim(lineId, MAX_RENDER_ID);+ const filename = trim(audioFilename, 500);+ const profileId = trim(provenance?.profileId, 80);+ const profileRevision = positiveInteger(provenance?.profileRevision, 0);+ const engine = VOICE_PROFILE_ENGINES.has(provenance?.engine) ? provenance.engine : null;+ if (!issue || !line || !filename || !PROFILE_ID_RE.test(profileId) || !profileRevision || !engine) {+ throw new ServerError('Invalid local voice render provenance', {+ status: 400,+ code: 'VOICE_PROFILE_INVALID_RENDER_PROVENANCE',+ });+ }+ const now = timestamp();+ const data = {+ profileId,+ profileRevision,+ engine,+ modelRevision: trim(provenance?.modelRevision, MAX_REVISION) || null,+ effectiveControls: {+ rate: Number.isFinite(provenance?.effectiveControls?.rate) ? provenance.effectiveControls.rate : null,+ },+ mastering: sanitizeMastering(provenance?.mastering),+ timing: {+ latencyMs: Number.isFinite(latencyMs) ? Math.max(0, Math.round(latencyMs)) : null,+ durationMs: Number.isFinite(durationMs) ? Math.max(0, Math.round(durationMs)) : null,+ },+ audioFilename: filename,+ recordedAt: now,+ };+ await query(+ `INSERT INTO voice_profile_renders (issue_id, line_id, profile_id, profile_revision, data, created_at, updated_at)+ VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7)+ ON CONFLICT (issue_id, line_id) DO UPDATE SET+ profile_id = EXCLUDED.profile_id,+ profile_revision = EXCLUDED.profile_revision,+ data = EXCLUDED.data,+ updated_at = EXCLUDED.updated_at`,+ [issue, line, profileId, profileRevision, JSON.stringify(data), now, now],+ );+}++/** Clear stale local lineage when a later render uses a portable/default voice. */+export async function clearVoiceProfileRender({ issueId, lineId } = {}) {+ const issue = trim(issueId, MAX_RENDER_ID);+ const line = trim(lineId, MAX_RENDER_ID);+ if (!issue || !line) return;+ await query('DELETE FROM voice_profile_renders WHERE issue_id = $1 AND line_id = $2', [issue, line]);+}+const assertRoute = (route) => {if (!VOICE_PROFILE_ROUTES.has(route)) {throw new ServerError('Unsupported voice profile route', { status: 400, code: 'VOICE_PROFILE_INVALID_ROUTE' });@@ -337,12 +400,16 @@ export async function resolveCharacterVoice({unavailableProfile = profiles.find((item) => item.approval.status === 'approved') || null;}const preset = parsePresetVoiceId(characterVoiceId);- if (preset) {+ // Legacy character records stored a bare engine voice name. It remains a+ // valid portable fallback even though it is less descriptive than a modern+ // `kokoro:` / `piper:` preset id.+ const legacyVoice = trim(characterVoiceId, MAX_ID);+ if (preset || legacyVoice) {return {source: 'character-preset',profileId: null,profileRevision: null,- voiceId: preset.voiceId,+ voiceId: preset?.voiceId || legacyVoice,degraded: Boolean(unavailableProfile),warning: unavailableProfile? `The approved local voice profile is unavailable for ${route}; using the portable character preset.`diff --git a/server/services/voice/profiles.test.js b/server/services/voice/profiles.test.jsindex 4df950bbf7..51343108da 100644--- a/server/services/voice/profiles.test.js+++ b/server/services/voice/profiles.test.js@@ -19,6 +19,7 @@ const {resolveCharacterVoice,getProfileForSynthesis,profileArtifactDirectory,+ recordVoiceProfileRender,} = await import('./profiles.js');const PROFILE = {@@ -126,6 +127,36 @@ describe('voice profile contract', () => {});});+ it('keeps legacy bare character presets as portable fallbacks', async () => {+ queryMock.mockResolvedValueOnce({ rows: [] });+ await expect(resolveCharacterVoice({+ universeId: 'universe-1', characterId: 'character-1', characterVoiceId: 'af_heart',+ })).resolves.toMatchObject({ source: 'character-preset', voiceId: 'af_heart', degraded: false });+ });++ it('records dialogue lineage locally with the effective controls and timing', async () => {+ queryMock.mockResolvedValueOnce({ rows: [] });+ await recordVoiceProfileRender({+ issueId: 'iss-1', lineId: 'line-001', audioFilename: 'vo-local-profile.wav', latencyMs: 24, durationMs: 850,+ provenance: {+ profileId: PROFILE.id, profileRevision: 2, engine: 'kokoro', modelRevision: 'kokoro-test:q8',+ effectiveControls: { rate: 0.9 }, mastering: PROFILE.mastering,+ },+ });+ expect(queryMock).toHaveBeenCalledWith(expect.stringContaining('INSERT INTO voice_profile_renders'), expect.arrayContaining([+ 'iss-1', 'line-001', PROFILE.id, 2,+ ]));+ const saved = JSON.parse(queryMock.mock.calls[0][1][4]);+ expect(saved).toMatchObject({+ profileId: PROFILE.id,+ profileRevision: 2,+ audioFilename: 'vo-local-profile.wav',+ effectiveControls: { rate: 0.9 },+ timing: { latencyMs: 24, durationMs: 850 },+ mastering: PROFILE.mastering,+ });+ });+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'))