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

songs: layered multi-part MIDI player, unified take-type vocabulary, full 500 Miles melody

[._.]/ Adam Eivyfdcc4362522b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 949d90bf49..5dc1487eb0 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -20,6 +20,9 @@
## Changed
+- **Songs: play any combination of sheet-music parts together** — the read/perform view's Sheet music card now has a layered MIDI player. When a song carries harmony parts beyond the melody, a checkbox per part (**Layers: Melody, Bass, Mid Harmony I/II, High Harmony I/II…**) lets you pick any combination — melody + bass, the whole stack, two inner harmonies on their own — and a single **Play parts** transport synthesizes them all together, sample-aligned on one audio clock (Web Audio oscillators, no MIDI.js / Tone.js), with the master level backing off as voices stack so the blend doesn't clip. All parts are checked by default, so Play gives the full harmony stack out of the box. A **Tempo** field controls playback for the whole stack, and the pill row still picks which staff is *shown* independently of what plays — the moving playhead lights up on the shown staff whenever it's one of the sounding parts. A single-part song keeps the simple per-staff reference-tone player.
+- **Songs: recording "take types" now match the harmony stack you generate** — the voice-layer vocabulary used for vocal takes (the "Next take is for layer" picker, the per-take layer dropdown, the "Add layer from ladder" presets, and the Learning Guide ladder) was the old folk set (Lead melody, Bass / root, Harmony third/fifth, Drone, Counter-melody, Vocal percussion) — out of step with the **Melody, Bass, Mid Harmony I/II, High Harmony I/II** stack the AI derive tool actually writes. The two vocabularies are now unified: a recorded take's layer lines up by id and label with the notated part of the same name, so you can record yourself singing each generated part and stack them. A test guards the two lists against drifting apart again. Existing songs keep their stored layers; "Refresh from template" pulls the new set onto built-in songs.
+- **Songs: the built-in "500 Miles" ships the full song, not just verse 1** — the bundled sheet-music melody now spans every verse and the closing coda (46 bars) instead of only the first verse, so the Sheet music view shows the whole song. Existing installs that still hold the earlier single-verse (or the original C-major placeholder) melody can pull it via the song's "Refresh from template" button; the per-section harmony parts can be regenerated to match with "Derive with AI" (it now reads the full melody).
- **Songs: the practice tools now lead the View tab** — the sheet music, metronome, and vocal recorder are grouped at the top of a song's performance view (just under the meta line and round-stack toggle), instead of the recorder sitting at the very bottom below the lyrics and references. So when you open a song to play it, you read the chart, set the tempo, and record against it without scrolling — the lyrics and reference videos follow underneath.
- **Universe Builder now stores universes in PostgreSQL** — your universes (canon bibles, categories, composite sheets, locks, influences, and the per-universe render-run history) moved out of the per-record `data/universes/{id}/index.json` files into dedicated `universes` and `universe_runs` tables, one row per universe. Existing installs are migrated automatically and losslessly on first boot — the legacy `data/universes/` directory is renamed aside (`data/universes.imported`) as a one-release recovery source. Nothing changes in how you create, edit, delete, render, or sync universes: the Universe Builder UI and the cross-machine federation wire format are unchanged (no schema-version bump — the sync payload is storage-independent, so a machine on this version syncs universes cleanly with a peer still on the old file storage). This is the first implementation slice (#1014) of the Create relational-schema migration designed in #999. Universes still persist to the per-record file store under the `MEMORY_BACKEND=file` dev/test escape hatch.
- **Pipeline series & issues now store in PostgreSQL** — your comic/TV series and their issues (the 8-stage production pipeline state: idea, prose, comic script, teleplay, comic pages, storyboards, episode video, audio) moved out of the per-record `data/pipeline-series/{id}/index.json` and `data/pipeline-issues/{id}/index.json` files into dedicated `pipeline_series` and `pipeline_issues` tables, one row per record. The hot relationships are promoted to indexed columns — `pipeline_issues (series_id, number)` directly serves the issue-renumber pass (the most common cross-record pipeline query), and `pipeline_series (universe_id)` serves the universe delete-guard and "series in this universe" lists. Existing installs are migrated automatically and losslessly on first boot. Each issue's full stage map (including its `lastRunId` transcript pointers) stays in the row's `data` payload, and the "Finish the draft" manuscript-review sibling document stays a file alongside the series — only the series/issue records themselves moved. Nothing changes in how you create, edit, delete, renumber, run, or sync the pipeline: the UI and the cross-machine federation wire format are unchanged (no schema-version bump — the sync payload is storage-independent, so a machine on this version syncs the pipeline cleanly with a peer still on the old file storage). This is the second implementation slice (#1015) of the Create relational-schema migration designed in #999, building on the Universes slice (#1014). The pipeline still persists to the per-record file store under the `MEMORY_BACKEND=file` dev/test escape hatch.
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 9c814277c1..c310153dea 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -91,7 +91,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `universeBuilderExpand.js` | `mergeExpandIntoDraft(draft, result)` — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with `kind` precedence, canon dedupe by name/slugline/alias). Also exports `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` for callers that need the building blocks (per-category Generate, save-time refetch+merge). |
| `metronome.js` | Sample-accurate Web Audio metronome — the shared timing grid for the song system and first consumer of the song `tempo` field. `createMetronome({ bpm, beatsPerBar, countInBars, onBeat, onCountInComplete })` lookahead-schedules accented click tones on the shared `AudioContext` clock (same pattern as `songPlayback.js`), emits `{ beat, bar, accent, countIn, whenAudioTime }` per beat (the beat-clock callback color-match/sing-to-score subscribe to), and tears down all timers on `stop()`. Plus `clampBpm` (20–320), `secondsPerBeat`, `timeSignatureFromScore`, `beatDescriptor`. |
| `scoreNotation.js` | Parser for the PortOS lead-sheet notation — a dependency-free text format for melody + chords + lyrics that the `<ScoreSheet>` SVG renderer draws (no abcjs / VexFlow / OSMD). `parseScore(text)` → `{ clef, key, keySig, time, tempo, measures, errors }`; plus `parsePitch`, `diatonicStep`, `durationBeats`, `keySignature`, `DURATIONS`, and `scoreHasMusic(text)`. Forgiving: bad tokens collect into `errors` and are skipped, never thrown. Pure — the renderer only does geometry. |
-| `scorePlayback.js` | Melody synth playback for the lead-sheet notation — companion to `songPlayback.js` (which stacks recorded vocal takes), this synthesizes the WRITTEN melody as soft `OscillatorNode` reference tones on a lazy shared `AudioContext` (no MIDI.js / Tone.js). `buildSchedule(score, bpm?)` is the pure notes→`{ freq, startSec, durSec }` mapping (A4=440, quarter-beat = `(60/bpm)·(beatValue/4)` so it honors the time signature); `noteToFrequency`/`midiToFreq`/`pitchToMidi` convert pitches; `createScorePlayer(score, { bpm, onNote, onEnded })` plays/pauses/stops with a lookahead scheduler and emits the now-sounding note index for the `<ScoreSheet>` playhead. |
+| `scorePlayback.js` | Melody synth playback for the lead-sheet notation — companion to `songPlayback.js` (which stacks recorded vocal takes), this synthesizes the WRITTEN melody as soft `OscillatorNode` reference tones on a lazy shared `AudioContext` (no MIDI.js / Tone.js). `buildSchedule(score, bpm?)` is the pure notes→`{ freq, startSec, durSec }` mapping (A4=440, quarter-beat = `(60/bpm)·(beatValue/4)` so it honors the time signature); `noteToFrequency`/`midiToFreq`/`pitchToMidi` convert pitches; `createScorePlayer(score, { bpm, onNote, onEnded })` plays/pauses/stops with a lookahead scheduler and emits the now-sounding note index for the `<ScoreSheet>` playhead; `createMultiScorePlayer(parts, { bpm, onNote, onEnded })` synthesizes several parts (melody + checked harmony) together on one master bus (level backs off as voices stack) with a per-part `onNote(partId, index)` playhead. |
| `songCraft.js` | Canonical a cappella song-craft reference data rendered by the Songs Guide (`/songs/guide`) and reused by the Song editor: `RHYTHM_SHAPES` / `DIRGE_RHYTHM_SHAPES` (dirge & ballad pulse feels with BPM bands), `VOICE_LAYERS` (foundation-first harmony build ladder), `LEARNING_STEPS` (practice sequence), `NOTATION_HELP` (lead-sheet/notation primers), `SOLFEGE_DEGREES` + `solfegeForDegree(n)`, and `rhythmShapeLabel(id)` (human-readable "Slow 4/4 ballad · dirge (56–76 BPM)" label shared by the editor's picker and read view). Pure data; pickers and docs read the same source so they can't drift. |
| `songPlayback.js` | `createLayeredPlayer(takes)` — decode N recorded vocal takes and start them together on one shared `AudioContext` so they stack into a layered a cappella performance (sample-aligned, per-layer mute). Used by the Song editor's recording mixer. |
| `wrSceneCursor.js` | Resolve which script scene the editor caret sits in (`sceneAtCursor`, `sceneAnchorIndex`) — inverse of WorkEditor's jump-to-scene text search; drives the live render preview's "scene at cursor" target. |
diff --git a/client/src/lib/scorePlayback.js b/client/src/lib/scorePlayback.js
index c894ad5676..b528ae24c7 100644
--- a/client/src/lib/scorePlayback.js
+++ b/client/src/lib/scorePlayback.js
@@ -103,6 +103,33 @@ const safeCall = (cb, ...args) => {
const LEAD = 0.08; // seconds of lead-in before beat 0 sounds
const LOOKAHEAD_MS = 25; // how often the scheduler wakes
const SCHEDULE_AHEAD = 0.12; // seconds of audio scheduled past "now"
+const TONE_PEAK = 0.18; // per-voice gain peak for a single sounding tone
+
+// Schedule one tone with a short attack/release gain envelope so it doesn't
+// click. Triangle wave reads as a soft reference tone. Routed into `destination`
+// (the context output for the solo player; a per-part gain → master bus for the
+// multi-part player). Returns the live { osc, gain } so the caller can track it
+// for teardown. Pure of any module state — both players share it.
+const scheduleTone = (c, freq, startAt, durSec, destination, peak = TONE_PEAK) => {
+ const osc = c.createOscillator();
+ const gain = c.createGain();
+ osc.type = 'triangle';
+ osc.frequency.setValueAtTime(freq, startAt);
+
+ const attack = Math.min(0.012, durSec * 0.25);
+ const release = Math.min(0.07, durSec * 0.4);
+ const end = startAt + durSec;
+ const sustainEnd = Math.max(startAt + attack, end - release);
+ gain.gain.setValueAtTime(0.0001, startAt);
+ gain.gain.exponentialRampToValueAtTime(peak, startAt + attack);
+ gain.gain.setValueAtTime(peak, sustainEnd);
+ gain.gain.exponentialRampToValueAtTime(0.0001, end);
+
+ osc.connect(gain).connect(destination);
+ osc.start(startAt);
+ osc.stop(end + 0.03);
+ return { osc, gain };
+};
/**
* Build a melody player over a parsed score.
@@ -142,30 +169,10 @@ export const createScorePlayer = (score, options = {}) => {
if (interval != null) { clearInterval(interval); interval = null; }
};
- // Schedule one tone with a short attack/release gain envelope so it doesn't
- // click. Triangle wave reads as a soft reference tone.
- const scheduleTone = (freq, startAt, durSec) => {
- const c = ctx();
- const osc = c.createOscillator();
- const gain = c.createGain();
- osc.type = 'triangle';
- osc.frequency.setValueAtTime(freq, startAt);
-
- const peak = 0.18;
- const attack = Math.min(0.012, durSec * 0.25);
- const release = Math.min(0.07, durSec * 0.4);
- const end = startAt + durSec;
- const sustainEnd = Math.max(startAt + attack, end - release);
- gain.gain.setValueAtTime(0.0001, startAt);
- gain.gain.exponentialRampToValueAtTime(peak, startAt + attack);
- gain.gain.setValueAtTime(peak, sustainEnd);
- gain.gain.exponentialRampToValueAtTime(0.0001, end);
-
- osc.connect(gain).connect(c.destination);
- osc.start(startAt);
- osc.stop(end + 0.03);
- const entry = { osc, gain };
- osc.onended = () => { nodes = nodes.filter((n) => n !== entry); };
+ // Hand one due tone to the audio clock and track it for teardown.
+ const playTone = (freq, startAt, durSec) => {
+ const entry = scheduleTone(ctx(), freq, startAt, durSec, ctx().destination);
+ entry.osc.onended = () => { nodes = nodes.filter((n) => n !== entry); };
nodes.push(entry);
};
@@ -179,7 +186,7 @@ export const createScorePlayer = (score, options = {}) => {
const ev = events[nextScheduleIdx];
const at = startTime + ev.startSec;
if (at > now + SCHEDULE_AHEAD) break;
- if (!ev.rest && ev.freq) scheduleTone(ev.freq, Math.max(at, now), ev.durSec);
+ if (!ev.rest && ev.freq) playTone(ev.freq, Math.max(at, now), ev.durSec);
nextScheduleIdx += 1;
}
@@ -271,3 +278,170 @@ export const createScorePlayer = (score, options = {}) => {
schedule: () => schedule,
};
};
+
+// Master gain for the multi-part bus: back the level off as more voices stack so
+// the summed triangle waves don't clip, while a lone voice still plays at the
+// same level as the solo player (1.0 for n=1, ~0.35 for a 4-part stack).
+const masterGainFor = (count) => Math.min(1, 1.4 / Math.max(1, count));
+
+/**
+ * Build a player that synthesizes MULTIPLE parts at once — the melody plus any
+ * checked harmony parts — so any combination of lead-sheet voices sounds
+ * together, sample-aligned on the one shared AudioContext. Each part is scheduled
+ * through its own gain into a shared master bus whose level backs off as more
+ * voices stack so the sum doesn't clip. The transport mirrors `createScorePlayer`
+ * (play / pause / stop / setTempo) but iterates every part each tick, and the
+ * playhead callback is per-part so a viewer can highlight the staff it's showing.
+ *
+ * @param {Array<{id:string, score:object}>} parts — parsed scores to play together.
+ * @param {object} [options]
+ * @param {number} [options.bpm] — tempo override applied to every part.
+ * @param {(partId:string, index:number|null)=>void} [options.onNote] — the
+ * now-sounding note index for a part (null for every part when playback ends).
+ * @param {()=>void} [options.onEnded] — called once when the longest part finishes.
+ * @returns {{ play, pause, stop, isPlaying, setTempo }}
+ */
+export const createMultiScorePlayer = (parts, options = {}) => {
+ const { onNote, onEnded } = options;
+ let bpm = Number.isFinite(options.bpm) && options.bpm > 0 ? options.bpm : null;
+
+ // A voice carries its part id, its schedule, and per-voice scheduler cursors.
+ const buildVoices = () => (parts || []).map((p) => ({
+ id: p.id,
+ schedule: buildSchedule(p.score, bpm),
+ nextScheduleIdx: 0,
+ nextNotifyIdx: 0,
+ lastNotified: -1,
+ }));
+
+ let voices = [];
+ let totalSec = 0; // longest voice (seconds) — cached, refreshed on rebuild
+ // Rebuild the voice schedules (and cache totalSec) — on init, on play, and on a
+ // tempo change while idle. Cheaper than reducing over voices every 25ms tick.
+ const rebuild = () => {
+ voices = buildVoices();
+ totalSec = voices.reduce((m, v) => Math.max(m, v.schedule.totalSec), 0);
+ };
+ rebuild();
+
+ let playing = false;
+ let interval = null;
+ let startTime = 0; // ctx time at which beat 0 plays
+ let offsetSec = 0; // resume position (seconds into the score)
+ let master = null; // shared bus GainNode (created per play)
+ let nodes = []; // live { osc, gain } across all voices, for teardown
+
+ const stopNodes = () => {
+ for (const n of nodes) {
+ n.osc.onended = null;
+ try { n.osc.stop(); } catch { /* already stopped */ }
+ }
+ nodes = [];
+ master = null;
+ };
+
+ const clearTick = () => {
+ if (interval != null) { clearInterval(interval); interval = null; }
+ };
+
+ const resetCursors = (offset = 0) => {
+ for (const v of voices) {
+ const events = v.schedule.events;
+ let idx = events.findIndex((e) => e.startSec + e.durSec > offset + 1e-6);
+ if (idx < 0) idx = events.length;
+ v.nextScheduleIdx = idx;
+ v.nextNotifyIdx = idx;
+ v.lastNotified = -1;
+ }
+ };
+
+ const playTone = (freq, startAt, durSec) => {
+ const entry = scheduleTone(ctx(), freq, startAt, durSec, master);
+ entry.osc.onended = () => { nodes = nodes.filter((n) => n !== entry); };
+ nodes.push(entry);
+ };
+
+ const tick = () => {
+ const now = ctx().currentTime;
+ for (const v of voices) {
+ const events = v.schedule.events;
+ while (v.nextScheduleIdx < events.length) {
+ const ev = events[v.nextScheduleIdx];
+ const at = startTime + ev.startSec;
+ if (at > now + SCHEDULE_AHEAD) break;
+ if (!ev.rest && ev.freq) playTone(ev.freq, Math.max(at, now), ev.durSec);
+ v.nextScheduleIdx += 1;
+ }
+
+ let newest = -1;
+ while (v.nextNotifyIdx < events.length && startTime + events[v.nextNotifyIdx].startSec <= now) {
+ newest = events[v.nextNotifyIdx].index;
+ v.nextNotifyIdx += 1;
+ }
+ if (newest >= 0 && newest !== v.lastNotified) {
+ v.lastNotified = newest;
+ safeCall(onNote, v.id, newest);
+ }
+ }
+
+ if (now - startTime >= totalSec) finish();
+ };
+
+ function finish() {
+ clearTick();
+ stopNodes();
+ playing = false;
+ offsetSec = 0;
+ resetCursors(0);
+ for (const v of voices) safeCall(onNote, v.id, null);
+ safeCall(onEnded);
+ }
+
+ const play = async () => {
+ if (playing) return;
+ const c = ctx();
+ if (c.state === 'suspended' && c.resume) await c.resume();
+ rebuild(); // pick up a tempo change made while idle
+ if (!totalSec) { safeCall(onEnded); return; }
+
+ master = c.createGain();
+ master.gain.setValueAtTime(masterGainFor(voices.length), c.currentTime);
+ master.connect(c.destination);
+
+ playing = true;
+ startTime = c.currentTime + LEAD - offsetSec;
+ resetCursors(offsetSec);
+ tick(); // schedule the immediate window now so playback starts promptly
+ interval = setInterval(tick, LOOKAHEAD_MS);
+ };
+
+ const pause = () => {
+ if (!playing) return;
+ offsetSec = Math.min(Math.max(0, ctx().currentTime - startTime), totalSec);
+ clearTick();
+ stopNodes();
+ playing = false;
+ };
+
+ const stop = () => {
+ clearTick();
+ stopNodes();
+ playing = false;
+ offsetSec = 0;
+ resetCursors(0);
+ for (const v of voices) safeCall(onNote, v.id, null);
+ };
+
+ const setTempo = (nextBpm) => {
+ bpm = Number.isFinite(nextBpm) && nextBpm > 0 ? nextBpm : null;
+ if (!playing) rebuild();
+ };
+
+ return {
+ play,
+ pause,
+ stop,
+ isPlaying: () => playing,
+ setTempo,
+ };
+};
diff --git a/client/src/lib/scorePlayback.test.js b/client/src/lib/scorePlayback.test.js
index 413976010b..d92a758a70 100644
--- a/client/src/lib/scorePlayback.test.js
+++ b/client/src/lib/scorePlayback.test.js
@@ -6,6 +6,7 @@ import {
pitchToMidi,
noteToFrequency,
createScorePlayer,
+ createMultiScorePlayer,
DEFAULT_BPM,
} from './scorePlayback.js';
@@ -164,3 +165,76 @@ describe('createScorePlayer', () => {
expect(ended).toHaveBeenCalled();
});
});
+
+// --- Multi-part player (layered MIDI) --------------------------------------
+describe('createMultiScorePlayer', () => {
+ beforeEach(() => {
+ audio.now = 0;
+ audio.oscillators = [];
+ vi.stubGlobal('AudioContext', FakeAudioContext);
+ vi.useFakeTimers();
+ });
+ afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); });
+
+ const MELODY = parseScore('time: 4/4\ntempo: 120\n| C4q D4q E4q F4q |'); // 4 notes
+ const BASS = parseScore('time: 4/4\ntempo: 120\n| C3h G3h |'); // 2 notes
+
+ it('synthesizes every selected part together (sum of pitched notes across voices)', async () => {
+ const player = createMultiScorePlayer(
+ [{ id: 'melody', score: MELODY }, { id: 'bass', score: BASS }],
+ { bpm: 120 },
+ );
+ await player.play();
+ drive(3); // past the longest part (2 s)
+ expect(audio.oscillators).toHaveLength(6); // 4 melody + 2 bass
+ player.stop();
+ });
+
+ it('emits a per-part playhead index, then null for every part at the end', async () => {
+ const seen = [];
+ const ended = vi.fn();
+ const player = createMultiScorePlayer(
+ [{ id: 'melody', score: MELODY }, { id: 'bass', score: BASS }],
+ { bpm: 120, onNote: (id, i) => seen.push([id, i]), onEnded: ended },
+ );
+ await player.play();
+ drive(3);
+ expect(seen).toContainEqual(['melody', 0]);
+ expect(seen).toContainEqual(['bass', 0]);
+ // Last event per part clears its playhead with null.
+ expect(seen).toContainEqual(['melody', null]);
+ expect(seen).toContainEqual(['bass', null]);
+ expect(ended).toHaveBeenCalledTimes(1);
+ });
+
+ it('plays only the parts it is given (a deselected part contributes nothing)', async () => {
+ const player = createMultiScorePlayer([{ id: 'bass', score: BASS }], { bpm: 120 });
+ await player.play();
+ drive(3);
+ expect(audio.oscillators).toHaveLength(2); // bass only
+ player.stop();
+ });
+
+ it('stop() cancels the lookahead and stops live nodes across all voices', async () => {
+ const player = createMultiScorePlayer(
+ [{ id: 'melody', score: MELODY }, { id: 'bass', score: BASS }],
+ { bpm: 120 },
+ );
+ await player.play();
+ const scheduledSoFar = audio.oscillators.length;
+ expect(scheduledSoFar).toBeGreaterThan(0);
+ player.stop();
+ expect(audio.oscillators.every((o) => o.stopped !== null)).toBe(true);
+ drive(3);
+ expect(audio.oscillators).toHaveLength(scheduledSoFar); // nothing new after stop
+ expect(player.isPlaying()).toBe(false);
+ });
+
+ it('reports ended for an empty selection without scheduling audio', async () => {
+ const ended = vi.fn();
+ const player = createMultiScorePlayer([], { onEnded: ended });
+ await player.play();
+ expect(audio.oscillators).toHaveLength(0);
+ expect(ended).toHaveBeenCalled();
+ });
+});
diff --git a/client/src/lib/songCraft.js b/client/src/lib/songCraft.js
index 54467b55ad..db1d8a188d 100644
--- a/client/src/lib/songCraft.js
+++ b/client/src/lib/songCraft.js
@@ -82,64 +82,64 @@ export const rhythmShapeLabel = (id) => {
// --- Voice layers ----------------------------------------------------------
// The order singers stack parts when arranging a cappella, foundation-first.
-// `order` is the recommended build sequence; `voices` names the typical
-// SATB-ish home for the part. The editor offers these as part labels.
+// This is the SAME vocabulary as the sheet-music HARMONY_PARTS stack below — ids
+// and labels match — so a recorded take's layer lines up with the notated part of
+// the same name (Melody, Bass, Mid/High Harmony I & II), and the recording
+// "take types" stay in step with the parts the AI derive tool generates. The
+// difference is framing: here `voices`/`role`/`advice` teach how to *build and
+// sing* each layer, where HARMONY_PARTS carries the `range`/`voicing` rules the
+// derive prompt needs. `order` is the recommended build sequence (melody → bass →
+// inner voices → upper voices); `voices` names the typical SATB-ish home.
+// songCraft.test.js guards that every layer id+label still exists in
+// HARMONY_PARTS so the two vocabularies can't drift apart.
export const VOICE_LAYERS = [
{
- id: 'lead',
- label: 'Lead melody',
+ id: 'melody',
+ label: 'Melody',
order: 1,
voices: 'Any — the tune everyone knows',
- role: 'The song itself. Everyone learns this first so the harmony has a home to orbit.',
+ role: 'The lead — the song itself. Everyone learns this first so the harmony has a home to orbit.',
advice: 'Lock the lead before adding anything. If the melody is shaky, every layer above it wobbles.',
},
{
id: 'bass',
- label: 'Bass / root',
+ label: 'Bass',
order: 2,
voices: 'Bass',
- role: 'The harmonic floor — usually the root of each chord, moving slowly.',
+ role: 'The harmonic floor — the root of each chord with the fifth as gentle movement.',
advice: 'Add the bass second. It defines the chord under the melody and gives the upper voices their tuning reference.',
},
{
- id: 'harmony-3rd',
- label: 'Harmony (third)',
+ id: 'mid-harmony-1',
+ label: 'Mid Harmony I',
order: 3,
voices: 'Alto / Tenor',
- role: 'A line a third above or below the melody — the first taste of chord color.',
- advice: 'Thirds are the sweet spot: close enough to feel like the tune, far enough to bloom into harmony. Build this before stacking wider intervals.',
+ role: 'The main moving inner voice — a third/sixth below the melody but landing on chord tones.',
+ advice: 'The richest harmony, so build it first among the inner voices. Move smoothly and favour common tones between chords.',
},
{
- id: 'harmony-5th',
- label: 'Harmony (fifth)',
+ id: 'mid-harmony-2',
+ label: 'Mid Harmony II',
order: 4,
- voices: 'Tenor / Soprano',
- role: 'The fifth fills out the triad and opens the sound up.',
- advice: 'With root, third and fifth you have a full chord. Add this once the third is solid so the stack stays in tune.',
+ voices: 'Alto',
+ role: 'A 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: 'drone',
- label: 'Drone / pedal',
+ id: 'high-harmony-2',
+ label: 'High Harmony II',
order: 5,
- voices: 'Bass / Alto',
- role: 'A sustained held note (often the tonic or fifth) under everything.',
- advice: 'A drone is the cheapest way to make a lament feel ancient and grounded. One held vowel under the whole verse does enormous work.',
- },
- {
- id: 'counter',
- label: 'Counter-melody',
- order: 6,
voices: 'Soprano / Tenor',
- role: 'An independent melodic line that answers the lead in its gaps.',
- advice: 'Save this for last. It fills the lead\'s breathing spaces — write it into the rests, not on top of the words.',
+ role: 'A sustained upper chord tone with gentle suspensions — carries the leading tone that pulls back to the tonic.',
+ advice: 'A held pad above the inner voices. Keep the dominant-7 third so it resolves up to the tonic.',
},
{
- id: 'vocal-perc',
- label: 'Vocal percussion / texture',
- order: 7,
- voices: 'Any',
- role: 'Breath, hums, clicks, "doo"/"ah" pads, or beatbox — rhythmic and textural glue.',
- advice: 'Optional and genre-dependent. For a dirge, a soft hummed pad beats a beatbox; keep texture serving the mood.',
+ id: 'high-harmony-1',
+ label: 'High Harmony I',
+ order: 6,
+ voices: 'Soprano',
+ role: 'The 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.',
},
];
diff --git a/client/src/lib/songCraft.test.js b/client/src/lib/songCraft.test.js
index 4173345da1..503a755d5f 100644
--- a/client/src/lib/songCraft.test.js
+++ b/client/src/lib/songCraft.test.js
@@ -43,15 +43,30 @@ describe('songCraft reference data', () => {
const orders = VOICE_LAYERS.map((l) => l.order);
expect(orders).toEqual([...orders].sort((a, b) => a - b));
expect(new Set(orders).size).toBe(orders.length);
- // Lead melody is always the first layer learned.
- expect(VOICE_LAYERS[0].id).toBe('lead');
+ // The melody (lead) is always the first layer learned.
+ expect(VOICE_LAYERS[0].id).toBe('melody');
for (const l of VOICE_LAYERS) {
expect(typeof l.label).toBe('string');
expect(typeof l.role).toBe('string');
expect(typeof l.advice).toBe('string');
+ expect(typeof l.voices).toBe('string');
}
});
+ it('voice-layer vocabulary matches the harmony-parts stack (recording take types == notated parts)', () => {
+ // Every recordable voice layer must correspond to a sheet-music part of the
+ // same id AND label, so a take assigned to a layer lines up with the staff of
+ // the same name and the two vocabularies can't drift apart.
+ const partById = new Map(HARMONY_PARTS.map((p) => [p.id, p]));
+ for (const l of VOICE_LAYERS) {
+ const part = partById.get(l.id);
+ expect(part, `voice layer "${l.id}" has no matching harmony part`).toBeTruthy();
+ expect(l.label).toBe(part.label);
+ }
+ // And the layer set covers the full stack (melody + every derivable part).
+ expect(new Set(VOICE_LAYERS.map((l) => l.id))).toEqual(new Set(HARMONY_PARTS.map((p) => p.id)));
+ });
+
it('every learning step and notation group has the documented shape', () => {
for (const step of LEARNING_STEPS) {
expect(typeof step.id).toBe('string');
diff --git a/client/src/pages/SongEditor.jsx b/client/src/pages/SongEditor.jsx
index 4f12f093f8..8f40de9ce5 100644
--- a/client/src/pages/SongEditor.jsx
+++ b/client/src/pages/SongEditor.jsx
@@ -22,7 +22,7 @@
* recommended order.
*/
-import { useState, useEffect, useCallback, useMemo } from 'react';
+import { useState, useEffect, useCallback, useMemo, useRef, useId } from 'react';
import { useParams, useNavigate, useSearchParams, Link } from 'react-router-dom';
import {
Music, ArrowLeft, Plus, Trash2, Save, BookOpen, CheckCircle2, Circle, Layers, Eye, Pencil,
@@ -39,7 +39,8 @@ import SongScoreEditor from '../components/songs/SongScoreEditor';
import SongScoreParts from '../components/songs/SongScoreParts';
import ScoreSheet from '../components/songs/ScoreSheet';
import RoundStack from '../components/songs/RoundStack';
-import { scoreHasMusic } from '../lib/scoreNotation';
+import { scoreHasMusic, parseScore } from '../lib/scoreNotation';
+import { createMultiScorePlayer, DEFAULT_BPM } from '../lib/scorePlayback';
import { harmonyPartOrder } from '../lib/songCraft';
// Cap on partner songs — mirrors services/songs.js PARTNERS_MAX. Used only to
@@ -481,7 +482,7 @@ export default function SongEditor() {
</button>
</div>
<p className="text-xs text-gray-500 mb-2">
- Build foundation-first: lead, then bass, then thirds and fifths. See the{' '}
+ Build foundation-first: melody, then bass, then the mid &amp; high harmonies. See the{' '}
<Link to="/songs/guide" className="text-port-accent hover:underline">Learning Guide</Link> for the full ladder.
</p>
{remainingPresets.length > 0 && (
@@ -843,11 +844,13 @@ function ReadView({ song, setField, onRefreshTemplate, refreshing, partnerSongs
}
// Sheet-music card for the read view: the base melody plus any harmony
-// variations, switchable via a pill row (Melody first, then parts low→high). Each
-// part renders through <ScoreSheet> with its own reference-tone playback; keying
-// the staff on the active tab tears down the previous part's audio on switch.
-// Returns null when there's no music anywhere, so the caller can mount it
-// unconditionally.
+// variations. With more than one part it grows a layered MIDI player — a tempo
+// control plus a checkbox per part so you can hear any combination of voices
+// (melody + bass + a harmony, the whole stack, …) sounding together, synthesized
+// in sync by createMultiScorePlayer. A pill row picks which staff is *shown*
+// (independent of what plays), and the playhead lights up on the shown staff when
+// it's one of the parts currently sounding. A single-part song keeps the simple
+// per-staff player. Returns null when there's no music anywhere.
function SheetMusicViewer({ baseScore, scoreParts = [] }) {
const tabs = useMemo(() => {
const out = [];
@@ -859,35 +862,173 @@ function SheetMusicViewer({ baseScore, scoreParts = [] }) {
.forEach((p) => out.push({ key: p.id, label: p.label || 'Part', score: p.score }));
return out;
}, [baseScore, scoreParts]);
- const [active, setActive] = useState(0);
if (!tabs.length) return null;
- // Clamp if the tab set shrank since the last render (a part removed/cleared).
- const idx = active < tabs.length ? active : 0;
- const current = tabs[idx];
+ // Single part: keep the simple per-staff player (its own transport).
+ if (tabs.length === 1) {
+ return (
+ <section className="space-y-2">
+ <h2 className="text-sm font-semibold text-white">Sheet music</h2>
+ <div className="bg-port-card border border-port-border rounded-lg p-4 overflow-x-auto">
+ <ScoreSheet key={tabs[0].key} text={tabs[0].score} />
+ </div>
+ </section>
+ );
+ }
+ return <LayeredSheetMusic tabs={tabs} />;
+}
+
+// Multi-part sheet music with a layered MIDI player. `selected` (the checked
+// parts) drives playback; `viewKey` drives which staff is rendered. The combined
+// player is rebuilt whenever the selection, tab set, or tempo changes so it
+// always sounds exactly the checked voices.
+function LayeredSheetMusic({ tabs }) {
+ const uid = useId();
+ const tabsKey = tabs.map((t) => t.key).join('|');
+
+ const [viewKey, setViewKey] = useState(tabs[0].key);
+ // Default: every part checked, so Play gives the full stack out of the box.
+ // Reconcile across tab-set changes — keep checks for parts that still exist,
+ // include any newly-added part, and never leave the selection empty.
+ const [selected, setSelected] = useState(() => new Set(tabs.map((t) => t.key)));
+ useEffect(() => {
+ setSelected((prev) => {
+ const next = new Set(tabs.filter((t) => prev.has(t.key)).map((t) => t.key));
+ if (next.size === 0) tabs.forEach((t) => next.add(t.key));
+ return next;
+ });
+ }, [tabsKey]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ const melodyScore = tabs[0].score;
+ const tempoFromMelody = useMemo(() => {
+ const t = parseScore(melodyScore).tempo;
+ return Number.isFinite(t) && t > 0 ? t : DEFAULT_BPM;
+ }, [melodyScore]);
+ const [tempo, setTempo] = useState(tempoFromMelody);
+ useEffect(() => { setTempo(tempoFromMelody); }, [tempoFromMelody]);
+
+ const playerRef = useRef(null);
+ const [isPlaying, setIsPlaying] = useState(false);
+ const [activeByPart, setActiveByPart] = useState({}); // partKey → now-sounding note index
+
+ const selectionKey = tabs.filter((t) => selected.has(t.key)).map((t) => t.key).join('|');
+
+ const teardown = useCallback(() => {
+ if (playerRef.current) { playerRef.current.stop(); playerRef.current = null; }
+ setIsPlaying(false);
+ setActiveByPart({});
+ }, []);
+
+ // A changed selection / tab set / tempo invalidates the combined player.
+ useEffect(() => { teardown(); }, [selectionKey, tabsKey, tempo, teardown]);
+ // Tear down live audio on unmount.
+ useEffect(() => () => teardown(), [teardown]);
+
+ const ensurePlayer = () => {
+ if (!playerRef.current) {
+ const parts = tabs
+ .filter((t) => selected.has(t.key))
+ .map((t) => ({ id: t.key, score: parseScore(t.score) }));
+ playerRef.current = createMultiScorePlayer(parts, {
+ bpm: tempo,
+ onNote: (id, i) => setActiveByPart((prev) => {
+ const next = i == null ? -1 : i;
+ return prev[id] === next ? prev : { ...prev, [id]: next };
+ }),
+ onEnded: () => { setIsPlaying(false); setActiveByPart({}); },
+ });
+ }
+ return playerRef.current;
+ };
+
+ const togglePlay = () => {
+ if (!selected.size) return;
+ const player = ensurePlayer();
+ if (isPlaying) { player.pause(); setIsPlaying(false); return; }
+ setIsPlaying(true);
+ Promise.resolve(player.play()).catch(() => setIsPlaying(false));
+ };
+
+ const handleStop = () => { teardown(); };
+
+ const toggleSelected = (key) => setSelected((prev) => {
+ const next = new Set(prev);
+ if (next.has(key)) next.delete(key); else next.add(key);
+ return next;
+ });
+
+ const current = tabs.find((t) => t.key === viewKey) || tabs[0];
+ // Light the playhead on the shown staff only when it's one of the parts that's
+ // actually sounding; otherwise -1 (no highlight) rather than null (which would
+ // hand control back to <ScoreSheet>'s own — here unused — internal player).
+ const shownActive = selected.has(current.key) ? (activeByPart[current.key] ?? -1) : -1;
+
+ const transportBtn = 'flex items-center gap-1 rounded-md border border-port-border bg-port-card px-2 py-1 text-white hover:border-port-accent transition-colors disabled:opacity-40 disabled:hover:border-port-border';
return (
<section className="space-y-2">
- <div className="flex items-center justify-between gap-2 flex-wrap">
- <h2 className="text-sm font-semibold text-white">Sheet music</h2>
- {tabs.length > 1 && (
- <div className="flex flex-wrap gap-1.5">
- {tabs.map((t, i) => (
- <button
- key={t.key}
- type="button"
- onClick={() => setActive(i)}
- aria-pressed={i === idx}
- className={`px-2.5 py-1 text-xs rounded-full border transition-colors ${i === idx ? 'bg-port-accent text-white border-port-accent' : 'border-port-border text-gray-300 hover:text-white hover:border-port-accent/60'}`}
- >
- {t.label}
- </button>
- ))}
- </div>
- )}
+ <h2 className="text-sm font-semibold text-white">Sheet music</h2>
+
+ {/* Layered MIDI transport: play the checked combination of parts together. */}
+ <div className="flex flex-wrap items-center gap-2 text-xs text-gray-400">
+ <button type="button" onClick={togglePlay} disabled={!selected.size} aria-label={isPlaying ? 'Pause parts' : 'Play selected parts'} className={transportBtn}>
+ <span aria-hidden="true">{isPlaying ? '⏸' : '▶'}</span>
+ <span className="hidden sm:inline">{isPlaying ? 'Pause' : 'Play parts'}</span>
+ </button>
+ <button type="button" onClick={handleStop} disabled={!isPlaying} aria-label="Stop" className={transportBtn}>
+ <span aria-hidden="true">⏹</span>
+ <span className="hidden sm:inline">Stop</span>
+ </button>
+ <label htmlFor={`${uid}-tempo`} className="flex items-center gap-1">
+ <span>Tempo</span>
+ <input
+ id={`${uid}-tempo`}
+ type="number"
+ min={20}
+ max={300}
+ value={tempo}
+ onChange={(e) => { const n = Number(e.target.value); if (Number.isFinite(n) && n > 0) setTempo(n); }}
+ className="w-16 rounded-md border border-port-border bg-port-card px-2 py-1 text-white"
+ />
+ <span>BPM</span>
+ </label>
</div>
+
+ {/* One checkbox per part — the mix that Play sounds. */}
+ <fieldset className="flex flex-wrap items-center gap-x-3 gap-y-1.5 text-xs">
+ <legend className="sr-only">Parts to play together</legend>
+ <span className="text-gray-500">Layers:</span>
+ {tabs.map((t) => (
+ <label key={t.key} htmlFor={`${uid}-pick-${t.key}`} className="flex items-center gap-1.5 text-gray-300 cursor-pointer">
+ <input
+ id={`${uid}-pick-${t.key}`}
+ type="checkbox"
+ checked={selected.has(t.key)}
+ onChange={() => toggleSelected(t.key)}
+ className="accent-port-accent"
+ />
+ {t.label}
+ </label>
+ ))}
+ </fieldset>
+
+ {/* Pill row picks which staff is shown (independent of what plays). */}
+ <div className="flex flex-wrap gap-1.5">
+ {tabs.map((t) => (
+ <button
+ key={t.key}
+ type="button"
+ onClick={() => setViewKey(t.key)}
+ aria-pressed={t.key === current.key}
+ className={`px-2.5 py-1 text-xs rounded-full border transition-colors ${t.key === current.key ? 'bg-port-accent text-white border-port-accent' : 'border-port-border text-gray-300 hover:text-white hover:border-port-accent/60'}`}
+ >
+ {t.label}
+ </button>
+ ))}
+ </div>
+
<div className="bg-port-card border border-port-border rounded-lg p-4 overflow-x-auto">
- <ScoreSheet key={current.key} text={current.score} />
+ <ScoreSheet key={current.key} text={current.score} controls={false} activeNoteIndex={shownActive} />
</div>
</section>
);
diff --git a/scripts/migrations/073-seed-500-miles-score.js b/scripts/migrations/073-seed-500-miles-score.js
index 08209ca595..1e21e43cd4 100644
--- a/scripts/migrations/073-seed-500-miles-score.js
+++ b/scripts/migrations/073-seed-500-miles-score.js
@@ -21,11 +21,11 @@ import { join } from 'path';
const SONG_ID = 'seed-500-miles';
-// The shipped verse melody — kept identical to SEED_SONGS[seed-500-miles].score
-// in server/services/songs.js (the migration test asserts they match, so a drift
-// fails CI rather than silently shipping two different scores). Updated to the
-// correct G-major transcription (Hedy West) alongside the seed; migration 075
-// upgrades installs that already hold the earlier C-major backfill.
+// The shipped melody — kept identical to SEED_SONGS[seed-500-miles].score in
+// server/services/songs.js (the migration test asserts they match, so a drift
+// fails CI rather than silently shipping two different scores). Now the full
+// song (all verses + closing coda) in G major; migration 075 upgrades installs
+// that still hold the earlier C-major backfill.
export const SCORE_500_MILES = [
'clef: treble',
'key: G',
@@ -40,6 +40,50 @@ export const SCORE_500_MILES = [
'| [D7] A4q.(hear) F#4e(the) A4q.(whis-) F#4e(tle) |',
'| [G] G4h(blow) A4e(a) B4e(hun-) C5q(dred) |',
'| [G] D5w(miles) |',
+ '',
+ '| [G] D5h(A) B4q(hun-) A4q(dred) |',
+ '| [Em] B4q.(miles) A4e(a) B4q.(hun-) A4e(dred) |',
+ '| [C] C5q.(miles) B4e(a) A4q(hun-) G4q(dred) |',
+ '| [Am7] E4h.(miles) F#4e(you) G4e(can) |',
+ '| [D7] A4q.(hear) F#4e(the) A4q.(whis-) F#4e(tle) |',
+ '| [G] G4h(blow) A4e(a) B4e(hun-) C5q(dred) |',
+ '| [G] D5w(miles) |',
+ '',
+ '| [G] D5h(Lord,) B4q(I\'m) A4q(one,) |',
+ '| [Em] B4h(Lord,) A4q(I\'m) G4q(two,) |',
+ '| [C] C5q.(Lord,) B4e(I\'m) A4q(three,) G4q(Lord,) |',
+ '| [Am7] E4h.(I\'m) F#4e(four,) G4e(Lord,) |',
+ '| [D7] A4q.(I\'m) F#4e(five) A4q.(hun-) F#4e(dred) |',
+ '| [G] G4h(miles) A4e(a-) B4e(way) C5q(from) |',
+ '| [G] D5w(home) |',
+ '',
+ '| [G] D5h(A-) B4q(way) A4q(from) |',
+ '| [Em] B4h(home,) A4q(a-) G4q(way) |',
+ '| [C] C5q.(from) B4e(home,) A4q(a-) G4q(way) |',
+ '| [Am7] E4h.(from) F#4e(home,) G4e(Lord,) |',
+ '| [D7] A4q.(I\'m) F#4e(five) A4q.(hun-) F#4e(dred) |',
+ '| [G] G4h(miles) A4e(a-) B4e(way) C5q(from) |',
+ '| [G] D5w(home) |',
+ '',
+ '| [G] D5h(Not) B4q(a) A4q(shirt) |',
+ '| [Em] B4h(on) A4q(my) G4q(back,) |',
+ '| [C] C5q.(not) B4e(a) A4q(pen-) G4q(ny) |',
+ '| [Am7] E4h.(to) F#4e(my) G4e(name,) |',
+ '| [D7] A4q.(Lord,) F#4e(I) A4q.(can\'t) F#4e(go) |',
+ '| [G] G4h(back) A4e(home) B4e(this-) C5q(a-) |',
+ '| [G] D5w(way) |',
+ '',
+ '| [G] D5h(This-) B4q(a-) A4q(way,) |',
+ '| [Em] B4h(this-) A4q(a-) G4q(way,) |',
+ '| [C] C5q.(this-) B4e(a-) A4q(way,) G4q(Lord,) |',
+ '| [Am7] E4h.(I) F#4e(can\'t) G4e(go) |',
+ '| [D7] A4q.(back) F#4e(home) A4q.(this-) F#4e(a-) |',
+ '| [G] G4h(way) D5h |',
+ '',
+ '| [G] D5h(You) B4q(can) A4q(hear) |',
+ '| [C] C5q.(the) B4e(whis-) A4q(tle) G4q(blow) |',
+ '| [D7] A4q(a) F#4q(hun-) A4q(dred) F#4q(miles) |',
+ '| [G] G4w(miles) |',
].join('\n');
const fileExists = (path) => stat(path).then(() => true, (err) => {
diff --git a/server/lib/songCraftRef.js b/server/lib/songCraftRef.js
index a43938885a..ca967cc3e2 100644
--- a/server/lib/songCraftRef.js
+++ b/server/lib/songCraftRef.js
@@ -28,15 +28,16 @@ export const RHYTHM_SHAPES = [
];
// Voice layers in foundation-first build order: { id, label, voices, role }.
-// Mirrors VOICE_LAYERS in songCraft.js.
+// SAME vocabulary as HARMONY_PARTS (ids + labels match) so recording "take types"
+// stay in step with the parts the derive tool generates. Mirrors VOICE_LAYERS in
+// songCraft.js.
export const VOICE_LAYERS = [
- { id: 'lead', label: 'Lead melody', voices: 'Any — the tune everyone knows', role: 'The song itself. Everyone learns this first so the harmony has a home to orbit.' },
- { id: 'bass', label: 'Bass / root', voices: 'Bass', role: 'The harmonic floor — usually the root of each chord, moving slowly.' },
- { id: 'harmony-3rd', label: 'Harmony (third)', voices: 'Alto / Tenor', role: 'A line a third above or below the melody — the first taste of chord color.' },
- { id: 'harmony-5th', label: 'Harmony (fifth)', voices: 'Tenor / Soprano', role: 'The fifth fills out the triad and opens the sound up.' },
- { id: 'drone', label: 'Drone / pedal', voices: 'Bass / Alto', role: 'A sustained held note (often the tonic or fifth) under everything.' },
- { id: 'counter', label: 'Counter-melody', voices: 'Soprano / Tenor', role: 'An independent melodic line that answers the lead in its gaps.' },
- { id: 'vocal-perc', label: 'Vocal percussion / texture', voices: 'Any', role: 'Breath, hums, clicks, "doo"/"ah" pads, or beatbox — rhythmic and textural glue.' },
+ { id: 'melody', label: 'Melody', voices: 'Any — the tune everyone knows', role: 'The lead — the song itself. Everyone learns this first so the harmony has a home to orbit.' },
+ { id: 'bass', label: 'Bass', voices: 'Bass', role: 'The harmonic floor — the root of each chord with the fifth as gentle movement.' },
+ { id: 'mid-harmony-1', label: 'Mid Harmony I', voices: 'Alto / Tenor', role: 'The main moving inner voice — a third/sixth below the melody but landing on chord tones.' },
+ { id: 'mid-harmony-2', label: 'Mid Harmony II', voices: 'Alto', role: 'A low inner pad — sustained chord tones below the melody (often the 3rd or 5th of the chord).' },
+ { id: 'high-harmony-2', label: 'High Harmony II', voices: 'Soprano / Tenor', role: 'A sustained upper chord tone with gentle suspensions — carries the leading tone that pulls back to the tonic.' },
+ { id: 'high-harmony-1', label: 'High Harmony I', voices: 'Soprano', role: 'The sparse top descant — mostly sustained high chord tones, entering on the emotional phrases.' },
];
// The dirge-family shapes (the lament the workbench centers on), in order.
diff --git a/server/services/songs.js b/server/services/songs.js
index 42e4b0b2f7..dfb2cd7701 100644
--- a/server/services/songs.js
+++ b/server/services/songs.js
@@ -311,9 +311,9 @@ export const SEED_SONGS = [
tempo: 68,
rhythmShapeId: 'slow-4-4',
notation: 'Verse chords (key of G, after Hedy West): G — Em — C — Am7 — D7 — G, four slow bars per line. A gentle 4/4 ballad; let each line breathe across the bar rather than chopping it.',
- // Sheet music in the PortOS lead-sheet DSL — the verse melody with chords and
- // lyrics, transcribed from the Hedy West lead sheet in G major. Edit it in the
- // Sheet music tab; see client/src/lib/scoreNotation.js for the format. NOTE:
+ // Sheet music in the PortOS lead-sheet DSL — the full melody (all verses plus
+ // the closing coda) with chords and lyrics, in G major. Edit it in the Sheet
+ // music tab; see client/src/lib/scoreNotation.js for the format. NOTE:
// migration 073's SCORE_500_MILES constant must stay identical to this (the
// 073 drift test asserts it) — update both together.
score: [
@@ -330,6 +330,50 @@ export const SEED_SONGS = [
'| [D7] A4q.(hear) F#4e(the) A4q.(whis-) F#4e(tle) |',
'| [G] G4h(blow) A4e(a) B4e(hun-) C5q(dred) |',
'| [G] D5w(miles) |',
+ '',
+ '| [G] D5h(A) B4q(hun-) A4q(dred) |',
+ '| [Em] B4q.(miles) A4e(a) B4q.(hun-) A4e(dred) |',
+ '| [C] C5q.(miles) B4e(a) A4q(hun-) G4q(dred) |',
+ '| [Am7] E4h.(miles) F#4e(you) G4e(can) |',
+ '| [D7] A4q.(hear) F#4e(the) A4q.(whis-) F#4e(tle) |',
+ '| [G] G4h(blow) A4e(a) B4e(hun-) C5q(dred) |',
+ '| [G] D5w(miles) |',
+ '',
+ '| [G] D5h(Lord,) B4q(I\'m) A4q(one,) |',
+ '| [Em] B4h(Lord,) A4q(I\'m) G4q(two,) |',
+ '| [C] C5q.(Lord,) B4e(I\'m) A4q(three,) G4q(Lord,) |',
+ '| [Am7] E4h.(I\'m) F#4e(four,) G4e(Lord,) |',
+ '| [D7] A4q.(I\'m) F#4e(five) A4q.(hun-) F#4e(dred) |',
+ '| [G] G4h(miles) A4e(a-) B4e(way) C5q(from) |',
+ '| [G] D5w(home) |',
+ '',
+ '| [G] D5h(A-) B4q(way) A4q(from) |',
+ '| [Em] B4h(home,) A4q(a-) G4q(way) |',
+ '| [C] C5q.(from) B4e(home,) A4q(a-) G4q(way) |',
+ '| [Am7] E4h.(from) F#4e(home,) G4e(Lord,) |',
+ '| [D7] A4q.(I\'m) F#4e(five) A4q.(hun-) F#4e(dred) |',
+ '| [G] G4h(miles) A4e(a-) B4e(way) C5q(from) |',
+ '| [G] D5w(home) |',
+ '',
+ '| [G] D5h(Not) B4q(a) A4q(shirt) |',
+ '| [Em] B4h(on) A4q(my) G4q(back,) |',
+ '| [C] C5q.(not) B4e(a) A4q(pen-) G4q(ny) |',
+ '| [Am7] E4h.(to) F#4e(my) G4e(name,) |',
+ '| [D7] A4q.(Lord,) F#4e(I) A4q.(can\'t) F#4e(go) |',
+ '| [G] G4h(back) A4e(home) B4e(this-) C5q(a-) |',
+ '| [G] D5w(way) |',
+ '',
+ '| [G] D5h(This-) B4q(a-) A4q(way,) |',
+ '| [Em] B4h(this-) A4q(a-) G4q(way,) |',
+ '| [C] C5q.(this-) B4e(a-) A4q(way,) G4q(Lord,) |',
+ '| [Am7] E4h.(I) F#4e(can\'t) G4e(go) |',
+ '| [D7] A4q.(back) F#4e(home) A4q.(this-) F#4e(a-) |',
+ '| [G] G4h(way) D5h |',
+ '',
+ '| [G] D5h(You) B4q(can) A4q(hear) |',
+ '| [C] C5q.(the) B4e(whis-) A4q(tle) G4q(blow) |',
+ '| [D7] A4q(a) F#4q(hun-) A4q(dred) F#4q(miles) |',
+ '| [G] G4w(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.
@@ -346,10 +390,12 @@ export const SEED_SONGS = [
{ id: 'sec-verse-4', label: 'Verse 4 (reprise)', lyrics: 'If you miss the train I\'m on\nYou will know that I am gone\nYou can hear the whistle blow a hundred miles' },
],
layers: [
- { id: 'lead', label: 'Lead melody', part: 'Soprano / Tenor', notes: 'The tune everyone knows. Lock this first, in tune, before stacking anything.' },
- { id: 'bass', label: 'Bass / root', part: 'Bass', notes: 'Root of each chord — C, A, F, G. Move slowly; you are the floor.' },
- { id: 'harmony-3rd', label: 'Harmony (third)', part: 'Alto', notes: 'A third under the melody. The first colour — keep it close and warm.' },
- { id: 'drone', label: 'Drone / pedal', part: 'Bass / Alto', notes: 'Optional held tonic (C) under the verse to make the lament feel ancient.' },
+ { id: 'melody', label: 'Melody', part: 'Soprano / Tenor', notes: 'The tune everyone knows. Lock this first, in tune, before stacking anything.' },
+ { id: 'bass', label: 'Bass', part: 'Bass', notes: 'Root of each chord — C, A, F, G — with the fifth as gentle movement. You are the floor; move slowly.' },
+ { id: 'mid-harmony-1', label: 'Mid Harmony I', part: 'Alto / Tenor', notes: 'The main inner voice — a third/sixth under the melody, landing on chord tones. The richest harmony; build it first.' },
+ { id: 'mid-harmony-2', label: 'Mid Harmony II', part: 'Alto', notes: 'Low inner pad — sustained chord tones under Mid Harmony I. Move by step; do not chase the melody.' },
+ { id: 'high-harmony-2', label: 'High Harmony II', part: 'Soprano / Tenor', notes: 'Held upper pad — keep the leading tone (the B in G7) so it resolves up to C.' },
+ { id: 'high-harmony-1', label: 'High Harmony I', part: 'Soprano', notes: 'Sparse top descant — high chord tones on the emotional phrases. Enter late; mostly long notes.' },
],
references: [
{ id: 'ref-tt-marie', url: 'https://www.tiktok.com/@marie.celestinee/video/7638358831205977376', label: 'TikTok · @marie.celestinee', note: 'Reference performance.' },
diff --git a/server/services/songsAI.js b/server/services/songsAI.js
index 53bc5ee8bc..892290eb68 100644
--- a/server/services/songsAI.js
+++ b/server/services/songsAI.js
@@ -102,7 +102,7 @@ Return ONLY a JSON object (no prose, no markdown fence) with this shape:
"notation": "string — chord progression / lead-sheet notes / solfège, e.g. 'C — Am — F — G'",
"notes": "string — how it should feel, dynamics, where to breathe, what to drill",
"sections": [ { "label": "Verse 1", "lyrics": "..." } ], // max ${SECTIONS_MAX}
- "layers": [ { "id": "lead", "label": "Lead melody", "part": "Soprano/Tenor", "notes": "learning notes — intervals, entrances, breaths" } ] // max ${LAYERS_MAX}
+ "layers": [ { "id": "melody", "label": "Melody", "part": "Soprano/Tenor", "notes": "learning notes — intervals, entrances, breaths" } ] // max ${LAYERS_MAX}
}
Keep lyrics original (do not reproduce copyrighted lyrics verbatim). Each string field under ${FIELD_MAX_LENGTH} characters.`;
};