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
songs: chord-tone voicing for derived harmony parts + ship the 500 Miles stack
[._.]/ Adam Eivy3b9e4c9c3291
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 23ee94b172..27ae2b69f0 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,7 +2,7 @@## Added-- **Songs: sheet-music harmony parts, derived from the melody by AI** — a song can now carry multiple staves beyond its base melody — **Bass, Mid Harmony I/II, High Harmony I/II** — each its own sheet music, rhythm-aligned to the melody so the parts stack when sung together. In the Sheet music editor there's a new **Sheet music parts** section with a one-click **Derive with AI**: it reads the song's base melody and writes a full set of harmony parts (chord-tone voicings at the right interval and register for each part), which land in the editor for you to review, tweak, and Save — nothing is auto-saved, matching the rest of the AI assists. You can also add a blank part (seeded from the melody) and hand-edit it. In the read/perform view, the Sheet music card gains a part switcher — flip between Melody and each harmony, and play any one back as a reference tone on its own. Derive is gated on the base melody being saved (it reads the persisted score), so you won't accidentally harmonize stale notes. Built on the existing in-house lead-sheet renderer — no third-party engraving or MIDI library. Try it on the built-in "500 Miles".+- **Songs: sheet-music harmony parts, derived from the melody by AI** — a song can now carry multiple staves beyond its base melody — **Bass, Mid Harmony I/II, High Harmony I/II** — each its own sheet music that stacks with the melody when sung together. In the Sheet music editor there's a new **Sheet music parts** section with a one-click **Derive with AI**: it reads the song's base melody and writes a full layered-folk vocal stack — *chord-tone* voicings (each voice targets a chord tone and moves smoothly, rather than tracking the melody in parallel 3rds/6ths like a "MIDI choir"), with a hymn-like root–fifth bass, sustained inner pads, an upper pad that keeps the dominant-7 leading tone (e.g. the F# on D7 that pulls back to G), a sparse top descant that enters late, sensible per-voice ranges, and staggered entrances. Parts land in the editor for you to review, tweak, and Save — nothing is auto-saved. You can also add a blank part (seeded from the melody) and hand-edit it. In the read/perform view, the Sheet music card gains a part switcher — flip between Melody and each harmony (laid out low→high) and play any one back as a reference tone on its own. Derive is gated on the base melody being saved (it reads the persisted score), so you won't harmonize stale notes. Built on the existing in-house lead-sheet renderer — no third-party engraving or MIDI library. The built-in **"500 Miles"** now ships with the full five-part harmony stack as a worked example.- **Songs: pitch-detection core (foundation for the upcoming vocal tuner & color-match)** — a new in-house, dependency-free DSP module estimates the fundamental frequency of sung audio (McLeod normalized-square-difference autocorrelation, with a clarity score that rejects silence and noise) and maps frequency↔note using the same diatonic staff math the sheet-music renderer already uses — so a detected pitch lands on exactly the note position the staff would draw. It also ships a live pitch tracker that reads a microphone analyser on an animation-frame loop and smooths the result (median + EMA) to suppress the octave jumps raw vocal detection produces. No new third-party library — like the rest of the song system's notation stack, the detector is hand-rolled in-tree. This is groundwork; the singer-facing tuner, color-match grading, and sing-to-score features build on it.- **Songs — an a cappella song workbench (Create → Songs)** — write, arrange, and learn songs like "500 Miles" by Peter, Paul and Mary. Each song tracks its key, tempo, and rhythm shape (slow 4/4 ballad, compound 6/8 dirge, free-time lament, and more), lyric sections, and the voice layers you're stacking — with per-layer learning notes. An "Add from ladder" picker seeds layers in the recommended foundation-first order (lead → bass → thirds → fifths → drone → counter-melody). A deep-linkable **Learning Guide** (Create → Songs → Learning Guide, or `/songs/guide`) covers dirge rhythm shapes with tempo bands, the layer-building ladder, a step-by-step practice sequence for learning a new song, and a plain-language musical-notation primer (staves, time signatures, note values, dynamics, reading a lead sheet). A worked "500 Miles" example is seeded on first visit. Reachable from `⌘K` and voice nav.- **Songs: AI generate, expand & evaluate** — like the manuscript and universe/series creators, the Songs workbench now drafts and critiques arrangements with AI. From the Songs list, **Generate** drafts a full arrangement (lyrics, voice layers, key/tempo/rhythm shape, notation, and learning notes) from the title/artist as a brief; inside the editor, **Generate draft** and **Expand current** rewrite or build on the open draft, and **Evaluate** scores the arrangement 0–100 for performance-readiness with concrete strengths, weaknesses, and suggestions. The model returns rhythm-shape and voice-layer ids the editor's pickers already understand. Generated drafts land in the editor for review and are never auto-saved.diff --git a/client/src/lib/songCraft.js b/client/src/lib/songCraft.jsindex c2b8eb3b9e..54467b55ad 100644--- a/client/src/lib/songCraft.js+++ b/client/src/lib/songCraft.js@@ -147,81 +147,96 @@ export const VOICE_LAYERS = [// The set of sheet-music parts a song can carry beyond its base melody. The// base score is the `melody`; the rest are harmony variations the AI derive// tool produces (and the user edits) — each its own staff in the same lead-sheet-// DSL, rhythm-aligned to the melody so the parts stack. `register` orders them-// low→high for the View-tab part switcher; `interval` is the rule of thumb the-// derive prompt and the UI hint use. Mirrored (id/label/role/register/interval)-// in server/lib/songCraftRef.js so the AI prompt and the editor agree.+// DSL, rhythm-aligned to the melody so the parts stack.+//+// The voicing model is CHORD-TONE, not parallel-interval: each voice targets a+// chord tone (sustaining / moving smoothly), rather than tracking the melody a+// fixed interval away — a folk/a cappella "layered build" where one clear melody+// sits over a grounded bass, two moving inner voices, and one or two sustained+// upper pads, with staggered entrances. Building parallel 3rds/6ths under every+// syllable reads as a "MIDI choir" and is explicitly what this avoids.+//+// `order` lays the stack low→high for the View-tab switcher; `range` and+// `voicing` are the per-voice rules the derive prompt and the UI hint inject.+// Mirrored (id/label/role/order/range/voicing) in server/lib/songCraftRef.js so+// the AI prompt and the editor agree.export const HARMONY_PARTS = [{id: 'melody',label: 'Melody',role: 'melody',- register: 'mid',+ order: 0,+ range: 'as written',derivable: false,- interval: 'The tune itself — the base every harmony is built from.',- advice: 'This is the base score. Lock it first; every derived part follows its rhythm, chords, and phrasing.',+ voicing: 'The lead — carries the lyric and rhythmic detail. The base every harmony targets.',+ advice: 'This is the base score. Lock it first; every derived part is voiced against its chords and phrasing.',},{id: 'bass',label: 'Bass',role: 'bass',- register: 'low',- derivable: true,- interval: 'Chord roots, low — the harmonic floor, often an octave or more below the melody.',- advice: 'Mostly the root of each chord, moving slowly on the strong beats. It is the tuning reference for every voice above.',- },- {- id: 'mid-harmony-1',- label: 'Mid Harmony I',- role: 'harmony',- register: 'mid',+ order: 1,+ range: 'G2–D3 (down to E2)',derivable: true,- interval: 'A third below the melody — the closest inner harmony.',- advice: 'The sweetest, most stable harmony. Build this before any wider interval.',+ voicing: 'Root of each chord, with the fifth as gentle movement — a hymn-like root–fifth–root drone.',+ advice: 'The harmonic floor and tuning reference. Long tones or soft pulses on beats 1 and 3; keep it simple.',},{id: 'mid-harmony-2',label: 'Mid Harmony II',role: 'harmony',- register: 'mid',+ order: 2,+ range: 'B2–E4',derivable: true,- interval: 'A sixth below the melody (a different chord tone from Mid Harmony I).',- advice: 'Fills the inner voice under Mid Harmony I so the mid-register triad is complete.',+ voicing: 'Low inner pad — sustained chord tones below the melody (often the 3rd or 5th of the chord).',+ advice: 'Fills the chord under Mid Harmony I. Sustain and move by step; do not chase the melody.',},{- id: 'high-harmony-1',- label: 'High Harmony I',+ id: 'mid-harmony-1',+ label: 'Mid Harmony I',role: 'harmony',- register: 'high',+ order: 3,+ range: 'D3–G4',derivable: true,- interval: 'A third above the melody — the first upper harmony.',- advice: 'Bright and close over the tune. Keep it locked to the melody contour.',+ voicing: 'The main moving inner voice — a third/sixth below the melody but landing on chord tones.',+ advice: 'The richest harmony. Move smoothly, favour common tones between chords, hold on a chord tone when the melody passes through a non-chord note.',},{id: 'high-harmony-2',label: 'High Harmony II',role: 'harmony',- register: 'high',+ order: 4,+ range: 'G3–B4',+ derivable: true,+ voicing: 'Sustained upper chord tone with gentle suspensions — carries the leading tone (the F# on D7) that pulls back to G.',+ advice: 'A held pad above the inner voices. Keep the dominant-7 third (F# under D7) — it resolves up to the tonic.',+ },+ {+ id: 'high-harmony-1',+ label: 'High Harmony I',+ role: 'harmony',+ order: 5,+ range: 'B3–E5',derivable: true,- interval: 'A fifth or sixth above the melody — the top of the stack.',- advice: 'The descant that crowns the chord. Save it for last; it exposes any tuning slip.',+ voicing: 'Sparse top descant — mostly sustained high chord tones, entering on the emotional phrases.',+ advice: 'The shimmer on top. Save it for the climaxes; rest through the opening and enter late, mostly long notes.',},];// The parts the AI derive tool generates from the base melody (everything except-// the melody itself, which is the input). Declaration order is low→high register.+// the melody itself, which is the input). Declaration order is low→high.export const DERIVABLE_HARMONY_PARTS = HARMONY_PARTS.filter((p) => p.derivable);// Human-readable label for a harmony-part id; empty string for an unknown id so// a custom/free-text part falls back to its own stored label at the call site.export const harmonyPartLabel = (id) => HARMONY_PARTS.find((p) => p.id === id)?.label || '';-// Sort key for a part role/register so the View-tab switcher lists low→high-// (bass, mids, highs). Unknown roles sort last, after the known set.-const REGISTER_ORDER = { low: 0, mid: 1, high: 2 };+// Sort key so the View-tab switcher lists the stack low→high (Bass, Mid II, Mid+// I, High II, High I). A scorePart stores the HARMONY_PARTS id in its `role`+// field, so match on id first, then the generic role; unknown ⇒ after the set.export const harmonyPartOrder = (roleOrId) => {- const part = HARMONY_PARTS.find((p) => p.id === roleOrId || p.role === roleOrId);- return part ? REGISTER_ORDER[part.register] ?? 3 : 3;+ const part = HARMONY_PARTS.find((p) => p.id === roleOrId) || HARMONY_PARTS.find((p) => p.role === roleOrId);+ return part ? part.order : 99;};// --- Learning steps --------------------------------------------------------diff --git a/client/src/lib/songCraft.test.js b/client/src/lib/songCraft.test.jsindex 7446d21257..4173345da1 100644--- a/client/src/lib/songCraft.test.js+++ b/client/src/lib/songCraft.test.js@@ -78,25 +78,30 @@ describe('songCraft reference data', () => {expect(solfegeForDegree('x')).toBeNull();});- it('every harmony part carries id, label, role, register, derivable flag and interval', () => {+ it('every harmony part carries id, label, role, numeric order, range, derivable flag and voicing', () => {const ids = new Set();- const registers = new Set(['low', 'mid', 'high']);for (const p of HARMONY_PARTS) {expect(typeof p.id).toBe('string');expect(ids.has(p.id)).toBe(false); // ids uniqueids.add(p.id);expect(typeof p.label).toBe('string');expect(typeof p.role).toBe('string');- expect(registers.has(p.register)).toBe(true);+ expect(typeof p.order).toBe('number');+ expect(typeof p.range).toBe('string');expect(typeof p.derivable).toBe('boolean');- expect(typeof p.interval).toBe('string');+ expect(typeof p.voicing).toBe('string');}- // The melody is the base (not derivable); the rest are.- expect(HARMONY_PARTS.find((p) => p.id === 'melody').derivable).toBe(false);+ // The melody is the base (not derivable, order 0); the rest are derivable.+ const melody = HARMONY_PARTS.find((p) => p.id === 'melody');+ expect(melody.derivable).toBe(false);+ expect(melody.order).toBe(0);expect(DERIVABLE_HARMONY_PARTS.every((p) => p.derivable)).toBe(true);+ // Declaration order is the low→high stack from the guide.expect(DERIVABLE_HARMONY_PARTS.map((p) => p.id)).toEqual([- 'bass', 'mid-harmony-1', 'mid-harmony-2', 'high-harmony-1', 'high-harmony-2',+ 'bass', 'mid-harmony-2', 'mid-harmony-1', 'high-harmony-2', 'high-harmony-1',]);+ // High Harmony I is the TOP voice (above High Harmony II) — guide ordering.+ expect(harmonyPartOrder('high-harmony-1')).toBeGreaterThan(harmonyPartOrder('high-harmony-2'));});it('harmonyPartLabel resolves known ids and empties unknown', () => {@@ -105,11 +110,11 @@ describe('songCraft reference data', () => {expect(harmonyPartLabel('nope')).toBe('');});- it('harmonyPartOrder sorts low→high and pushes unknown roles last', () => {- expect(harmonyPartOrder('bass')).toBeLessThan(harmonyPartOrder('mid-harmony-1'));- expect(harmonyPartOrder('mid-harmony-1')).toBeLessThan(harmonyPartOrder('high-harmony-1'));- expect(harmonyPartOrder('custom-unknown')).toBe(3);- // Resolves by role too (harmony parts share the 'harmony' role).- expect(harmonyPartOrder('harmony')).toBeLessThanOrEqual(3);+ it('harmonyPartOrder lays the stack low→high and pushes unknown ids last', () => {+ const order = ['bass', 'mid-harmony-2', 'mid-harmony-1', 'high-harmony-2', 'high-harmony-1'].map(harmonyPartOrder);+ // Strictly ascending.+ expect(order).toEqual([...order].sort((a, b) => a - b));+ expect(new Set(order).size).toBe(order.length); // all distinct+ expect(harmonyPartOrder('custom-unknown')).toBe(99);});});diff --git a/scripts/migrations/076-seed-500-miles-harmony-parts.js b/scripts/migrations/076-seed-500-miles-harmony-parts.jsnew file mode 100644index 0000000000..85ebdcd313--- /dev/null+++ b/scripts/migrations/076-seed-500-miles-harmony-parts.js@@ -0,0 +1,69 @@+/**+ * Backfill the worked-example harmony stack (Bass, Mid Harmony I/II, High Harmony+ * I/II) onto the built-in "500 Miles" for installs that already have the song but+ * no sheet-music parts.+ *+ * Background:+ * `server/services/songs.js#SEED_SONGS` now ships "500 Miles" with a full+ * chord-tone harmony stack (SEED_500_MILES_SCORE_PARTS) as the worked example+ * for the AI-derive feature. Fresh installs seed it directly. An install that+ * already persisted `data/songs.json` keeps its existing `seed-500-miles`+ * record — which has no `scoreParts` (or its own).+ *+ * This migration adds the shipped parts ONLY when the record has none, so a+ * user who already derived or hand-wrote their own parts is never clobbered.+ * The parts come from the single shipped source (no drift). The user can also+ * pull the latest bundled content any time via "Refresh from template".+ *+ * Fresh installs (no file) are a clean no-op. Re-runs detect parts are present+ * and skip.+ */++import { readFile, writeFile, stat } from 'fs/promises';+import { join } from 'path';+import { SEED_500_MILES_SCORE_PARTS } from '../../server/services/songs.js';++const SONG_ID = 'seed-500-miles';++const fileExists = (path) => stat(path).then(() => true, (err) => {+ if (err.code === 'ENOENT') return false;+ throw err;+});++export default {+ async up({ rootDir }) {+ const path = join(rootDir, 'data', 'songs.json');+ if (!(await fileExists(path))) {+ console.log('📦 migration 076: no data/songs.json — fresh install seeds the harmony parts directly.');+ return { updated: 0, reason: 'no-file' };+ }++ const raw = await readFile(path, 'utf-8');+ let doc;+ try { doc = JSON.parse(raw); } catch (err) {+ console.warn(`⚠️ migration 076: data/songs.json is unparseable (${err.message}); skipping.`);+ return { updated: 0, reason: 'unreadable' };+ }+ if (!doc || !Array.isArray(doc.songs)) {+ return { updated: 0, reason: 'unexpected-shape' };+ }++ const song = doc.songs.find((s) => s && s.id === SONG_ID);+ if (!song) {+ console.log('📦 migration 076: built-in 500 Miles not present; nothing to backfill.');+ return { updated: 0, reason: 'song-absent' };+ }+ if (Array.isArray(song.scoreParts) && song.scoreParts.length > 0) {+ console.log('📦 migration 076: 500 Miles already has sheet-music parts; leaving them untouched.');+ return { updated: 0, reason: 'already-applied' };+ }++ // Deep-clone the shipped parts so the persisted record can't share references+ // with the in-memory seed (defensive — the seed is reused across reads).+ song.scoreParts = SEED_500_MILES_SCORE_PARTS.map((p) => ({ ...p }));+ song.updatedAt = new Date().toISOString();+ await writeFile(path, JSON.stringify(doc, null, 2) + '\n');+ console.log(`📦 migration 076: seeded ${song.scoreParts.length} harmony parts onto built-in 500 Miles.`);+ return { updated: 1 };+ },+};diff --git a/scripts/migrations/076-seed-500-miles-harmony-parts.test.js b/scripts/migrations/076-seed-500-miles-harmony-parts.test.jsnew file mode 100644index 0000000000..20e639e5d5--- /dev/null+++ b/scripts/migrations/076-seed-500-miles-harmony-parts.test.js@@ -0,0 +1,99 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './076-seed-500-miles-harmony-parts.js';+import { SEED_500_MILES_SCORE_PARTS, SEED_SONGS } from '../../server/services/songs.js';+import { parseScore } from '../../client/src/lib/scoreNotation.js';++const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));+const findSong = (path, id) => readJson(path).songs.find((s) => s.id === id);++describe('migration 076 — seed 500 Miles harmony parts', () => {+ let rootDir;+ let songsPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-076-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ songsPath = join(rootDir, 'data', 'songs.json');+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('the seed song carries the five shipped harmony parts (single source)', () => {+ const seed = SEED_SONGS.find((s) => s.id === 'seed-500-miles');+ expect(seed.scoreParts).toBe(SEED_500_MILES_SCORE_PARTS);+ expect(SEED_500_MILES_SCORE_PARTS.map((p) => p.role)).toEqual([+ 'bass', 'mid-harmony-2', 'mid-harmony-1', 'high-harmony-2', 'high-harmony-1',+ ]);+ });++ it('every shipped part parses cleanly to eight 4-beat bars', () => {+ for (const part of SEED_500_MILES_SCORE_PARTS) {+ const parsed = parseScore(part.score);+ expect(parsed.errors).toEqual([]);+ expect(parsed.measures).toHaveLength(8);+ for (const m of parsed.measures) expect(m.beats).toBe(4);+ }+ // High Harmony I rests through the opening (sparse, late entrance).+ const highI = SEED_500_MILES_SCORE_PARTS.find((p) => p.role === 'high-harmony-1');+ const parsed = parseScore(highI.score);+ expect(parsed.measures.slice(0, 4).every((m) => m.notes.every((n) => n.rest))).toBe(true);+ // High Harmony II carries the F# leading tone on the D7 bar (bar 6).+ const highII = parseScore(SEED_500_MILES_SCORE_PARTS.find((p) => p.role === 'high-harmony-2').score);+ expect(highII.measures[5].notes.some((n) => n.pitch?.letter === 'F' && n.pitch?.accidental === '#')).toBe(true);+ });++ it('no-ops when data/songs.json is missing (fresh install seeds parts directly)', async () => {+ const result = await migration.up({ rootDir });+ expect(result).toEqual({ updated: 0, reason: 'no-file' });+ expect(existsSync(songsPath)).toBe(false);+ });++ it('backfills parts onto a 500 Miles record that has none', async () => {+ writeJson(songsPath, { songs: [{ id: 'seed-500-miles', title: '500 Miles' }] });+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(1);+ const song = findSong(songsPath, 'seed-500-miles');+ expect(song.scoreParts).toHaveLength(5);+ expect(song.scoreParts.map((p) => p.role)).toEqual(SEED_500_MILES_SCORE_PARTS.map((p) => p.role));+ });++ it('treats an empty scoreParts array as missing and fills it', async () => {+ writeJson(songsPath, { songs: [{ id: 'seed-500-miles', scoreParts: [] }] });+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(1);+ expect(findSong(songsPath, 'seed-500-miles').scoreParts).toHaveLength(5);+ });++ it('never clobbers existing user/AI-derived parts', async () => {+ writeJson(songsPath, { songs: [{ id: 'seed-500-miles', scoreParts: [{ id: 'mine', label: 'Mine', role: 'bass', score: '| G2w |' }] }] });+ const result = await migration.up({ rootDir });+ expect(result).toEqual({ updated: 0, reason: 'already-applied' });+ expect(findSong(songsPath, 'seed-500-miles').scoreParts).toEqual([{ id: 'mine', label: 'Mine', role: 'bass', score: '| G2w |' }]);+ });++ it('is idempotent across re-runs', async () => {+ writeJson(songsPath, { songs: [{ id: 'seed-500-miles' }] });+ await migration.up({ rootDir });+ const second = await migration.up({ rootDir });+ expect(second.reason).toBe('already-applied');+ });++ it('no-ops when 500 Miles is absent (user deleted it)', async () => {+ writeJson(songsPath, { songs: [{ id: 'song-custom' }] });+ const result = await migration.up({ rootDir });+ expect(result).toEqual({ updated: 0, reason: 'song-absent' });+ });++ it('skips an unparseable songs.json instead of throwing', async () => {+ writeFileSync(songsPath, '{ not json');+ const result = await migration.up({ rootDir });+ expect(result).toEqual({ updated: 0, reason: 'unreadable' });+ });+});diff --git a/server/lib/songCraftRef.js b/server/lib/songCraftRef.jsindex 3da1358591..a43938885a 100644--- a/server/lib/songCraftRef.js+++ b/server/lib/songCraftRef.js@@ -42,19 +42,23 @@ export const VOICE_LAYERS = [// The dirge-family shapes (the lament the workbench centers on), in order.export const DIRGE_RHYTHM_SHAPES = RHYTHM_SHAPES.filter((s) => s.dirge);-// Sheet-music harmony parts: { id, label, role, register, derivable, interval }.-// The base score is the `melody`; the derivable parts are what the AI derive-// tool produces from it. Injected into the derive prompt so the model returns-// part ids the editor's switcher already understands. Mirrors HARMONY_PARTS in-// client/src/lib/songCraft.js — keep id/label/role/register/interval in sync.+// Sheet-music harmony parts: { id, label, role, order, range, derivable, voicing }.+// The base score is the `melody`; the derivable parts are what the AI derive tool+// produces from it. The voicing model is CHORD-TONE (each voice targets a chord+// tone and moves smoothly), NOT parallel-interval tracking of the melody — see+// client/src/lib/songCraft.js for the full rationale. Injected into the derive+// prompt so the model voices each part correctly and returns ids the editor's+// switcher understands. Mirrors HARMONY_PARTS in songCraft.js — keep+// id/label/role/order/range/voicing in sync.export const HARMONY_PARTS = [- { id: 'melody', label: 'Melody', role: 'melody', register: 'mid', derivable: false, interval: 'The tune itself — the base every harmony is built from.' },- { id: 'bass', label: 'Bass', role: 'bass', register: 'low', derivable: true, interval: 'Chord roots, low — the harmonic floor, often an octave or more below the melody.' },- { id: 'mid-harmony-1', label: 'Mid Harmony I', role: 'harmony', register: 'mid', derivable: true, interval: 'A third below the melody — the closest inner harmony.' },- { id: 'mid-harmony-2', label: 'Mid Harmony II', role: 'harmony', register: 'mid', derivable: true, interval: 'A sixth below the melody (a different chord tone from Mid Harmony I).' },- { id: 'high-harmony-1', label: 'High Harmony I', role: 'harmony', register: 'high', derivable: true, interval: 'A third above the melody — the first upper harmony.' },- { id: 'high-harmony-2', label: 'High Harmony II', role: 'harmony', register: 'high', derivable: true, interval: 'A fifth or sixth above the melody — the top of the stack.' },+ { id: 'melody', label: 'Melody', role: 'melody', order: 0, range: 'as written', derivable: false, voicing: 'The lead — carries the lyric and rhythmic detail. The base every harmony targets.' },+ { id: 'bass', label: 'Bass', role: 'bass', order: 1, range: 'G2–D3 (down to E2)', derivable: true, voicing: 'Root of each chord, with the fifth as gentle movement — a hymn-like root–fifth–root drone.' },+ { id: 'mid-harmony-2', label: 'Mid Harmony II', role: 'harmony', order: 2, range: 'B2–E4', derivable: true, voicing: 'Low inner pad — sustained chord tones below the melody (often the 3rd or 5th of the chord).' },+ { id: 'mid-harmony-1', label: 'Mid Harmony I', role: 'harmony', order: 3, range: 'D3–G4', derivable: true, voicing: 'The main moving inner voice — a third/sixth below the melody but landing on chord tones.' },+ { id: 'high-harmony-2', label: 'High Harmony II', role: 'harmony', order: 4, range: 'G3–B4', derivable: true, voicing: 'Sustained upper chord tone with gentle suspensions — carries the leading tone (the F# on D7) that pulls back to G.' },+ { id: 'high-harmony-1', label: 'High Harmony I', role: 'harmony', order: 5, range: 'B3–E5', derivable: true, voicing: 'Sparse top descant — mostly sustained high chord tones, entering on the emotional phrases.' },];-// The parts the derive tool generates (all but the melody, which is the input).+// The parts the derive tool generates (all but the melody, which is the input),+// declaration order low→high.export const DERIVABLE_HARMONY_PARTS = HARMONY_PARTS.filter((p) => p.derivable);diff --git a/server/services/songs.js b/server/services/songs.jsindex 2d623825ac..42e4b0b2f7 100644--- a/server/services/songs.js+++ b/server/services/songs.js@@ -218,6 +218,87 @@ export const sanitizeSong = (raw) => {};};+// Worked-example harmony stack for the built-in "500 Miles" — the chord-tone+// voicing the AI-derive feature is meant to produce (the song the user pointed+// at as the first experiment). Each part is a complete lead-sheet score in the+// PortOS DSL, voiced from the chord-tone map (NOT parallel intervals): a+// hymn-like root–fifth bass, two sustained inner pads, a sustained upper pad+// that carries the F#→G leading tone on D7, and a sparse top descant that enters+// late. Kept as a named export so SEED_SONGS and migration 076 share ONE source+// (no drift). Voicing roles/ranges mirror songCraft.js HARMONY_PARTS.+export const SEED_500_MILES_SCORE_PARTS = [+ {+ id: 'part-500-bass', label: 'Bass', role: 'bass',+ score: [+ 'clef: bass', 'key: G', 'time: 4/4', 'tempo: 68', '',+ '| rh [G] G2h(you) |',+ '| [G] G2h(miss) D3h(train) |',+ '| [Em] E2h(on) B2h(will) |',+ '| [C] C3h(know) G2h(am) |',+ '| [Am7] A2h(gone) E3h(can) |',+ '| [D7] D3h(hear) A2h(tle) |',+ '| [G] G2h(blow) D3h(dred) |',+ '| [G] G2w(miles) |',+ ].join('\n'),+ },+ {+ id: 'part-500-mid-2', label: 'Mid Harmony II', role: 'mid-harmony-2',+ score: [+ 'clef: treble', 'key: G', 'time: 4/4', 'tempo: 68', '',+ '| rw |',+ '| [G] B3w(miss) |',+ '| [Em] B3w(on) |',+ '| [C] G3w(know) |',+ '| [Am7] G3w(gone) |',+ '| [D7] A3w(hear) |',+ '| [G] B3w(blow) |',+ '| [G] G3w(miles) |',+ ].join('\n'),+ },+ {+ id: 'part-500-mid-1', label: 'Mid Harmony I', role: 'mid-harmony-1',+ score: [+ 'clef: treble', 'key: G', 'time: 4/4', 'tempo: 68', '',+ '| rw |',+ '| [G] D4w(miss) |',+ '| [Em] E4w(on) |',+ '| [C] E4w(know) |',+ '| [Am7] E4w(gone) |',+ '| [D7] C4w(hear) |',+ '| [G] D4w(blow) |',+ '| [G] D4w(miles) |',+ ].join('\n'),+ },+ {+ id: 'part-500-high-2', label: 'High Harmony II', role: 'high-harmony-2',+ score: [+ 'clef: treble', 'key: G', 'time: 4/4', 'tempo: 68', '',+ '| rw |',+ '| [G] G4w(miss) |',+ '| [Em] G4w(on) |',+ '| [C] E4w(know) |',+ '| [Am7] E4w(gone) |',+ '| [D7] F#4w(hear) |',+ '| [G] G4w(blow) |',+ '| [G] G4w(miles) |',+ ].join('\n'),+ },+ {+ id: 'part-500-high-1', label: 'High Harmony I', role: 'high-harmony-1',+ score: [+ 'clef: treble', 'key: G', 'time: 4/4', 'tempo: 68', '',+ '| rw |',+ '| rw |',+ '| rw |',+ '| rw |',+ '| [Am7] G4w(gone) |',+ '| [D7] A4w(hear) |',+ '| [G] B4w(blow) |',+ '| [G] B4w(miles) |',+ ].join('\n'),+ },+];+// Seeded on first read so a fresh install opens on a worked example — the song// the feature was designed around. Mirrors the dirge `slow-4-4` rhythm shape// and the foundation-first layer ladder from songCraft.js.@@ -250,6 +331,9 @@ export const SEED_SONGS = ['| [G] G4h(blow) A4e(a) B4e(hun-) C5q(dred) |','| [G] D5w(miles) |',].join('\n'),+ // A full chord-tone harmony stack (bass + two mid pads + two high pads),+ // the worked example for the AI-derive feature. See SEED_500_MILES_SCORE_PARTS.+ scoreParts: SEED_500_MILES_SCORE_PARTS,notes: 'A travelling lament — keep it spacious and mournful. Sustain the vowels on the downbeats. Works beautifully with a soft hummed drone under the verses.',learned: false,sections: [diff --git a/server/services/songsAI.js b/server/services/songsAI.jsindex 78a43c1368..53bc5ee8bc 100644--- a/server/services/songsAI.js+++ b/server/services/songsAI.js@@ -246,9 +246,14 @@ const LEAD_SHEET_SPEC = `PortOS lead-sheet notation:- Rest = "r" + duration (rq, rh) — no pitch, no lyric.- [chord] draws a chord symbol above; (lyric) draws a syllable beneath (trailing "-" = held syllable).`;-// The "parts to write" block — id + interval rule for each requested part.+// The "parts to write" block — id + range + voicing rule for each requested+// part, low→high so the model builds the stack in order.const partsBrief = (parts) =>- parts.map((p) => `- ${p.id} ("${p.label}", ${p.register} register): ${p.interval}`).join('\n');+ parts+ .slice()+ .sort((a, b) => (a.order ?? 99) - (b.order ?? 99))+ .map((p) => `- ${p.id} ("${p.label}", range ${p.range}): ${p.voicing}`)+ .join('\n');const isDerivedPartsShape = (o) =>o && typeof o === 'object' && Array.isArray(o.parts);@@ -256,7 +261,7 @@ const isDerivedPartsShape = (o) =>const buildDerivePrompt = ({ song, parts }) => {const key = clean(song.key) || 'C major';const baseScore = clean(song.score);- return `You are an a cappella arranger. Given a base MELODY in PortOS lead-sheet notation, write singable HARMONY parts that stack with it when sung together.+ return `You are an a cappella arranger building a layered folk vocal stack (think a sparse, TikTok-style harmony build, NOT a dense chorale). Given a base MELODY in PortOS lead-sheet notation, write singable HARMONY parts that stack with it.# Format (the melody below uses it; your output must too)${LEAD_SHEET_SPEC}@@ -264,15 +269,22 @@ ${LEAD_SHEET_SPEC}# Base melody — key: ${key}${baseScore}-# Parts to write+# Parts to write (low → high)${partsBrief(parts)}-# Rules-- Mirror the melody MEASURE-FOR-MEASURE: same number of bars, same note durations and the SAME lyric syllable on each note, so every part lines up rhythmically with the melody and the others.-- Choose each pitch to be consonant with the chord symbol attached to the corresponding melody note ([G], [Em], [C] …) AND to sit at the requested interval/register relative to the melody. "Below" parts must stay below the melody; "above" parts above it; never cross it.-- Keep the same key signature as the melody. Use "clef: bass" for the Bass part and "clef: treble" for the others. Keep the same time and tempo headers.-- Keep every part within a comfortable singing range for its register (Bass roughly G2–C4; mid roughly G3–C5; high roughly C4–G5).-- Carry the chord symbols ([G] …) through on the same notes as the melody so the part is readable on its own.+# How to voice each part — CHORD-TONE, not parallel+- For each chord symbol ([G], [Em], [C], [Am7], [D7] …), spell its chord tones, then give each voice a chord tone from that chord, picking the octave that fits the voice's range. This vertical chord-tone map is the goal — NOT tracking the melody a fixed interval away.+- DO NOT move every voice in parallel with the melody. Parallel 3rds/6ths under every syllable sound like a MIDI choir. Instead: favour COMMON TONES held across a chord change, and move by the smallest step when the chord changes (smooth voice leading).+- SUSTAIN. A harmony voice should usually hold one chord tone per chord (whole/half notes) rather than singing every melodic syllable. It does NOT need the melody's rhythm or every lyric — use long notes and rests.+- When the melody passes through a non-chord (passing) tone, HOLD the harmony on the nearest stable chord tone; don't chase the passing note.+- Preserve leading tones: the third of a dominant-7 chord (e.g. F# under D7 in the key of G) MUST stay — it pulls up to the tonic. Never flatten it to a modal sound.+- Stagger entrances. Lower/inner voices can enter after the opening; the top descant ("high-harmony-1") should be SPARSE — rest through the opening bars (use whole rests \`rw\`) and enter only on the later, emotional phrases. The bass and inner pads carry the body.+- Keep each voice within its stated range, and keep the lower voices below the melody, the upper voices above the inner ones.++# Output rules+- Same number of measures as the melody, same key signature, same time and tempo headers. Use "clef: bass" for the bass part and "clef: treble" for the others.+- Carry the chord symbols ([G] …) on each part's downbeats so it is readable on its own.+- Lyrics are optional on harmony parts — a sustained note can carry the bar's lead word (or none). Do not force a syllable onto every note.# Output contractReturn ONLY a JSON object (no prose, no markdown fence):