Skip to content

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

fix([issue-894]): harden numeric edge cases in learning reset, goal velocity, audio mux

[._.]/ Adam Eivyab69c2a6dad2
diff --git a/server/services/creativeDirector/stitchRunner.js b/server/services/creativeDirector/stitchRunner.js
index 9a41274ff0..1f3c665ec8 100644
--- a/server/services/creativeDirector/stitchRunner.js
+++ b/server/services/creativeDirector/stitchRunner.js
@@ -23,7 +23,7 @@ import { loadHistory } from '../videoGen/local.js';
import { addItem as addCollectionItem } from '../mediaCollections.js';
import { buildTimelineClips } from './orchestrator.js';
import { getProject, updateProject } from './local.js';
-import { getIssue } from '../pipeline/issues.js';
+import { getIssue, sanitizeAudioMode } from '../pipeline/issues.js';
import { muxMusicBed, muxVoLines, muxCueBed, muxStripAudio, resolveMusicTrackPath, selectPlacedVoLines, selectPlacedCues } from '../pipeline/audioMux.js';
import { placeCuesOnTimeline } from '../pipeline/audioCuePlacement.js';
import { PATHS } from '../../lib/fileUtils.js';
@@ -147,7 +147,7 @@ async function maybeMuxPipelineAudio(project, finalEntry) {
// Whole-episode audio strategy (issue #863). Absent / unknown audioMode reads
// as 'per-clip' (the sanitizer already defaults it), so existing issues keep
// today's behavior. Placed VO lines are muxable in every non-silent mode.
- const audioMode = issue.stages?.audio?.audioMode || 'per-clip';
+ const audioMode = sanitizeAudioMode(issue.stages?.audio?.audioMode);
const voLines = selectPlacedVoLines(issue.stages?.audio?.lines);
// 'generated' — assemble the arc-driven cues[] onto the timeline. Cue timing
diff --git a/server/services/identity/goals.js b/server/services/identity/goals.js
index 078de9146e..8ee7b02454 100644
--- a/server/services/identity/goals.js
+++ b/server/services/identity/goals.js
@@ -93,7 +93,7 @@ export function computeGoalVelocity(goal) {
}
const daysDiff = (new Date(last.date) - new Date(first.date)) / (1000 * 60 * 60 * 24);
- if (daysDiff < 1) return null;
+ if (Number.isNaN(daysDiff) || daysDiff < 1) return null;
const monthsDiff = daysDiff / 30.44;
const totalChange = last.value - first.value;
diff --git a/server/services/identity/goals.test.js b/server/services/identity/goals.test.js
new file mode 100644
index 0000000000..37502703b2
--- /dev/null
+++ b/server/services/identity/goals.test.js
@@ -0,0 +1,36 @@
+import { describe, it, expect } from 'vitest';
+import { computeGoalVelocity } from './goals.js';
+
+describe('computeGoalVelocity', () => {
+ it('returns null with fewer than two progress entries', () => {
+ expect(computeGoalVelocity({ progressHistory: [] })).toBeNull();
+ expect(computeGoalVelocity({ progressHistory: [{ date: '2026-01-01', value: 10 }] })).toBeNull();
+ expect(computeGoalVelocity({})).toBeNull();
+ });
+
+ it('computes a positive percent-per-month from a valid history', () => {
+ const v = computeGoalVelocity({
+ progress: 30,
+ progressHistory: [
+ { date: '2026-01-01', value: 0 },
+ { date: '2026-02-01', value: 30 },
+ ],
+ });
+ expect(v).not.toBeNull();
+ // 30 points over ~31 days ≈ one month → ~30%/month.
+ expect(v.percentPerMonth).toBeGreaterThan(25);
+ expect(v.trend).toBe('stable');
+ });
+
+ it('returns null when a progress entry has a malformed date (NaN guard)', () => {
+ // A bad `progressHistory.date` makes the date subtraction NaN; without the
+ // guard that yields NaN velocity / mis-ordered trend rather than a clean
+ // "insufficient data" null.
+ expect(computeGoalVelocity({
+ progressHistory: [
+ { date: 'not-a-date', value: 0 },
+ { date: '2026-02-01', value: 30 },
+ ],
+ })).toBeNull();
+ });
+});
diff --git a/server/services/pipeline/audioMux.js b/server/services/pipeline/audioMux.js
index 82f1905b49..97462820a1 100644
--- a/server/services/pipeline/audioMux.js
+++ b/server/services/pipeline/audioMux.js
@@ -43,6 +43,16 @@ import { statMusicTrack } from './musicLibrary.js';
// (4d.2), but not so quiet the user wonders if it's there.
const DEFAULT_MUSIC_GAIN = 0.5;
+// Coerce a gain to a finite number, falling back to DEFAULT_MUSIC_GAIN for any
+// non-numeric / NaN / Infinity input. Every `volume=` filter string runs through
+// this so a stray non-numeric gain can never inject `"NaN"` into the ffmpeg
+// graph (which aborts the whole render). Callers today pass clamped/frozen
+// gains, so this is parity hardening on these exported "pure" builders.
+const finiteGain = (value) => {
+ const n = Number(value);
+ return Number.isFinite(n) ? n : DEFAULT_MUSIC_GAIN;
+};
+
// Sidechain-ducking defaults — the music bed (sidechain input) is compressed
// whenever the VO track (sidechain key) exceeds the threshold. ratio=8 +
// a low threshold pulls the bed well down under speech; release=300ms lets the
@@ -117,7 +127,7 @@ export async function muxMusicBed(inputVideoPath, { musicPath, musicGain = DEFAU
'-i', inputVideoPath,
'-stream_loop', '-1',
'-i', musicPath,
- '-filter_complex', `[1:a]volume=${Number(musicGain).toFixed(3)},aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo[bed]`,
+ '-filter_complex', `[1:a]volume=${finiteGain(musicGain).toFixed(3)},aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo[bed]`,
'-map', '0:v',
'-map', '[bed]',
'-c:v', 'copy',
@@ -215,7 +225,7 @@ export function buildVoMuxArgs({ inputVideoPath, voLines, musicPath, musicGain =
const beds = [];
if (musicPath) {
const musicIdx = voLines.length + 1;
- const gain = Number(musicGain).toFixed(3);
+ const gain = finiteGain(musicGain).toFixed(3);
chains.push(`[${musicIdx}:a]volume=${gain},${AFMT}[bed]`);
beds.push('[bed]');
}
@@ -370,7 +380,7 @@ export function buildCueMuxArgs({ inputVideoPath, cues, voLines = [], musicGain
cues.forEach((cue, i) => {
const inputIdx = i + 1; // 0 is the video
const delayMs = Math.round(Number(cue.startSec) * 1000);
- const gain = Number(cue.gain ?? musicGain).toFixed(3);
+ const gain = finiteGain(cue.gain ?? musicGain).toFixed(3);
const span = (typeof cue.endSec === 'number' && cue.endSec > cue.startSec)
? cue.endSec - cue.startSec
: null;
diff --git a/server/services/pipeline/audioMux.test.js b/server/services/pipeline/audioMux.test.js
index a139bcee82..a94d9d1b42 100644
--- a/server/services/pipeline/audioMux.test.js
+++ b/server/services/pipeline/audioMux.test.js
@@ -313,6 +313,22 @@ describe('buildVoMuxArgs', () => {
expect(filter).toContain('[vo0]apad[aout]');
expect(filter).not.toContain('amix');
});
+
+ it('falls back to DEFAULT_MUSIC_GAIN for a non-finite musicGain', () => {
+ // A non-numeric gain must never reach the filter string as "NaN" — that
+ // aborts the whole ffmpeg graph. The finite-gain guard substitutes the
+ // default so the bed still renders.
+ const args = buildVoMuxArgs({
+ inputVideoPath: '/v.mp4',
+ voLines: [{ path: '/a.wav', offsetSec: 0 }],
+ musicPath: '/m.mp3',
+ musicGain: 'loud',
+ outPath: '/out.mp4',
+ });
+ const filter = args[args.indexOf('-filter_complex') + 1];
+ expect(filter).toContain(`[2:a]volume=${DEFAULT_MUSIC_GAIN.toFixed(3)}`);
+ expect(filter).not.toContain('NaN');
+ });
});
describe('muxVoLines', () => {
@@ -516,6 +532,19 @@ describe('buildCueMuxArgs', () => {
expect(filter).not.toContain('[cuebed]');
});
+ it('falls back to DEFAULT_MUSIC_GAIN for a non-finite per-cue gain', () => {
+ // Per-cue gain runs through the same finite-gain guard so a malformed cue
+ // gain can't inject "NaN" into the volume filter and abort the render.
+ const args = buildCueMuxArgs({
+ inputVideoPath: '/v.mp4',
+ cues: [{ path: '/c0.wav', startSec: 0, endSec: 30, gain: NaN }],
+ outPath: '/out.mp4',
+ });
+ const filter = args[args.indexOf('-filter_complex') + 1];
+ expect(filter).toContain(`volume=${DEFAULT_MUSIC_GAIN.toFixed(3)}`);
+ expect(filter).not.toContain('NaN');
+ });
+
it('ducks the cue bed under VO when VO lines are present', () => {
const args = buildCueMuxArgs({
inputVideoPath: '/v.mp4',
diff --git a/server/services/taskLearning.test.js b/server/services/taskLearning.test.js
index 14b4bb9cee..f3d70dae9f 100644
--- a/server/services/taskLearning.test.js
+++ b/server/services/taskLearning.test.js
@@ -188,6 +188,34 @@ describe('TaskLearning - resetTaskTypeLearning', () => {
expect(savedData.totals.completed).toBe(0);
expect(savedData.totals.avgDurationMs).toBe(0);
});
+
+ it('clamps successDurationMs to >= 0 when a drifted store would go negative', async () => {
+ // Hand-edited / older store where the running total drifted below a single
+ // task type's accumulated successDurationMs. Subtracting unclamped would go
+ // negative and feed calculateDurationETA a negative avgDurationMs.
+ const data = makeLearningData({
+ byTaskType: {
+ 'self-improve:ui': {
+ completed: 10, succeeded: 8, failed: 2,
+ totalDurationMs: 50000, avgDurationMs: 5000,
+ successDurationMs: 500000, successMaxDurationMs: 80000,
+ lastCompleted: '2026-01-25T00:00:00.000Z', successRate: 80
+ }
+ },
+ errorPatterns: {},
+ totals: {
+ completed: 10, succeeded: 8, failed: 2,
+ totalDurationMs: 50000, avgDurationMs: 5000,
+ successDurationMs: 100000, successMaxDurationMs: 80000
+ }
+ });
+ readFile.mockResolvedValue(JSON.stringify(data));
+
+ await resetTaskTypeLearning('self-improve:ui');
+
+ // 100000 - 500000 would be -400000; the clamp pins it at 0.
+ expect(savedData.totals.successDurationMs).toBe(0);
+ });
});
describe('TaskLearning - getSkippedTaskTypes', () => {
diff --git a/server/services/taskLearning/metrics.js b/server/services/taskLearning/metrics.js
index 15628141fe..3b6c66034a 100644
--- a/server/services/taskLearning/metrics.js
+++ b/server/services/taskLearning/metrics.js
@@ -187,7 +187,7 @@ export async function resetTaskTypeLearning(taskType) {
data.totals.failed -= metrics.failed;
data.totals.totalDurationMs -= metrics.totalDurationMs;
if (data.totals.successDurationMs) {
- data.totals.successDurationMs -= (metrics.successDurationMs || 0);
+ data.totals.successDurationMs = Math.max(0, data.totals.successDurationMs - (metrics.successDurationMs || 0));
}
// Recalculate max from remaining task types (we can't subtract a max)
const remainingTypes = Object.entries(data.byTaskType).filter(([t]) => t !== taskType);