Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-863]): audioMode + per-arc cues schema foundation for whole-episode audio
[._.]/ Adam Eivy60145a122f61
diff --git a/scripts/migrations/067-pipeline-audio-mode-cues.js b/scripts/migrations/067-pipeline-audio-mode-cues.jsnew file mode 100644index 0000000000..5303e16808--- /dev/null+++ b/scripts/migrations/067-pipeline-audio-mode-cues.js@@ -0,0 +1,106 @@+/**+ * Stamp `stages.audio.audioMode` + initialize `stages.audio.cues[]` on existing+ * pipeline issues (whole-episode audio — issue #863, design doc+ * docs/plans/2026-06-03-whole-episode-audio-strategy.md).+ *+ * Back-compat derivation (preserve today's behavior — never let "absent"+ * collapse into a wrong mode):+ * - audio.music present → 'uploaded-track' (the install has a single bed+ * it loops under the whole episode today)+ * - audio.music absent → 'per-clip' (today's "no bed, keep each+ * clip's own soundtrack" behavior)+ * - cues initialized to []+ *+ * The read-side sanitizer (`sanitizeAudioMode`) already defaults an absent+ * audioMode to 'per-clip', so an un-migrated or older-peer-synced record reads+ * correctly before this runs; the migration just makes the stored value+ * explicit (and stamps 'uploaded-track' where a track already exists, which the+ * read-side default alone can't infer).+ *+ * Issues live per-record under `data/pipeline-issues/{id}/index.json` after the+ * 035 split (which runs before this migration). Idempotent: a record that+ * already carries an `audioMode` is left untouched.+ */++import { readFile, writeFile, readdir, stat } from 'fs/promises';+import { join } from 'path';++const readJsonOrNull = async (path) => {+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) return null;+ try {+ return JSON.parse(raw);+ } catch {+ return null;+ }+};++const writeJson = async (path, data) => {+ await writeFile(path, `${JSON.stringify(data, null, 2)}\n`);+};++// Apply the audioMode/cues stamp to one issue record in place. Returns true if+// the record was changed.+const stampIssue = (issue) => {+ if (!issue || typeof issue.stages !== 'object' || issue.stages === null) return false;+ const audio = issue.stages.audio;+ if (!audio || typeof audio !== 'object') return false;+ let changed = false;+ if (!('audioMode' in audio)) {+ const hasTrack = audio.music && typeof audio.music === 'object';+ audio.audioMode = hasTrack ? 'uploaded-track' : 'per-clip';+ changed = true;+ }+ if (!Array.isArray(audio.cues)) {+ audio.cues = [];+ changed = true;+ }+ return changed;+};++const listIssueDirs = async (typeDir) => {+ const entries = await readdir(typeDir).catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (entries == null) return [];+ const dirs = [];+ for (const name of entries) {+ if (name === 'index.json') continue;+ const full = join(typeDir, name);+ const st = await stat(full).catch(() => null);+ if (st?.isDirectory()) dirs.push(full);+ }+ return dirs;+};++export default {+ async up({ rootDir }) {+ const typeDir = join(rootDir, 'data', 'pipeline-issues');+ const dirs = await listIssueDirs(typeDir);+ if (dirs.length === 0) {+ console.log('🎵 audio-mode: no pipeline issues — nothing to do (fresh installs seed audioMode on create)');+ return;+ }++ let touched = 0;+ for (const dir of dirs) {+ const recordPath = join(dir, 'index.json');+ const issue = await readJsonOrNull(recordPath);+ if (!issue) continue;+ if (stampIssue(issue)) {+ await writeJson(recordPath, issue);+ touched += 1;+ }+ }++ if (touched > 0) {+ console.log(`📝 audio-mode: stamped audioMode + cues[] on ${touched} issue${touched === 1 ? '' : 's'}`);+ } else {+ console.log('✅ audio-mode: all issues already carry audioMode — nothing to do');+ }+ },+};diff --git a/scripts/migrations/067-pipeline-audio-mode-cues.test.js b/scripts/migrations/067-pipeline-audio-mode-cues.test.jsnew file mode 100644index 0000000000..975248b6ba--- /dev/null+++ b/scripts/migrations/067-pipeline-audio-mode-cues.test.js@@ -0,0 +1,84 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './067-pipeline-audio-mode-cues.js';++const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++describe('migration 067 — pipeline audio mode + cues', () => {+ let rootDir;+ let typeDir;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-067-'));+ typeDir = join(rootDir, 'data', 'pipeline-issues');+ mkdirSync(typeDir, { recursive: true });+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ const writeIssue = (id, issue) => {+ const dir = join(typeDir, id);+ mkdirSync(dir, { recursive: true });+ writeJson(join(dir, 'index.json'), issue);+ };+ const readIssue = (id) => readJson(join(typeDir, id, 'index.json'));++ it('stamps uploaded-track when a music pointer exists', async () => {+ writeIssue('iss-a', {+ id: 'iss-a',+ stages: { audio: { status: 'ready', music: { source: 'upload', trackFilename: 'bg.mp3' } } },+ });+ await migration.up({ rootDir });+ const a = readIssue('iss-a');+ expect(a.stages.audio.audioMode).toBe('uploaded-track');+ expect(a.stages.audio.cues).toEqual([]);+ });++ it('stamps per-clip when no music pointer exists', async () => {+ writeIssue('iss-b', {+ id: 'iss-b',+ stages: { audio: { status: 'empty', music: null, lines: [] } },+ });+ await migration.up({ rootDir });+ const b = readIssue('iss-b');+ expect(b.stages.audio.audioMode).toBe('per-clip');+ expect(b.stages.audio.cues).toEqual([]);+ });++ it('is idempotent — leaves an already-stamped record untouched', async () => {+ writeIssue('iss-c', {+ id: 'iss-c',+ stages: {+ audio: {+ status: 'ready',+ audioMode: 'generated',+ music: { source: 'gen', trackFilename: 't.wav' },+ cues: [{ id: 'cue-001', prompt: 'pads' }],+ },+ },+ });+ await migration.up({ rootDir });+ const c = readIssue('iss-c');+ // existing audioMode preserved (not flipped to uploaded-track) and cues kept+ expect(c.stages.audio.audioMode).toBe('generated');+ expect(c.stages.audio.cues).toEqual([{ id: 'cue-001', prompt: 'pads' }]);+ });++ it('skips records without an audio stage and the type index', async () => {+ writeJson(join(typeDir, 'index.json'), { schemaVersion: 1, type: 'pipelineIssues' });+ writeIssue('iss-d', { id: 'iss-d', stages: { idea: { status: 'ready' } } });+ await expect(migration.up({ rootDir })).resolves.toBeUndefined();+ expect(readIssue('iss-d').stages.audio).toBeUndefined();+ });++ it('no pipeline-issues dir → no-op', async () => {+ rmSync(typeDir, { recursive: true, force: true });+ await expect(migration.up({ rootDir })).resolves.toBeUndefined();+ });+});diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 95e4e24ea8..f24fbbad11 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -39,7 +39,15 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({universes: 5,// v1 = post-split. Migrations 035/036 introduced the pipeline collection// layout for issues and series.- pipelineIssues: 1,+ // v2 = `stages.audio.audioMode` + `stages.audio.cues[]` added (whole-episode+ // audio, issue #863). Additive, but version-gated for the same reason+ // `pipelineSeries 1→2` (readerMap) is: an older, audioMode/cues-unaware peer+ // that receives and re-sanitizes the record would silently strip the new+ // fields and last-writer-wins the loss back onto the newer peer. Bumping+ // makes the older peer reject the ahead-version issue transfer instead.+ // Per-category gate → only issue sync pauses with old peers; series/universes+ // keep flowing.+ pipelineIssues: 2,// v2 = `series.arc.readerMap` added (Unified Story Builder). Additive +// gracefully-degrading, but version-gated so a not-yet-upgraded peer can't// round-trip a series through its readerMap-unaware sanitizer and LWW-stripdiff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.jsindex d32a2b20d4..74921e0e55 100644--- a/server/lib/schemaVersions.test.js+++ b/server/lib/schemaVersions.test.js@@ -22,7 +22,8 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {});it('declares pipeline collection layout versions', () => {- expect(PORTOS_SCHEMA_VERSIONS.pipelineIssues).toBe(1);+ // pipelineIssues bumped to 2 when stages.audio.audioMode + cues[] were added.+ expect(PORTOS_SCHEMA_VERSIONS.pipelineIssues).toBe(2);// pipelineSeries bumped to 2 when series.arc.readerMap was added.expect(PORTOS_SCHEMA_VERSIONS.pipelineSeries).toBe(2);});@@ -37,7 +38,7 @@ describe('buildPortosMeta', () => {const meta = await buildPortosMeta();expect(meta.portosVersion).toMatch(/^\d+\.\d+\.\d+/);expect(meta.schemaVersions.universes).toBe(5);- expect(meta.schemaVersions.pipelineIssues).toBe(1);+ expect(meta.schemaVersions.pipelineIssues).toBe(2);expect(meta.schemaVersions.pipelineSeries).toBe(2);});@@ -191,7 +192,7 @@ describe('scopeVersionDiff', () => {// Sender is ahead on mediaCollections only; a universe transfer scopes to// ['universes'] and stays compatible even though the union diff is not.const union = compareSchemaVersions(- { universes: 5, pipelineSeries: 2, pipelineIssues: 1, mediaCollections: 2 },+ { universes: 5, pipelineSeries: 2, pipelineIssues: 2, mediaCollections: 2 },PORTOS_SCHEMA_VERSIONS,);expect(union.compatible).toBe(false); // mediaCollections 2 > 1diff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex 617653ac4d..4673b0b1a4 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -301,6 +301,28 @@ const stageInputSchema = z.object({locked: z.boolean().optional(),});+// Strict base arm for the stage-record union below — a bare text-stage patch+// (only base fields) validates here, but a payload carrying any visual/audio+// extra key fails this arm and is routed to the matching specific arm instead+// of being silently key-stripped. The non-strict `stageInputSchema` stays the+// `.extend()` base for the specific arms (they re-apply `.strict()` themselves).+const baseStageStrictSchema = stageInputSchema.strict();++// Light per-cue arm for the audio stage (issue #863). The service-side+// `sanitizeAudioCue` enforces the real shape (ids, time sentinels, gain clamp);+// here we only bound sizes so a corrupt payload can't balloon the request.+const audioCueInputSchema = z.object({+ id: z.string().trim().max(80).optional(),+ label: z.string().max(200).nullable().optional(),+ prompt: z.string().max(8000).nullable().optional(),+ engine: z.string().trim().max(80).nullable().optional(),+ startSec: z.number().nullable().optional(),+ endSec: z.number().nullable().optional(),+ trackFilename: z.string().trim().max(500).nullable().optional(),+ durationSec: z.number().nullable().optional(),+ gain: z.number().nullable().optional(),+}).strip();+// Visual stage records also accept pages/scenes/cdProjectId/videoPath — those// are arbitrary structured artifacts written by the visual UI. Keep the// validation light here so the artifact shape can evolve without a schema@@ -338,17 +360,27 @@ const visualStageInputSchema = stageInputSchema.extend({imageJobId: z.string().trim().max(200).nullable().optional(),prompt: z.string().max(16_000).nullable().optional(),}).nullable().optional(),-});+}).strict();-// Audio stage payloads carry lines[] (voice-over per dialogue line) + a-// nullable music descriptor. Light validation — the sanitizer in-// services/pipeline/issues.js enforces per-line + per-music shape. Without-// this arm in the union below, audio PATCHes silently fall through to the-// base stageInputSchema and Zod strips lines[]/music.+// Audio stage payloads carry lines[] (voice-over per dialogue line), a nullable+// music descriptor, the whole-episode `audioMode` selector, and arc-driven+// `cues[]` (issue #863). Light validation — the sanitizer in+// services/pipeline/issues.js enforces per-line / per-music / per-cue shape.+// Without this arm in the union below, audio PATCHes fall through and the+// base/visual arms strip lines/music/audioMode/cues.+//+// `.strict()` is load-bearing here: the union arms below all share the same+// optional base fields, so a plain object parses against *any* arm and Zod's+// default key-stripping would let an audio payload match the visual arm FIRST,+// silently dropping audioMode/cues. Strict arms reject unknown keys, so an+// audio payload (with audioMode/cues/lines/music) only validates against THIS+// arm and reaches the audio sanitizer intact.const audioStageInputSchema = stageInputSchema.extend({lines: z.array(z.any()).max(1000).optional(),music: z.any().nullable().optional(),-});+ audioMode: z.enum(issuesSvc.AUDIO_MODES).optional(),+ cues: z.array(audioCueInputSchema).max(issuesSvc.AUDIO_CUES_MAX).optional(),+}).strict();const issuePatchSchema = z.object({title: z.string().trim().min(1).max(issuesSvc.TITLE_MAX).optional(),@@ -365,14 +397,16 @@ const issuePatchSchema = z.object({lengthProfile: z.enum(LENGTH_PROFILE_NAMES).optional(),pageTarget: z.number().int().min(CUSTOM_PAGE_MIN).max(CUSTOM_PAGE_MAX).nullable().optional(),minutesTarget: z.number().int().min(CUSTOM_MINUTE_MIN).max(CUSTOM_MINUTE_MAX).nullable().optional(),- // Use visualStageInputSchema as the union arm so visual-stage payloads keep- // their `scenes` / `pages` / `cdProjectId` / `videoPath` fields. The schema- // is a superset of stageInputSchema (those four are optional additions), so- // text-stage patches still validate. Z.union picks the first schema that- // succeeds — stageInputSchema first would silently strip the visual fields.- // Union order matters: Zod picks the first arm that succeeds, so the- // more-specific schemas (visual, audio) must precede the bare base.- stages: z.record(z.string(), z.union([visualStageInputSchema, audioStageInputSchema, stageInputSchema])).optional(),+ // Stage-record arms are all `.strict()` (see audioStageInputSchema above):+ // every arm shares the same optional base fields, so a non-strict arm would+ // accept (and key-strip) a payload meant for a sibling arm. With strict arms+ // a payload only validates against the arm whose extra keys it actually+ // carries — visual payloads (pages/scenes/…) reach the visual arm, audio+ // payloads (lines/music/audioMode/cues) reach the audio arm, and bare+ // text-stage patches (status/output/locked only) fall through to the base.+ // Order is now defensive rather than load-bearing, but we still place the+ // more-specific arms first; the bare base last.+ stages: z.record(z.string(), z.union([visualStageInputSchema, audioStageInputSchema, baseStageStrictSchema])).optional(),ephemeral: z.boolean().optional(),}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.jsindex 4a154a607b..5480a34713 100644--- a/server/routes/pipeline.test.js+++ b/server/routes/pipeline.test.js@@ -1809,6 +1809,44 @@ describe('pipeline routes', () => {expect(r.body.stages.idea.status).toBe('empty');});+ it('PATCH /issues/:id audio payload survives the union (audioMode + cues not stripped)', async () => {+ // Regression for the #736-flagged union-arm hazard: the all-optional visual+ // arm could match an audio payload first and strip audioMode/cues. The+ // strict union arms must route the payload to the audio arm intact.+ const app = makeApp();+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'Ep 1' });+ const r = await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({+ stages: {+ audio: {+ status: 'edited',+ audioMode: 'generated',+ lines: [{ text: 'Hello.' }],+ cues: [{ label: 'Act I', prompt: 'warm pads', engine: 'audioldm2', startSec: 0, endSec: 30 }],+ },+ },+ });+ expect(r.status).toBe(200);+ expect(r.body.stages.audio.audioMode).toBe('generated');+ expect(r.body.stages.audio.cues).toHaveLength(1);+ expect(r.body.stages.audio.cues[0]).toMatchObject({+ label: 'Act I', prompt: 'warm pads', engine: 'audioldm2', startSec: 0, endSec: 30,+ });+ expect(r.body.stages.audio.lines).toHaveLength(1);+ });++ it('PATCH /issues/:id visual payload still reaches the visual arm (scenes preserved)', async () => {+ // The strictness change must not regress visual-stage routing.+ const app = makeApp();+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'Ep 1' });+ const r = await request(app).patch(`/api/pipeline/issues/${iss.body.id}`).send({+ stages: { storyboards: { status: 'edited', scenes: [{ id: 's1', summary: 'open' }] } },+ });+ expect(r.status).toBe(200);+ expect(r.body.stages.storyboards.scenes).toHaveLength(1);+ });+it('PATCH /series/:id accepts arc payload', async () => {const app = makeApp();const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex 30a97bde6e..130b91bceb 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -439,6 +439,60 @@ const sanitizeMusicTrack = (raw) => {return { source, trackFilename, label };};+// Which strategy drives the episode's non-dialogue audio (whole-episode audio,+// issue #863 / design doc 2026-06-03-whole-episode-audio-strategy.md):+// per-clip — keep each stitched clip's own soundtrack (today's default)+// silent — strip any bed+// generated — assemble the arc-driven cues[] onto the timeline+// uploaded-track — loop the single `music` pointer under the whole episode+export const AUDIO_MODES = Object.freeze(['per-clip', 'silent', 'generated', 'uploaded-track']);+// Read-side default: an absent / unknown audioMode collapses to 'per-clip' —+// today's behavior — so an un-migrated record (or one synced from an older,+// audioMode-unaware peer) reads correctly before migration 067 stamps the+// explicit value. Never let "absent" become a wrong mode (CLAUDE.md sentinel+// discipline).+export const sanitizeAudioMode = (raw) => (AUDIO_MODES.includes(raw) ? raw : 'per-clip');++const AUDIO_CUE_ID_MAX = 80;+const AUDIO_CUE_LABEL_MAX = 200;+const AUDIO_CUE_PROMPT_MAX = 8000;+const AUDIO_CUE_ENGINE_MAX = 80;+export const AUDIO_CUES_MAX = 200;++// Per-cue gain override. `null` = "use the stage / global default", distinct+// from `0` ("muted"). Clamped to a sane 0..4 range so a corrupted value can't+// blow out the mix.+const sanitizeCueGain = (raw) => {+ if (raw === null || raw === undefined) return null;+ const n = Number(raw);+ if (!Number.isFinite(n) || n < 0) return null;+ return Math.min(n, 4);+};++const sanitizeAudioCue = (raw, i) => {+ if (!raw || typeof raw !== 'object') return null;+ const id = trimTo(raw.id, AUDIO_CUE_ID_MAX) || `cue-${String(i + 1).padStart(3, '0')}`;+ return {+ id,+ label: trimTo(raw.label, AUDIO_CUE_LABEL_MAX) || null,+ prompt: trimTo(raw.prompt, AUDIO_CUE_PROMPT_MAX) || null,+ // Engine id (musicgen | audioldm2 | suno | …). Free-form trimmed string so+ // a future pluggable engine works without a sanitizer change — the render+ // route resolves it against the live ENGINES registry. null = "unset".+ engine: trimTo(raw.engine, AUDIO_CUE_ENGINE_MAX) || null,+ // Reuse sanitizeLineOffset for cue timing: identical null-vs-0 sentinel+ // ("not placed yet" vs "plays at start") and 2h cap as VO line offsets.+ // durationSec is "not rendered yet" (null) → actual length once rendered.+ startSec: sanitizeLineOffset(raw.startSec),+ endSec: sanitizeLineOffset(raw.endSec),+ trackFilename: isStr(raw.trackFilename) && raw.trackFilename+ ? raw.trackFilename.slice(0, AUDIO_FILENAME_MAX)+ : null,+ durationSec: sanitizeLineOffset(raw.durationSec),+ gain: sanitizeCueGain(raw.gain),+ };+};+const sanitizeAudioStage = (raw) => {// `canonExtraction` is text-stage-only (see sanitizeTextStage) — the audio// shape never carries it.@@ -449,6 +503,10 @@ const sanitizeAudioStage = (raw) => {? raw.lines.slice(0, AUDIO_LINES_MAX).map(sanitizeAudioLine).filter(Boolean): [],music: sanitizeMusicTrack(raw?.music),+ audioMode: sanitizeAudioMode(raw?.audioMode),+ cues: Array.isArray(raw?.cues)+ ? raw.cues.slice(0, AUDIO_CUES_MAX).map(sanitizeAudioCue).filter(Boolean)+ : [],};};diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.jsindex fc972c3acb..7072febf30 100644--- a/server/services/pipeline/issues.test.js+++ b/server/services/pipeline/issues.test.js@@ -1079,7 +1079,7 @@ describe('pipeline issues service', () => {expect(i.stages.audio).toEqual({status: 'empty', input: '', output: '', lastRunId: null,errorMessage: '', updatedAt: null, lines: [], music: null, locked: false,- runHistory: [],+ runHistory: [], audioMode: 'per-clip', cues: [],});});@@ -1140,6 +1140,73 @@ describe('pipeline issues service', () => {expect(stage.lines[0].text).toBe('fresh text');expect(stage.lines[0].characterId).toBe('chr-9');});++ it('defaults audioMode to per-clip and keeps known values', async () => {+ const def = await makeIssue({ lines: [] });+ expect(def.stages.audio.audioMode).toBe('per-clip');+ for (const mode of ['silent', 'generated', 'uploaded-track', 'per-clip']) {+ const i = await makeIssue({ audioMode: mode });+ expect(i.stages.audio.audioMode).toBe(mode);+ }+ });++ it('coerces unknown / non-string audioMode to per-clip', async () => {+ for (const bogus of ['made-up', 42, null, {}, '']) {+ const i = await makeIssue({ audioMode: bogus });+ expect(i.stages.audio.audioMode).toBe('per-clip');+ }+ });++ it('round-trips cues[] with auto-assigned ids and time/render sentinels', async () => {+ const i = await makeIssue({+ audioMode: 'generated',+ cues: [+ { label: 'Act I', prompt: 'warm pads', engine: 'audioldm2', startSec: 0, endSec: 84.5 },+ { id: 'cue-custom', prompt: 'tense strings', gain: 0.5 },+ ],+ });+ const cues = i.stages.audio.cues;+ expect(cues).toHaveLength(2);+ expect(cues[0]).toEqual({+ id: 'cue-001', label: 'Act I', prompt: 'warm pads', engine: 'audioldm2',+ startSec: 0, endSec: 84.5, trackFilename: null, durationSec: null, gain: null,+ });+ expect(cues[1].id).toBe('cue-custom');+ // null = "not placed / not rendered yet"; gain 0.5 preserved.+ expect(cues[1].startSec).toBeNull();+ expect(cues[1].endSec).toBeNull();+ expect(cues[1].trackFilename).toBeNull();+ expect(cues[1].durationSec).toBeNull();+ expect(cues[1].gain).toBe(0.5);+ });++ it('cue gain distinguishes null (default) from 0 (muted) and clamps the range', async () => {+ const i = await makeIssue({+ cues: [+ { prompt: 'a' }, // gain omitted → null+ { prompt: 'b', gain: 0 }, // intentional mute → 0+ { prompt: 'c', gain: 99 }, // clamped to 4+ { prompt: 'd', gain: -1 }, // negative → null+ ],+ });+ expect(i.stages.audio.cues.map((c) => c.gain)).toEqual([null, 0, 4, null]);+ });++ it('caps cues[] at the max (slice before sanitize, mirroring lines[])', async () => {+ const huge = Array.from({ length: 300 }, (_, n) => ({ prompt: `cue ${n}` }));+ const i = await makeIssue({ cues: huge });+ expect(i.stages.audio.cues).toHaveLength(200);+ });++ it('drops non-object cues', async () => {+ const i = await makeIssue({ cues: [{ prompt: 'keep' }, null, 'nope', 42, { prompt: 'also keep' }] });+ expect(i.stages.audio.cues.map((c) => c.prompt)).toEqual(['keep', 'also keep']);+ });++ it('non-array cues collapses to []', async () => {+ const i = await makeIssue({ cues: 'not-an-array' });+ expect(i.stages.audio.cues).toEqual([]);+ });});describe('reassignIssuesToSeries (season mapping)', () => {diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex 0bc5ad6a2e..6c41e1f185 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -2547,7 +2547,7 @@ describe('peerSync', () => {record: { id: 's1', name: 'Foo' },assetManifest: [],sourceInstanceId: 'peer-a',- portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, pipelineSeries: 1, pipelineIssues: 2 } },+ portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, pipelineSeries: 1, pipelineIssues: 3 } },});expect(mergeSeriesFromSync).toHaveBeenCalled();expect(mergeIssuesFromSync).not.toHaveBeenCalled();@@ -2562,10 +2562,10 @@ describe('peerSync', () => {issues: [{ id: 'i1', seriesId: 's1', deleted: false, deletedAt: null }],assetManifest: [],sourceInstanceId: 'peer-a',- portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, pipelineSeries: 1, pipelineIssues: 2 } },+ portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, pipelineSeries: 1, pipelineIssues: 3 } },}).catch((err) => err);expect(rejection.code).toBe('PEER_SYNC_SCHEMA_VERSION_AHEAD');- expect(rejection.details.ahead).toEqual([{ category: 'pipelineIssues', senderV: 2, receiverV: 1 }]);+ expect(rejection.details.ahead).toEqual([{ category: 'pipelineIssues', senderV: 3, receiverV: 2 }]);expect(mergeSeriesFromSync).not.toHaveBeenCalled();expect(mergeIssuesFromSync).not.toHaveBeenCalled();});@@ -2616,10 +2616,10 @@ describe('peerSync', () => {issues: [{ id: 'i1', seriesId: 's1', deleted: false, deletedAt: null }],assetManifest: [],sourceInstanceId: 'peer-a',- portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, pipelineSeries: 1, pipelineIssues: 2 } },+ portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, pipelineSeries: 1, pipelineIssues: 3 } },}).catch((err) => err);expect(rejection.code).toBe('PEER_SYNC_SCHEMA_VERSION_AHEAD');- expect(rejection.details.ahead).toEqual([{ category: 'pipelineIssues', senderV: 2, receiverV: 1 }]);+ expect(rejection.details.ahead).toEqual([{ category: 'pipelineIssues', senderV: 3, receiverV: 2 }]);expect(mergeSeriesFromSync).not.toHaveBeenCalled();expect(mergeIssuesFromSync).not.toHaveBeenCalled();});