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
address review (codex): close cross-peer score-loss paths and bound render work
[._.]/ Adam Eivyfc400ca42141
diff --git a/server/lib/chiptuneRender.js b/server/lib/chiptuneRender.jsindex 6ec1ff49c1..de8901f191 100644--- a/server/lib/chiptuneRender.js+++ b/server/lib/chiptuneRender.js@@ -75,9 +75,15 @@ export function renderScoreToPcm(score, { sampleRate = CHIPTUNE_SAMPLE_RATE } =// Sweep constants are per-preset, not per-sample — hoist out of the loop.const k = preset.kind === 'sweep' ? Math.log(preset.toHz / preset.fromHz) / preset.decaySec : 0;const fromOverK = k ? preset.fromHz / k : 0;+ // End-of-note release taper: exponential decay alone can leave a hit+ // near the loop boundary audibly non-zero at its final sample (a click+ // on loop restart). Mirror the tonal branch's inside-the-note release.+ const noteDurSec = durSamples / sampleRate;+ const release = Math.min(0.01, noteDurSec * 0.25);for (let i = 0; i < durSamples; i += 1) {const t = i / sampleRate;- const env = Math.exp(-t / preset.decaySec) * (t < ATTACK_SEC ? t / ATTACK_SEC : 1);+ let env = Math.exp(-t / preset.decaySec) * (t < ATTACK_SEC ? t / ATTACK_SEC : 1);+ if (t > noteDurSec - release) env *= Math.max(0, (noteDurSec - t) / release);let s;if (preset.kind === 'sweep') {// Exponential pitch sweep integrated in closed form keeps phase smooth.diff --git a/server/lib/chiptuneRender.test.js b/server/lib/chiptuneRender.test.jsindex f9d9b7a9c9..a7b2366c35 100644--- a/server/lib/chiptuneRender.test.js+++ b/server/lib/chiptuneRender.test.js@@ -63,6 +63,22 @@ describe('renderScoreToPcm', () => {const tail = Math.abs(pcm[pcm.length - 1]);expect(tail).toBeLessThan(0.2);});++ it('a drum hit ending at the loop boundary tapers to ~zero (no loop click)', () => {+ // A snare on the very last step: its 0.12s exponential decay alone would+ // still be audibly non-zero after a 0.125s note — the release taper must+ // bring the final sample to (near) silence so the loop restart is seamless.+ const s = score();+ s.patterns.A.notes.pulse1 = [];+ s.patterns.A.notes.triangle = [];+ s.patterns.A.notes.noise = [{ step: 15, pitch: 'snare', len: 1, vel: 1 }];+ const pcm = renderScoreToPcm(s);+ expect(Math.abs(pcm[pcm.length - 1])).toBeLessThan(0.005);+ // The hit itself still sounds (the taper is a tail, not a mute).+ let peak = 0;+ for (const v of pcm) peak = Math.max(peak, Math.abs(v));+ expect(peak).toBeGreaterThan(0.05);+ });});describe('pcmToWavBuffer', () => {diff --git a/server/lib/chiptuneScore.js b/server/lib/chiptuneScore.jsindex 6cdfc8632a..337c28a430 100644--- a/server/lib/chiptuneScore.js+++ b/server/lib/chiptuneScore.js@@ -38,6 +38,14 @@ export const CHIPTUNE_LIMITS = Object.freeze({// gigabytes from one errant LLM response. 3 minutes is far beyond any// sane background loop.MAX_LOOP_SEC: 180,+ // Aggregate cap on VOICED time (sum of every note's clamped length across+ // the order walk). The loop-duration cap bounds the output buffer but not+ // the render work: hundreds of full-loop overlapping notes would each spin+ // the per-sample synth loop for the whole piece (billions of iterations+ // from one errant response). 4 channels × MAX_LOOP_SEC fully voiced = 720s+ // is the physical ceiling of distinct-channel audio; anything past it is+ // pure overdraw.+ NOTE_SECONDS_MAX: 720,TITLE_MAX: 120,});@@ -95,6 +103,16 @@ export const chiptuneScoreSchema = z.object({if (channelIds.size !== score.channels.length) {ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['channels'], message: 'channel ids must be unique' });}+ // The channel palette is fixed NES-style: the id determines the waveform.+ // Left unbound, `{ id: 'pulse1', wave: 'noise' }` validates and then every+ // melody note on that channel silently drops (pitches aren't drum presets) —+ // persisting a broken score instead of triggering the runner's schema retry.+ for (const [i, c] of score.channels.entries()) {+ const expected = c.id === 'noise' ? 'noise' : c.id === 'triangle' ? 'triangle' : 'square';+ if (c.wave !== expected) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['channels', i, 'wave'], message: `channel "${c.id}" must use wave "${expected}"` });+ }+ }for (const name of score.order) {if (!score.patterns[name]) {ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['order'], message: `order references unknown pattern "${name}"` });@@ -118,10 +136,29 @@ export const chiptuneScoreSchema = z.object({if (totalSteps > CHIPTUNE_LIMITS.TOTAL_STEPS_MAX) {ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['order'], message: `loop is too long (${totalSteps} steps > ${CHIPTUNE_LIMITS.TOTAL_STEPS_MAX})` });}- const totalSec = totalSteps * (60 / (score.bpm * score.stepsPerBeat));+ const stepSec = 60 / (score.bpm * score.stepsPerBeat);+ const totalSec = totalSteps * stepSec;if (totalSec > CHIPTUNE_LIMITS.MAX_LOOP_SEC) {ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['order'], message: `loop is too long (${Math.round(totalSec)}s > ${CHIPTUNE_LIMITS.MAX_LOOP_SEC}s)` });}+ // Bound the aggregate VOICED time the renderer will synthesize (see+ // NOTE_SECONDS_MAX) — the duration cap alone doesn't bound overlapping-note+ // render work. Mirrors buildScoreEvents' clamp semantics (len clamped to the+ // pattern end; out-of-pattern notes contribute nothing).+ let voicedSteps = 0;+ for (const name of score.order) {+ const pattern = score.patterns[name];+ const steps = pattern.bars * score.beatsPerBar * score.stepsPerBeat;+ for (const notes of Object.values(pattern.notes || {})) {+ for (const note of notes) {+ if (note.step >= steps) continue;+ voicedSteps += Math.min(note.len, steps - note.step);+ }+ }+ }+ if (voicedSteps * stepSec > CHIPTUNE_LIMITS.NOTE_SECONDS_MAX) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['patterns'], message: `too much voiced audio (${Math.round(voicedSteps * stepSec)}s of notes > ${CHIPTUNE_LIMITS.NOTE_SECONDS_MAX}s)` });+ }});/**diff --git a/server/lib/chiptuneScore.test.js b/server/lib/chiptuneScore.test.jsindex 1f6b5f8694..abc118cbe7 100644--- a/server/lib/chiptuneScore.test.js+++ b/server/lib/chiptuneScore.test.js@@ -47,6 +47,29 @@ describe('chiptuneScoreSchema', () => {expect(chiptuneScoreSchema.safeParse(score).success).toBe(false);});+ it('binds each channel id to its fixed waveform', () => {+ const score = validScore();+ score.channels[0].wave = 'noise'; // pulse1 must be square+ expect(chiptuneScoreSchema.safeParse(score).success).toBe(false);+ const score2 = validScore();+ score2.channels[2].wave = 'square'; // noise must be noise+ expect(chiptuneScoreSchema.safeParse(score2).success).toBe(false);+ });++ it('rejects a score whose aggregate voiced time exceeds the note-seconds cap', () => {+ // 60 BPM, 1 step/beat → 1s steps; one 4-step bar per pattern. 30 order+ // entries × 4 steps = 120s loop (under 180s), but 512 full-pattern notes+ // per channel push voiced time to 512×4×30 steps ≫ 720s.+ const score = validScore();+ score.bpm = 60;+ score.stepsPerBeat = 1;+ score.patterns.A.notes.pulse1 = Array.from({ length: 512 }, () => ({ step: 0, pitch: 'C5', len: 4 }));+ score.order = Array(30).fill('A');+ const r = chiptuneScoreSchema.safeParse(score);+ expect(r.success).toBe(false);+ expect(JSON.stringify(r.error.issues)).toContain('too much voiced audio');+ });+it('rejects duplicate channel ids', () => {const score = validScore();score.channels.push({ id: 'pulse1', wave: 'square' });diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.jsindex 0bc7efa047..df273d818a 100644--- a/server/lib/conflictJournal.js+++ b/server/lib/conflictJournal.js@@ -322,7 +322,10 @@ export const RESTORABLE_FIELDS = Object.freeze({// `renders` IS restorable (a conflict restore must bring back the local render// history) but is EXCLUDED FROM THE CONTENT HASH — see HASH_EXCLUDED_FIELDS for// why (base-hash compatibility for this additive backfilled field).- track: ['title', 'albumId', 'artistId', 'artist', 'lyrics', 'prompt', 'engine', 'modelId', 'durationSec', 'audioFilename', 'renders'],+ // `chiptuneScore`/`chiptunePrompt` (#2911) follow the `renders` pattern:+ // restorable (a conflict restore must bring back the local composition) but+ // excluded from the content hash for cross-version base-hash stability.+ track: ['title', 'albumId', 'artistId', 'artist', 'lyrics', 'prompt', 'engine', 'modelId', 'durationSec', 'audioFilename', 'renders', 'chiptuneScore', 'chiptunePrompt'],// Issue: the user-authored content the merge can restore. `stages` carries// the bulk of the work (prose, comic pages, render metadata). Server-owned /// structural fields are excluded deliberately — `number` is renumber-managed,diff --git a/server/services/tracks/logic.js b/server/services/tracks/logic.jsindex c150e5a8ee..1857844297 100644--- a/server/services/tracks/logic.js+++ b/server/services/tracks/logic.js@@ -286,7 +286,20 @@ export function mergeTrackRecord(local, remoteRaw) {if (!remote) return { next: null, inserted: false, remoteWins: false, changed: false };if (!local) return { next: remote, inserted: true, remoteWins: true, changed: true };const remoteWins = compareNewerWins(remote.updatedAt, local.updatedAt);- const next = remoteWins ? remote : local;+ let next = remoteWins ? remote : local;+ // Absent-vs-cleared (#2911, per the CLAUDE.md merge convention): a payload+ // from a chiptune-unaware (≤v2) peer lacks the chiptune KEYS entirely, while+ // a v3 peer that intentionally cleared the score sends `chiptuneScore: null`+ // explicitly. Sanitizing collapses both to null, so gate on key presence in+ // the RAW payload — a winning key-absent remote must not erase the local+ // composition. (The sender-ahead direction is already version-gated; this+ // covers the accepted sender-behind direction.)+ if (remoteWins && next === remote) {+ const carry = {};+ if (!('chiptuneScore' in remoteRaw) && local.chiptuneScore) carry.chiptuneScore = local.chiptuneScore;+ if (!('chiptunePrompt' in remoteRaw) && local.chiptunePrompt) carry.chiptunePrompt = local.chiptunePrompt;+ if (Object.keys(carry).length) next = { ...remote, ...carry };+ }const changed = JSON.stringify(next) !== JSON.stringify(local);return { next, inserted: false, remoteWins, changed };}diff --git a/server/services/tracks/logic.test.js b/server/services/tracks/logic.test.jsindex 52c7d5269e..fd823f2a99 100644--- a/server/services/tracks/logic.test.js+++ b/server/services/tracks/logic.test.js@@ -200,5 +200,26 @@ describe('tracks logic', () => {expect(cleared.chiptuneScore).toBeNull();expect(cleared.chiptunePrompt).toBe('');});++ it('merge preserves the local score when a winning remote payload lacks the keys entirely', () => {+ // A ≤v2 (chiptune-unaware) peer's payload has no chiptune keys — its+ // newer unrelated edit must not erase the local composition.+ const local = sanitizeTrack({ id: 'track-1', title: 'X', chiptuneScore: score, chiptunePrompt: 'v1', updatedAt: '2026-01-01T00:00:00.000Z' });+ const behindPeer = { id: 'track-1', title: 'Renamed', updatedAt: '2026-02-01T00:00:00.000Z' };+ const merged = mergeTrackRecord(local, behindPeer);+ expect(merged.remoteWins).toBe(true);+ expect(merged.next.title).toBe('Renamed');+ expect(merged.next.chiptuneScore).toMatchObject({ bpm: 120 });+ expect(merged.next.chiptunePrompt).toBe('v1');+ });++ it('merge applies an explicit remote clear (key present with null/empty)', () => {+ const local = sanitizeTrack({ id: 'track-1', title: 'X', chiptuneScore: score, chiptunePrompt: 'v1', updatedAt: '2026-01-01T00:00:00.000Z' });+ const v3Clear = { id: 'track-1', title: 'X', chiptuneScore: null, chiptunePrompt: '', updatedAt: '2026-02-01T00:00:00.000Z' };+ const merged = mergeTrackRecord(local, v3Clear);+ expect(merged.remoteWins).toBe(true);+ expect(merged.next.chiptuneScore).toBeNull();+ expect(merged.next.chiptunePrompt).toBe('');+ });});});