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

feat([issue-1027]): persist per-take pitch analysis on song recordings

Adam Eivyde0e5de2da62
diff --git a/scripts/migrations/078-song-recording-pitch-analysis.js b/scripts/migrations/078-song-recording-pitch-analysis.js
new file mode 100644
index 0000000000..247380fffc
--- /dev/null
+++ b/scripts/migrations/078-song-recording-pitch-analysis.js
@@ -0,0 +1,27 @@
+/**
+ * Registration stub for per-take pitch analysis on song recordings (#1027).
+ *
+ * The `Recording` shape (`server/services/songs.js`) gained two OPTIONAL,
+ * absent-tolerant fields — `pitchTrack` (a bounded, downsampled tuner trace) and
+ * `accuracy` (a color-match summary) — so the tuner history and grading aren't
+ * recomputed on every open. Both are additive: a legacy take simply has neither
+ * field, the sanitizer reads it back unchanged, and the Zod schema treats both as
+ * optional, so an older client's payload (no pitch analysis) still validates.
+ *
+ * Because the change is purely additive and the read path is absent-tolerant,
+ * there is no on-disk data to rewrite — existing `data/songs.json` records load
+ * as-is and gain the fields only when the user records a scored take. This stub
+ * ships anyway so the schema bump is RECORDED in `data/migrations.applied.json`:
+ * the distribution model is many installs upgrading independently (CLAUDE.md →
+ * Distribution model), and a recorded migration is the audit trail showing when
+ * the new recording shape was introduced.
+ *
+ * No-op + idempotent: nothing to rewrite in the file runner.
+ */
+
+export default {
+ async up() {
+ console.log('🎤 migration 078: song recording pitch-analysis fields are additive/absent-tolerant; nothing to rewrite — recording the schema bump.');
+ return { updated: 0, reason: 'additive-no-op' };
+ },
+};
diff --git a/scripts/migrations/078-song-recording-pitch-analysis.test.js b/scripts/migrations/078-song-recording-pitch-analysis.test.js
new file mode 100644
index 0000000000..1087df57b9
--- /dev/null
+++ b/scripts/migrations/078-song-recording-pitch-analysis.test.js
@@ -0,0 +1,15 @@
+import { describe, it, expect } from 'vitest';
+import migration from './078-song-recording-pitch-analysis.js';
+
+describe('migration 078 — song recording pitch-analysis registration stub', () => {
+ it('is a no-op that records the additive schema bump', async () => {
+ const result = await migration.up({ rootDir: '/tmp/nonexistent' });
+ expect(result).toEqual({ updated: 0, reason: 'additive-no-op' });
+ });
+
+ it('is idempotent (re-running changes nothing)', async () => {
+ const first = await migration.up({ rootDir: '/tmp/nonexistent' });
+ const second = await migration.up({ rootDir: '/tmp/nonexistent' });
+ expect(second).toEqual(first);
+ });
+});
diff --git a/server/routes/songs.js b/server/routes/songs.js
index ed018e6329..99eddae575 100644
--- a/server/routes/songs.js
+++ b/server/routes/songs.js
@@ -38,9 +38,35 @@ const layerSchema = z.object({
notes: str(svc.FIELD_MAX_LENGTH).optional().default(''),
});
+// One downsampled tuner sample from a take's pitch trace (#1027). hz/cents/
+// clarity are nullable so a silent frame round-trips; the service clamps tMs.
+const pitchSampleSchema = z.object({
+ tMs: z.number().optional(),
+ hz: z.number().nullable().optional(),
+ cents: z.number().nullable().optional(),
+ clarity: z.number().nullable().optional(),
+});
+
+// Per-take color-match accuracy summary (#1027), mirroring colorMatch's
+// summarizeAccuracy output. All fields optional/absent-tolerant; the service
+// clamps the percentage and drops unrecognized grades.
+const accuracySchema = z.object({
+ percentInTune: z.number().optional(),
+ graded: z.number().optional(),
+ counts: z.object({
+ 'in-tune': z.number().optional(),
+ close: z.number().optional(),
+ off: z.number().optional(),
+ missed: z.number().optional(),
+ }).partial().optional(),
+ perNote: z.array(z.string()).max(svc.PER_NOTE_GRADES_MAX).optional(),
+});
+
// A saved vocal take. `filename` is the /api/uploads file the audio is served
// from (the client uploads the WAV first, then PUTs the song with the returned
// filename). Numbers are accepted for the mixer; the service clamps them.
+// `pitchTrack`/`accuracy` are optional per-take pitch analysis (#1027) — absent
+// on legacy/unscored takes, persisted so the tuner history isn't recomputed.
const recordingSchema = z.object({
id: str(svc.ID_MAX_LENGTH).optional(),
layerId: str(svc.ID_MAX_LENGTH).optional().default(''),
@@ -50,6 +76,8 @@ const recordingSchema = z.object({
peak: z.number().min(0).max(1).optional(),
muted: z.boolean().optional(),
createdAt: z.string().optional(),
+ pitchTrack: z.array(pitchSampleSchema).max(svc.PITCH_TRACK_MAX).optional(),
+ accuracy: accuracySchema.optional(),
});
// A sheet-music part — a harmony variation of the base score, in the same
diff --git a/server/routes/songs.test.js b/server/routes/songs.test.js
index add542f0d5..c8d558bb27 100644
--- a/server/routes/songs.test.js
+++ b/server/routes/songs.test.js
@@ -129,6 +129,40 @@ describe('songs route', () => {
expect(mocks.updateSong).not.toHaveBeenCalled();
});
+ it('PUT /:id accepts a recording with pitchTrack + accuracy analysis (#1027)', async () => {
+ mocks.updateSong.mockResolvedValue({ id: 'song-1' });
+ const res = await request(makeApp()).put('/api/songs/song-1').send({
+ recordings: [{
+ filename: 'take.wav',
+ pitchTrack: [{ tMs: 0, hz: 220, cents: -3, clarity: 0.9 }, { tMs: 50, hz: null }],
+ accuracy: { percentInTune: 80, graded: 5, counts: { 'in-tune': 4, close: 1 }, perNote: ['in-tune', 'close'] },
+ }],
+ });
+ expect(res.status).toBe(200);
+ const [, patch] = mocks.updateSong.mock.calls[0];
+ expect(patch.recordings[0].pitchTrack).toHaveLength(2);
+ expect(patch.recordings[0].accuracy.percentInTune).toBe(80);
+ });
+
+ it('PUT /:id accepts a legacy recording with no pitch analysis (absent-tolerant)', async () => {
+ mocks.updateSong.mockResolvedValue({ id: 'song-1' });
+ const res = await request(makeApp()).put('/api/songs/song-1').send({
+ recordings: [{ filename: 'legacy.wav', durationMs: 500 }],
+ });
+ expect(res.status).toBe(200);
+ const [, patch] = mocks.updateSong.mock.calls[0];
+ expect(patch.recordings[0]).not.toHaveProperty('pitchTrack');
+ });
+
+ it('PUT /:id rejects a pitchTrack exceeding the bound', async () => {
+ const tooMany = Array.from({ length: 4001 }, (_, i) => ({ tMs: i }));
+ const res = await request(makeApp()).put('/api/songs/song-1').send({
+ recordings: [{ filename: 'x.wav', pitchTrack: tooMany }],
+ });
+ expect(res.status).toBe(400);
+ expect(mocks.updateSong).not.toHaveBeenCalled();
+ });
+
it('PUT /:id accepts a references array', async () => {
mocks.updateSong.mockResolvedValue({ id: 'song-1' });
const res = await request(makeApp()).put('/api/songs/song-1').send({
diff --git a/server/services/songs.js b/server/services/songs.js
index dfb2cd7701..3c9c0e5179 100644
--- a/server/services/songs.js
+++ b/server/services/songs.js
@@ -50,6 +50,17 @@ export const RECORDINGS_MAX = 64; // saved vocal takes for layered playback
export const REFERENCES_MAX = 12; // reference links/videos (e.g. TikTok)
export const PARTNERS_MAX = 12; // partner-song ids (rounds sung together)
export const URL_MAX_LENGTH = 512; // uploaded-file path/url
+// Per-take pitch analysis (#1027). The pitch track is a DOWNSAMPLED tuner trace
+// kept for replay/training so it isn't recomputed on every open; bound it so a
+// long take can't bloat data/songs.json. `accuracy.perNote` mirrors the
+// color-match grade-per-note array (#1025), bounded the same way a score can't
+// be arbitrarily long.
+export const PITCH_TRACK_MAX = 4000; // downsampled tuner samples per take
+export const PER_NOTE_GRADES_MAX = 2000; // per-note color-match grades per take
+// Valid color-match grades — mirrors client/src/lib/colorMatch.js GRADE. An
+// unrecognized grade is dropped (a newer/older client vocabulary can't 400 or
+// poison the persisted array).
+export const RECORDING_GRADES = ['in-tune', 'close', 'off', 'missed', 'pending'];
// Trim a string field, returning '' for non-strings. Mirrors the
// absent-vs-empty rule in CLAUDE.md: callers decide whether '' clears.
@@ -92,12 +103,68 @@ const sanitizeLayer = (l) => {
};
};
+// A finite number or null — used by the pitch-analysis fields so a missing
+// sample component (e.g. a silent frame with no detectable pitch) round-trips
+// as null rather than NaN/0.
+const finiteOrNull = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
+
+// One downsampled tuner sample ({ tMs, hz, cents, clarity }) from a take's
+// pitch trace (#1027). `tMs` is the elapsed time in the take; hz/cents/clarity
+// are the detected pitch, cents-from-target, and confidence. Drops shapeless
+// entries; a sample with no time and no pitch carries no information.
+const sanitizePitchSample = (s) => {
+ if (!s || typeof s !== 'object') return null;
+ const tMs = finiteOrNull(s.tMs);
+ const hz = finiteOrNull(s.hz);
+ if (tMs === null && hz === null) return null;
+ return {
+ tMs: tMs === null ? 0 : Math.max(0, Math.round(tMs)),
+ hz,
+ cents: finiteOrNull(s.cents),
+ clarity: finiteOrNull(s.clarity),
+ };
+};
+
+// The per-take accuracy summary (#1027), mirroring color-match's
+// summarizeAccuracy output ({ percentInTune, graded, counts, perNote }). All
+// fields are optional/absent-tolerant — a take recorded before color-match (or
+// without scoring) has no accuracy at all, which is distinct from a scored take
+// that graded zero notes (graded: 0). Returns null when there's nothing to
+// persist so the field stays absent rather than an empty husk.
+const sanitizeAccuracy = (a) => {
+ if (!a || typeof a !== 'object') return null;
+ const counts = a.counts && typeof a.counts === 'object' ? a.counts : {};
+ const perNote = (Array.isArray(a.perNote) ? a.perNote : [])
+ .map((g) => trimField(g, LABEL_MAX_LENGTH))
+ .filter((g) => RECORDING_GRADES.includes(g))
+ .slice(0, PER_NOTE_GRADES_MAX);
+ const clampPercent = finiteOrNull(a.percentInTune);
+ const clampGraded = finiteOrNull(a.graded);
+ return {
+ percentInTune: clampPercent === null ? 0 : Math.max(0, Math.min(100, Math.round(clampPercent))),
+ graded: clampGraded === null ? perNote.length : Math.max(0, Math.round(clampGraded)),
+ counts: {
+ 'in-tune': Math.max(0, Math.round(finiteOrNull(counts['in-tune']) ?? 0)),
+ close: Math.max(0, Math.round(finiteOrNull(counts.close) ?? 0)),
+ off: Math.max(0, Math.round(finiteOrNull(counts.off) ?? 0)),
+ missed: Math.max(0, Math.round(finiteOrNull(counts.missed) ?? 0)),
+ },
+ perNote,
+ };
+};
+
// One saved vocal take ({ id, layerId, filename, label, durationMs, peak,
// mutedByDefault }). `filename` is the /api/uploads file name the audio is
// served from; a recording without one is meaningless, so it's dropped.
// `layerId` ties a take to a voice layer for the layered-playback mixer (free
// text — empty means "unassigned"). Numbers are coerced/clamped; bad values
// fall to sensible defaults rather than throwing.
+//
+// Optional pitch analysis (#1027): `pitchTrack` (a bounded, downsampled tuner
+// trace) and `accuracy` (a color-match summary) are persisted so the tuner
+// history and grading aren't recomputed on every open. Both are absent on
+// legacy takes and on takes recorded without scoring — the fields only appear
+// when there's analysis to keep, so a pre-feature record reads back unchanged.
const sanitizeRecording = (r) => {
if (!r || typeof r !== 'object') return null;
const filename = trimField(r.filename, URL_MAX_LENGTH);
@@ -106,7 +173,7 @@ const sanitizeRecording = (r) => {
? Math.max(0, Math.round(r.durationMs)) : 0;
const peak = typeof r.peak === 'number' && Number.isFinite(r.peak)
? Math.max(0, Math.min(1, r.peak)) : 0;
- return {
+ const rec = {
id: trimField(r.id, ID_MAX_LENGTH) || `rec-${randomUUID().slice(0, 8)}`,
layerId: trimField(r.layerId, ID_MAX_LENGTH),
label: trimField(r.label, LABEL_MAX_LENGTH),
@@ -116,6 +183,14 @@ const sanitizeRecording = (r) => {
muted: r.muted === true,
createdAt: typeof r.createdAt === 'string' ? r.createdAt : new Date().toISOString(),
};
+ // Absent ⇒ omit (legacy/unscored take); present ⇒ sanitize + bound via the
+ // shared sanitizeList. Keeping the keys off the object when there's no
+ // analysis avoids a wave of empty arrays in data/songs.json on every take.
+ const pitchTrack = sanitizeList(r.pitchTrack, sanitizePitchSample, PITCH_TRACK_MAX);
+ if (pitchTrack.length) rec.pitchTrack = pitchTrack;
+ const accuracy = sanitizeAccuracy(r.accuracy);
+ if (accuracy) rec.accuracy = accuracy;
+ return rec;
};
// One reference link/video ({ id, url, label, note }) — external study
diff --git a/server/services/songs.test.js b/server/services/songs.test.js
index 2a4aa719d9..1db318ba0e 100644
--- a/server/services/songs.test.js
+++ b/server/services/songs.test.js
@@ -161,6 +161,71 @@ describe('songs service', () => {
expect(song.recordings[0].id).toBe('rec-keep');
});
+ it('legacy takes load unchanged — no pitchTrack/accuracy keys added', () => {
+ const song = svc.sanitizeSong({ id: 'x', recordings: [{ filename: 'legacy.wav', durationMs: 500 }] });
+ const rec = song.recordings[0];
+ expect(rec).not.toHaveProperty('pitchTrack');
+ expect(rec).not.toHaveProperty('accuracy');
+ });
+
+ it('persists + bounds a downsampled pitchTrack, dropping shapeless samples', () => {
+ const song = svc.sanitizeSong({
+ id: 'x',
+ recordings: [{
+ filename: 'take.wav',
+ pitchTrack: [
+ { tMs: 0.6, hz: 220, cents: -3.2, clarity: 0.9 }, // tMs rounded, kept
+ { tMs: null, hz: null }, // no time + no pitch → dropped
+ { tMs: 100 }, // time only → kept, nulls fill
+ ],
+ }],
+ });
+ const track = song.recordings[0].pitchTrack;
+ expect(track).toHaveLength(2);
+ expect(track[0]).toEqual({ tMs: 1, hz: 220, cents: -3.2, clarity: 0.9 });
+ expect(track[1]).toEqual({ tMs: 100, hz: null, cents: null, clarity: null });
+ });
+
+ it('clamps an oversized pitchTrack to PITCH_TRACK_MAX', () => {
+ const samples = Array.from({ length: svc.PITCH_TRACK_MAX + 50 }, (_, i) => ({ tMs: i, hz: 200 }));
+ const song = svc.sanitizeSong({ id: 'x', recordings: [{ filename: 't.wav', pitchTrack: samples }] });
+ expect(song.recordings[0].pitchTrack).toHaveLength(svc.PITCH_TRACK_MAX);
+ });
+
+ it('persists an accuracy summary, clamping percent and dropping unknown grades', () => {
+ const song = svc.sanitizeSong({
+ id: 'x',
+ recordings: [{
+ filename: 't.wav',
+ accuracy: {
+ percentInTune: 150, // clamped to 100
+ graded: 4,
+ counts: { 'in-tune': 2, close: 1, off: 1, missed: 0 },
+ perNote: ['in-tune', 'close', 'bogus', 'off', 'missed'], // 'bogus' dropped
+ },
+ }],
+ });
+ const acc = song.recordings[0].accuracy;
+ expect(acc.percentInTune).toBe(100);
+ expect(acc.graded).toBe(4);
+ expect(acc.counts).toEqual({ 'in-tune': 2, close: 1, off: 1, missed: 0 });
+ expect(acc.perNote).toEqual(['in-tune', 'close', 'off', 'missed']);
+ });
+
+ it('derives accuracy.graded from perNote when not supplied', () => {
+ const song = svc.sanitizeSong({
+ id: 'x',
+ recordings: [{ filename: 't.wav', accuracy: { perNote: ['in-tune', 'off'] } }],
+ });
+ expect(song.recordings[0].accuracy.graded).toBe(2);
+ expect(song.recordings[0].accuracy.percentInTune).toBe(0);
+ });
+
+ it('omits accuracy when there is nothing to persist', () => {
+ const song = svc.sanitizeSong({ id: 'x', recordings: [{ filename: 't.wav', accuracy: 'not-an-object' }] });
+ expect(song.recordings[0]).not.toHaveProperty('accuracy');
+ });
+
it('stamps builtIn from the seed-id set, ignoring the raw value', () => {
const seedId = [...svc.BUILTIN_SONG_IDS][0];
expect(svc.sanitizeSong({ id: seedId }).builtIn).toBe(true);