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: sheet-music harmony parts + AI derivation, and correct the 500 Miles melody
[._.]/ Adam Eivy7657c064510e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 5942ec4b97..23ee94b172 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +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: 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.@@ -35,6 +36,7 @@## Fixed+- **Songs: "500 Miles" now ships the correct melody, in G major** — the built-in "500 Miles" previously carried a placeholder verse melody in C major that didn't match the song. It's been re-transcribed in G major (the Hedy West lead sheet — G · Em · C · Am7 · D7 · G) with the correct verse tune, chords, and rhythm. Fresh installs get it directly; an existing install that still holds the old placeholder is upgraded automatically on boot (a migration that only touches the unedited shipped version — a score you've customized is left alone), and you can always pull the latest via the song's "Refresh from template" button.- **Sheet music: low notes no longer overlap their lyrics** — the lyric line was drawn at a fixed distance below the staff, so notes that dip below it (ledger-line pitches like A3) rendered their noteheads on top of the syllable. Lyrics now sit below the lowest note in each line.- **[issue-980] PostgreSQL restores now verify the backup against its manifest before replaying** — a snapshot's database dump is hashed into the snapshot's `manifest.json` when the backup is taken, but the restore path never checked that hash, so a corrupted or tampered dump would be fed straight into `psql`. Restores now recompute the dump's SHA-256 and compare it against the stored hash first; on a mismatch the restore refuses (no `psql` is run) rather than replaying a damaged dump over your live database. Older snapshots taken before manifests existed — or any manifest missing the dump's entry — still restore as before, since there's nothing recorded to verify against.diff --git a/client/src/components/songs/SongScoreParts.jsx b/client/src/components/songs/SongScoreParts.jsxnew file mode 100644index 0000000000..8201f532d0--- /dev/null+++ b/client/src/components/songs/SongScoreParts.jsx@@ -0,0 +1,190 @@+/**+ * SongScoreParts — manage a song's sheet-music harmony variations (Bass, Mid+ * Harmony I/II, High Harmony I/II …) in the editor. Each part is its own staff+ * in the PortOS lead-sheet DSL, rhythm-aligned to the base melody so the parts+ * stack when sung together.+ *+ * Two ways to fill it:+ * - "Derive with AI" → POST /api/songs/:id/derive-parts reads the song's SAVED+ * base melody and returns harmony parts; we merge them into the draft (the+ * parent owns Save). Because the server reads the *persisted* base score, the+ * button is gated on the base melody being saved (not the in-memory draft) —+ * the project's "Run Now actions gate on saved state" rule.+ * - "Add part" → a blank part seeded from the base melody to hand-edit.+ *+ * Each part has a live <ScoreSheet> preview (with its own reference-tone playback,+ * so you can hear a harmony in isolation) and a textarea for the notation. State+ * is lifted: every edit calls `onChange(nextParts)`; the parent persists on Save.+ */++import { useState } from 'react';+import { Music2, Plus, Trash2, Wand2, Loader2, ChevronDown, ChevronRight, AlertTriangle } from 'lucide-react';+import toast from '../ui/Toast';+import ScoreSheet from './ScoreSheet.jsx';+import { deriveSongParts } from '../../services/api';+import { HARMONY_PARTS, harmonyPartLabel, harmonyPartOrder } from '../../lib/songCraft';+import { scoreHasMusic } from '../../lib/scoreNotation';++// In-session temp id for a part not yet persisted. MUST end in `-new-<n>` so the+// editor's stripTempId (/-new-\d+$/) blanks it on save and the server assigns a+// stable `part-<uuid>` — otherwise a reload could re-mint the same id and collide.+let seq = 0;+const tempPartId = () => `part-new-${seq++}`;++// Roles the user can tag a part with (drives ordering + a sensible default+// label). Only the derivable harmony roles are offered; "melody" is the base.+const ROLE_OPTIONS = HARMONY_PARTS.filter((p) => p.derivable);++export default function SongScoreParts({ songId, baseScore = '', baseDirty = false, scoreParts = [], onChange }) {+ const [deriving, setDeriving] = useState(false);+ const [openId, setOpenId] = useState(null);++ const hasBase = scoreHasMusic(baseScore);+ // Derive needs a SAVED base melody — the server reads the persisted score, so a+ // dirty (unsaved) base would derive harmony from stale notes.+ const canDerive = hasBase && !baseDirty && !deriving;++ const update = (id, patch) => onChange(scoreParts.map((p) => (p.id === id ? { ...p, ...patch } : p)));+ const remove = (id) => onChange(scoreParts.filter((p) => p.id !== id));++ const addBlank = () => {+ const id = tempPartId();+ // Seed from the base melody so the user transposes rather than starting blank.+ onChange([...scoreParts, { id, label: 'Part', role: '', score: baseScore || '' }]);+ setOpenId(id);+ };++ const derive = async () => {+ setDeriving(true);+ const data = await deriveSongParts(songId, {}, { silent: true })+ .catch((err) => { toast.error(err?.message || 'Could not derive harmony parts'); return null; });+ setDeriving(false);+ if (!data?.scoreParts?.length) return;+ // Merge by role: a derived part replaces an existing part of the same role+ // (re-deriving updates in place); roles not present yet are appended. Parts+ // with no role (hand-added/custom) are never clobbered.+ const next = [...scoreParts];+ for (const dp of data.scoreParts) {+ const idx = dp.role ? next.findIndex((p) => p.role && p.role === dp.role) : -1;+ if (idx >= 0) next[idx] = { ...next[idx], label: dp.label || next[idx].label, score: dp.score };+ else next.push({ id: tempPartId(), label: dp.label || harmonyPartLabel(dp.role) || 'Part', role: dp.role || '', score: dp.score });+ }+ // Keep the list ordered low→high register for a predictable stack.+ next.sort((a, b) => harmonyPartOrder(a.role) - harmonyPartOrder(b.role));+ onChange(next);+ const n = data.scoreParts.length;+ toast.success(`Derived ${n} harmony part${n === 1 ? '' : 's'} — review & Save`);+ };++ const labelInput = 'flex-1 min-w-0 bg-port-bg border border-port-border rounded-lg px-3 py-1.5 text-sm text-white focus:border-port-accent focus:outline-none';+ const selectCls = 'bg-port-bg border border-port-border rounded-lg px-2 py-1.5 text-xs text-gray-300 focus:border-port-accent focus:outline-none';++ return (+ <section>+ <div className="flex items-center justify-between mb-2 gap-2 flex-wrap">+ <h2 className="flex items-center gap-2 text-sm font-semibold text-white">+ <Music2 size={15} className="text-port-accent" /> Sheet music parts (harmony variations)+ </h2>+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={derive}+ disabled={!canDerive}+ title={!hasBase ? 'Add a base melody first' : baseDirty ? 'Save the base melody first' : 'Derive harmony parts from the base melody'}+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg bg-port-accent text-white hover:bg-port-accent/90 disabled:opacity-50"+ >+ {deriving ? <Loader2 size={14} className="animate-spin" /> : <Wand2 size={14} />}+ Derive with AI+ </button>+ <button+ type="button"+ onClick={addBlank}+ disabled={!hasBase}+ title={hasBase ? 'Add a blank part seeded from the melody' : 'Add a base melody first'}+ className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50 disabled:opacity-50"+ >+ <Plus size={14} /> Add part+ </button>+ </div>+ </div>++ <p className="text-xs text-gray-500 mb-2">+ Bass, mid & high harmonies built from the melody above — each rhythm-aligned so the parts stack when sung together.+ Derive writes a full set with AI (Bass, Mid Harmony I/II, High Harmony I/II); review and <strong>Save</strong> to keep.+ </p>++ {!hasBase && (+ <p className="text-xs text-gray-500">Add a base melody in the Sheet music editor above, then derive or add harmony parts.</p>+ )}+ {hasBase && baseDirty && (+ <p className="flex items-center gap-1.5 text-xs text-port-warning mb-2">+ <AlertTriangle size={12} className="shrink-0" />+ You have unsaved changes to the base melody — Save first so AI derives harmony from the current notes.+ </p>+ )}++ {scoreParts.length > 0 && (+ <div className="space-y-3">+ {scoreParts.map((p) => {+ const open = openId === p.id;+ const partHasMusic = scoreHasMusic(p.score);+ return (+ <div key={p.id} className="bg-port-card border border-port-border rounded-lg p-3">+ <div className="flex items-center gap-2 mb-2">+ <button+ type="button"+ onClick={() => setOpenId(open ? null : p.id)}+ className="p-1 text-gray-400 hover:text-white shrink-0"+ aria-label={open ? 'Collapse part' : 'Edit part notation'}+ aria-expanded={open}+ >+ {open ? <ChevronDown size={15} /> : <ChevronRight size={15} />}+ </button>+ <input+ type="text"+ value={p.label}+ onChange={(e) => update(p.id, { label: e.target.value })}+ placeholder="Part label (Bass, High Harmony I…)"+ aria-label="Part label"+ className={labelInput}+ />+ <select+ value={p.role || ''}+ onChange={(e) => update(p.id, { role: e.target.value })}+ aria-label="Part role"+ className={selectCls}+ >+ <option value="">— role —</option>+ {ROLE_OPTIONS.map((r) => <option key={r.id} value={r.id}>{r.label}</option>)}+ </select>+ <button type="button" onClick={() => remove(p.id)} className="p-1.5 text-gray-500 hover:text-port-error shrink-0" aria-label="Remove part">+ <Trash2 size={15} />+ </button>+ </div>++ {/* Live staff preview with its own reference-tone playback. */}+ {partHasMusic && (+ <div className="bg-port-bg border border-port-border rounded-lg p-3 mb-2 overflow-x-auto">+ <ScoreSheet text={p.score} />+ </div>+ )}++ {open && (+ <textarea+ value={p.score}+ onChange={(e) => update(p.id, { score: e.target.value })}+ placeholder="Notation for this part (same lead-sheet format as the melody)…"+ aria-label="Part notation"+ rows={6}+ spellCheck={false}+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:border-port-accent focus:outline-none font-mono leading-relaxed"+ />+ )}+ </div>+ );+ })}+ </div>+ )}+ </section>+ );+}diff --git a/client/src/lib/songCraft.js b/client/src/lib/songCraft.jsindex 2266c1d2a3..c2b8eb3b9e 100644--- a/client/src/lib/songCraft.js+++ b/client/src/lib/songCraft.js@@ -143,6 +143,87 @@ export const VOICE_LAYERS = [},];+// --- Harmony parts (sheet-music variations) --------------------------------+// 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.+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.',+ advice: 'This is the base score. Lock it first; every derived part follows its rhythm, 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',+ derivable: true,+ interval: 'A third below the melody — the closest inner harmony.',+ advice: 'The sweetest, most stable harmony. Build this before any wider interval.',+ },+ {+ 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).',+ advice: 'Fills the inner voice under Mid Harmony I so the mid-register triad is complete.',+ },+ {+ id: 'high-harmony-1',+ label: 'High Harmony I',+ role: 'harmony',+ register: 'high',+ 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.',+ },+ {+ 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.',+ advice: 'The descant that crowns the chord. Save it for last; it exposes any tuning slip.',+ },+];++// 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.+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 };+export const harmonyPartOrder = (roleOrId) => {+ const part = HARMONY_PARTS.find((p) => p.id === roleOrId || p.role === roleOrId);+ return part ? REGISTER_ORDER[part.register] ?? 3 : 3;+};+// --- Learning steps --------------------------------------------------------// The practice sequence for learning a new a cappella song, in order.export const LEARNING_STEPS = [diff --git a/client/src/lib/songCraft.test.js b/client/src/lib/songCraft.test.jsindex 791bbc503d..7446d21257 100644--- a/client/src/lib/songCraft.test.js+++ b/client/src/lib/songCraft.test.js@@ -7,6 +7,10 @@ import {NOTATION_HELP,SOLFEGE_DEGREES,solfegeForDegree,+ HARMONY_PARTS,+ DERIVABLE_HARMONY_PARTS,+ harmonyPartLabel,+ harmonyPartOrder,} from './songCraft.js';describe('songCraft reference data', () => {@@ -73,4 +77,39 @@ describe('songCraft reference data', () => {expect(solfegeForDegree(null)).toBeNull();expect(solfegeForDegree('x')).toBeNull();});++ it('every harmony part carries id, label, role, register, derivable flag and interval', () => {+ 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 unique+ ids.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.derivable).toBe('boolean');+ expect(typeof p.interval).toBe('string');+ }+ // The melody is the base (not derivable); the rest are.+ expect(HARMONY_PARTS.find((p) => p.id === 'melody').derivable).toBe(false);+ expect(DERIVABLE_HARMONY_PARTS.every((p) => p.derivable)).toBe(true);+ expect(DERIVABLE_HARMONY_PARTS.map((p) => p.id)).toEqual([+ 'bass', 'mid-harmony-1', 'mid-harmony-2', 'high-harmony-1', 'high-harmony-2',+ ]);+ });++ it('harmonyPartLabel resolves known ids and empties unknown', () => {+ expect(harmonyPartLabel('bass')).toBe('Bass');+ expect(harmonyPartLabel('high-harmony-2')).toBe('High Harmony II');+ 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);+ });});diff --git a/client/src/pages/SongEditor.jsx b/client/src/pages/SongEditor.jsxindex a7adeebac0..4f12f093f8 100644--- a/client/src/pages/SongEditor.jsx+++ b/client/src/pages/SongEditor.jsx@@ -36,9 +36,11 @@ import Pill from '../components/ui/Pill';import SongAiPanel from '../components/songs/SongAiPanel';import SongRecordings from '../components/songs/SongRecordings';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 { harmonyPartOrder } from '../lib/songCraft';// Cap on partner songs — mirrors services/songs.js PARTNERS_MAX. Used only to// disable adding more in the editor; the server enforces the real bound.@@ -120,6 +122,17 @@ export default function SongEditor() {}, [setSearchParams]);const [song, setSong] = useState(null);const [loading, setLoading] = useState(true);+ // The last server-persisted base melody (score + key). Used to gate the AI+ // "Derive harmony parts" action, which reads the SAVED score server-side — so+ // it must be disabled while the base melody has unsaved edits (the project's+ // "Run Now actions gate on saved state" rule). Updated wherever a canonical+ // server song lands (load, save, refresh-from-template).+ const [savedBase, setSavedBase] = useState({ score: '', key: '' });+ // Adopt a server-canonical song: set the draft AND snapshot its saved base.+ const setServerSong = useCallback((s) => {+ setSong(s);+ setSavedBase({ score: s?.score || '', key: s?.key || '' });+ }, []);// All songs — resolves partner records for the round stack and the "Sings// with" editor's pick list. Best-effort; the page works without it.const [allSongs, setAllSongs] = useState([]);@@ -134,11 +147,11 @@ export default function SongEditor() {setLoading(true);setSong(null);getSong(id, { silent: true })- .then((data) => { if (!cancelled) setSong(data?.song || null); })+ .then((data) => { if (!cancelled) setServerSong(data?.song || null); }).catch((err) => { if (!cancelled) toast.error(err?.message || 'Failed to load song'); }).finally(() => { if (!cancelled) setLoading(false); });return () => { cancelled = true; };- }, [id]);+ }, [id, setServerSong]);// Refresh the all-songs list whenever the open song changes — this component// stays mounted across /songs/:id navigation, so a once-on-mount fetch would@@ -185,12 +198,13 @@ export default function SongEditor() {// them from being persisted and later colliding after a reload.sections: (song.sections || []).map(stripTempId),layers: (song.layers || []).map(stripTempId),+ scoreParts: (song.scoreParts || []).map(stripTempId),recordings: (song.recordings || []).map(stripTempId),references: (song.references || []).map(stripTempId),partnerSongIds: song.partnerSongIds || [],};const data = await updateSong(id, patch, { silent: true });- if (data?.song) setSong(data.song);+ if (data?.song) setServerSong(data.song);toast.success('Song saved');return data?.song;}, { errorMessage: 'Failed to save song' });@@ -201,7 +215,7 @@ export default function SongEditor() {// BuiltInBanner gates this behind an inline confirm.const [refreshTemplate, refreshing] = useAsyncAction(async () => {const data = await refreshSongTemplate(id, { silent: true });- if (data?.song) setSong(data.song);+ if (data?.song) setServerSong(data.song);toast.success('Refreshed from the bundled template');return data?.song;}, { errorMessage: 'Failed to refresh from template' });@@ -629,6 +643,16 @@ export default function SongEditor() {{/* Sheet music — live-rendered staff from the lead-sheet notation. */}<SongScoreEditor value={song.score} onChange={(v) => setField('score', v)} />+ {/* Harmony variations — bass / mid / high parts derived from the melody.+ `baseDirty` gates the AI derive (it reads the SAVED base score). */}+ <SongScoreParts+ songId={id}+ baseScore={song.score}+ baseDirty={(song.score || '') !== savedBase.score || (song.key || '') !== savedBase.key}+ scoreParts={song.scoreParts || []}+ onChange={(scoreParts) => setField('scoreParts', scoreParts)}+ />+{/* Notation + notes */}<section className="grid grid-cols-1 gap-4"><div>@@ -672,10 +696,6 @@ function ReadView({ song, setField, onRefreshTemplate, refreshing, partnerSongsconst references = song.references || [];const hasText = (v) => typeof v === 'string' && v.trim().length > 0;const feel = song.rhythmShapeId ? rhythmShapeLabel(song.rhythmShapeId) : '';- // Gate the whole sheet-music section on whether the score has notes. Memoized- // so a recording-driven re-render doesn't re-parse the score each time- // (ScoreSheet parses it again internally only when it actually renders).- const hasScore = useMemo(() => scoreHasMusic(song.score), [song.score]);// Only actually swap to the stacked view when there are partners to stack —// otherwise `?stack=1` with no partners would hide the single-song view and// render nothing.@@ -731,14 +751,10 @@ function ReadView({ song, setField, onRefreshTemplate, refreshing, partnerSongs{/* Sheet music — the rendered staff, full-width so a row of bars fits.Kept at the top with the metronome + recorder so the practice tools- (read the chart, set the tempo, record against it) lead the view. */}- {!showingStack && hasScore && (- <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 text={song.score} />- </div>- </section>+ (read the chart, set the tempo, record against it) lead the view. A+ part switcher appears when the song carries harmony variations. */}+ {!showingStack && (+ <SheetMusicViewer baseScore={song.score} scoreParts={song.scoreParts || []} />)}{/* Vocal takes — metronome + recording/playback, front-and-centre with the@@ -826,6 +842,57 @@ 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.+function SheetMusicViewer({ baseScore, scoreParts = [] }) {+ const tabs = useMemo(() => {+ const out = [];+ if (scoreHasMusic(baseScore)) out.push({ key: 'melody', label: 'Melody', score: baseScore });+ (scoreParts || [])+ .filter((p) => scoreHasMusic(p.score))+ .slice()+ .sort((a, b) => harmonyPartOrder(a.role) - harmonyPartOrder(b.role))+ .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];++ 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>+ )}+ </div>+ <div className="bg-port-card border border-port-border rounded-lg p-4 overflow-x-auto">+ <ScoreSheet key={current.key} text={current.score} />+ </div>+ </section>+ );+}+// One reference: a TikTok video renders as the official embed iframe; any other// URL renders as a link card (label + note + the raw URL).function ReferenceCard({ reference }) {diff --git a/client/src/services/apiSongs.js b/client/src/services/apiSongs.jsindex b63da1202c..b937008de2 100644--- a/client/src/services/apiSongs.js+++ b/client/src/services/apiSongs.js@@ -39,3 +39,10 @@ export const generateSongFor = (id, body = {}, options) =>// AI: critique a stored arrangement → { evaluation, llm }. Read-only server-side.export const evaluateSong = (id, body = {}, options) =>request(`/songs/${enc(id)}/evaluate`, { method: 'POST', body: JSON.stringify(body), ...options });++// AI: derive harmony parts (bass, mid/high harmonies) from the song's base+// melody → { scoreParts, llm }. Not persisted server-side; the client merges the+// returned parts into the editor draft and the user Saves. body: { partIds?,+// providerId?, model? } — partIds optionally restricts which harmony parts.+export const deriveSongParts = (id, body = {}, options) =>+ request(`/songs/${enc(id)}/derive-parts`, { method: 'POST', body: JSON.stringify(body), ...options });diff --git a/scripts/migrations/073-seed-500-miles-score.js b/scripts/migrations/073-seed-500-miles-score.jsindex c8aeae6b98..08209ca595 100644--- a/scripts/migrations/073-seed-500-miles-score.js+++ b/scripts/migrations/073-seed-500-miles-score.js@@ -23,17 +23,23 @@ 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).+// 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.export const SCORE_500_MILES = ['clef: treble',- 'key: C',+ 'key: G','time: 4/4','tempo: 68','',- '| [C] E4q(If) G4q(you) G4q(miss) G4q(the) | [Am] A4h(train) G4q(I\'m) E4q(on) |',- '| [F] F4q(You) A4q(will) A4q(know) A4q(that) | [C] G4h(I) E4q(am) C4q(gone) |',- '| [F] F4q(You) A4q(can) A4q(hear) A4q(the) | [C] G4q(whis-) E4q(tle) C4h(blow) |',- '| [G] D4q(A) F4q(hun-) G4q(dred) rq | [C] C4w(miles) |',+ '| rh [G] D4q(If) D4q(you) |',+ '| [G] B4q.(miss) A4e(the) B4q.(train) A4e(I\'m) |',+ '| [Em] B4h(on) A4q(you) G4q(will) |',+ '| [C] C5q.(know) B4e(that) A4q(I) G4q(am) |',+ '| [Am7] E4h.(gone) 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) |',].join('\n');const fileExists = (path) => stat(path).then(() => true, (err) => {diff --git a/scripts/migrations/075-correct-500-miles-melody.js b/scripts/migrations/075-correct-500-miles-melody.jsnew file mode 100644index 0000000000..c8509cef9b--- /dev/null+++ b/scripts/migrations/075-correct-500-miles-melody.js@@ -0,0 +1,92 @@+/**+ * Correct the built-in "500 Miles" sheet-music melody to the proper G-major+ * transcription (Hedy West lead sheet) for installs that hold the earlier,+ * incorrect C-major backfill.+ *+ * Background:+ * The first sheet-music score shipped for "500 Miles" was a placeholder in+ * C major with the wrong notes (migration 073 backfilled it onto pre-feature+ * installs). The seed has since been corrected to the real melody in G major.+ * A fresh install seeds the correct score directly; migration 073 now backfills+ * the correct score onto installs that never had one. But an install that+ * already persisted the OLD C-major score keeps it — neither path touches it.+ *+ * This migration upgrades that record: if `seed-500-miles.score` still matches+ * the OLD shipped C-major score (line-ending–normalized), replace it with the+ * corrected G-major score and update the key to "G major". A user who edited+ * their score is never clobbered — only the exact old shipped version is+ * upgraded. The user can also pull the latest bundled content any time via the+ * song's "Refresh from template" button.+ *+ * Fresh installs (no file) are a clean no-op. Re-runs detect the corrected+ * score is already present (no longer matches OLD) and skip.+ */++import { readFile, writeFile, stat } from 'fs/promises';+import { join } from 'path';+import { SCORE_500_MILES as NEW_SCORE } from './073-seed-500-miles-score.js';++const SONG_ID = 'seed-500-miles';++// The OLD shipped score — the C-major placeholder migration 073 originally+// backfilled. Kept here (not imported) precisely because 073's constant has been+// updated to the corrected G-major score; this is the fingerprint of the version+// we upgrade FROM.+const OLD_SCORE = [+ 'clef: treble',+ 'key: C',+ 'time: 4/4',+ 'tempo: 68',+ '',+ '| [C] E4q(If) G4q(you) G4q(miss) G4q(the) | [Am] A4h(train) G4q(I\'m) E4q(on) |',+ '| [F] F4q(You) A4q(will) A4q(know) A4q(that) | [C] G4h(I) E4q(am) C4q(gone) |',+ '| [F] F4q(You) A4q(can) A4q(hear) A4q(the) | [C] G4q(whis-) E4q(tle) C4h(blow) |',+ '| [G] D4q(A) F4q(hun-) G4q(dred) rq | [C] C4w(miles) |',+].join('\n');++// Normalize line endings before comparing so a Windows checkout (CRLF) still+// matches the LF-joined shipped string.+const norm = (s) => String(s || '').replace(/\r\n/g, '\n').replace(/\r/g, '\n').trim();++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 075: no data/songs.json — fresh install seeds the correct melody 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 075: 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 075: built-in 500 Miles not present; nothing to correct.');+ return { updated: 0, reason: 'song-absent' };+ }+ if (norm(song.score) !== norm(OLD_SCORE)) {+ console.log('📦 migration 075: 500 Miles score is not the old C-major placeholder (corrected or customized); leaving it untouched.');+ return { updated: 0, reason: 'not-old-score' };+ }++ song.score = NEW_SCORE;+ // Bring the key field in line with the corrected score's key signature.+ song.key = 'G major';+ song.updatedAt = new Date().toISOString();+ await writeFile(path, JSON.stringify(doc, null, 2) + '\n');+ console.log('📦 migration 075: corrected built-in 500 Miles melody to G major.');+ return { updated: 1 };+ },+};diff --git a/scripts/migrations/075-correct-500-miles-melody.test.js b/scripts/migrations/075-correct-500-miles-melody.test.jsnew file mode 100644index 0000000000..fe9f3ae6bb--- /dev/null+++ b/scripts/migrations/075-correct-500-miles-melody.test.js@@ -0,0 +1,97 @@+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 './075-correct-500-miles-melody.js';+import { SCORE_500_MILES as NEW_SCORE } from './073-seed-500-miles-score.js';+import { SEED_SONGS } from '../../server/services/songs.js';++// The OLD C-major placeholder the migration upgrades FROM (kept in lockstep with+// the constant inside the migration; this is the version we detect and replace).+const OLD_SCORE = [+ 'clef: treble',+ 'key: C',+ 'time: 4/4',+ 'tempo: 68',+ '',+ '| [C] E4q(If) G4q(you) G4q(miss) G4q(the) | [Am] A4h(train) G4q(I\'m) E4q(on) |',+ '| [F] F4q(You) A4q(will) A4q(know) A4q(that) | [C] G4h(I) E4q(am) C4q(gone) |',+ '| [F] F4q(You) A4q(can) A4q(hear) A4q(the) | [C] G4q(whis-) E4q(tle) C4h(blow) |',+ '| [G] D4q(A) F4q(hun-) G4q(dred) rq | [C] C4w(miles) |',+].join('\n');++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 075 — correct 500 Miles melody to G major', () => {+ let rootDir;+ let songsPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-075-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ songsPath = join(rootDir, 'data', 'songs.json');+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('the corrected score equals the shipped seed (no drift)', () => {+ const seed = SEED_SONGS.find((s) => s.id === 'seed-500-miles');+ expect(seed.score).toBe(NEW_SCORE);+ expect(seed.key).toBe('G major');+ });++ it('no-ops when data/songs.json is missing (fresh install seeds the correct melody)', async () => {+ const result = await migration.up({ rootDir });+ expect(result).toEqual({ updated: 0, reason: 'no-file' });+ expect(existsSync(songsPath)).toBe(false);+ });++ it('upgrades a record holding the old C-major placeholder', async () => {+ writeJson(songsPath, {+ songs: [{ id: 'seed-500-miles', key: 'C major', score: OLD_SCORE, updatedAt: '2026-01-01T00:00:00.000Z' }],+ });+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(1);+ const song = findSong(songsPath, 'seed-500-miles');+ expect(song.score).toBe(NEW_SCORE);+ expect(song.key).toBe('G major');+ expect(song.updatedAt).not.toBe('2026-01-01T00:00:00.000Z'); // bumped+ });++ it('matches the old score across CRLF line endings', async () => {+ writeJson(songsPath, { songs: [{ id: 'seed-500-miles', score: OLD_SCORE.replace(/\n/g, '\r\n') }] });+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(1);+ expect(findSong(songsPath, 'seed-500-miles').score).toBe(NEW_SCORE);+ });++ it('never clobbers a user-authored score', async () => {+ writeJson(songsPath, { songs: [{ id: 'seed-500-miles', score: '| C4w(mine) |' }] });+ const result = await migration.up({ rootDir });+ expect(result).toEqual({ updated: 0, reason: 'not-old-score' });+ expect(findSong(songsPath, 'seed-500-miles').score).toBe('| C4w(mine) |');+ });++ it('is idempotent — re-running over the corrected score is a no-op', async () => {+ writeJson(songsPath, { songs: [{ id: 'seed-500-miles', key: 'G major', score: NEW_SCORE }] });+ const result = await migration.up({ rootDir });+ expect(result).toEqual({ updated: 0, reason: 'not-old-score' });+ });++ it('no-ops when 500 Miles is absent (user deleted it)', async () => {+ writeJson(songsPath, { songs: [{ id: 'song-custom', score: OLD_SCORE }] });+ 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 9e21e4de8c..3da1358591 100644--- a/server/lib/songCraftRef.js+++ b/server/lib/songCraftRef.js@@ -41,3 +41,20 @@ 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.+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.' },+];++// The parts the derive tool generates (all but the melody, which is the input).+export const DERIVABLE_HARMONY_PARTS = HARMONY_PARTS.filter((p) => p.derivable);diff --git a/server/routes/songs.js b/server/routes/songs.jsindex 44f5da12b6..ed018e6329 100644--- a/server/routes/songs.js+++ b/server/routes/songs.js@@ -18,7 +18,7 @@ import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import * as svc from '../services/songs.js';-import { generateSong, evaluateSong } from '../services/songsAI.js';+import { generateSong, evaluateSong, deriveSongParts } from '../services/songsAI.js';const router = Router();@@ -52,6 +52,16 @@ const recordingSchema = z.object({createdAt: z.string().optional(),});+// A sheet-music part — a harmony variation of the base score, in the same+// lead-sheet DSL. `score` is required (a part without notation is meaningless);+// `role` is a HARMONY_PARTS id when known but free-text-safe.+const scorePartSchema = z.object({+ id: str(svc.ID_MAX_LENGTH).optional(),+ label: str(svc.LABEL_MAX_LENGTH).optional().default(''),+ role: str(svc.ID_MAX_LENGTH).optional().default(''),+ score: str(svc.SCORE_MAX_LENGTH),+});+// A reference link/video (e.g. a TikTok performance). `url` is required; the// client renders TikTok urls as embeds and everything else as a link.const referenceSchema = z.object({@@ -77,6 +87,9 @@ const songInputSchema = z.object({// Sheet-music notation (PortOS lead-sheet DSL) — bounded free text; the client// parses/renders it. Longer cap than `notation` since a full score is verbose.score: str(svc.SCORE_MAX_LENGTH).optional(),+ // Harmony variations of the base score (bass, mid/high harmonies). The service+ // drops parts with no notation and defaults the label; the schema bounds the list.+ scoreParts: z.array(scorePartSchema).max(svc.SCORE_PARTS_MAX).optional(),notes: str(svc.FIELD_MAX_LENGTH).optional(),learned: z.boolean().optional(),sections: z.array(sectionSchema).max(svc.SECTIONS_MAX).optional(),@@ -107,6 +120,14 @@ const evaluateSchema = z.object({providerId: optProvider,model: optProvider,});+// Derive harmony parts from the song's base score. `partIds` optionally restricts+// which harmony parts to generate (a HARMONY_PARTS id list); the service defaults+// to the full derivable set and only ever derives harmony (never the melody).+const derivePartsSchema = z.object({+ partIds: z.array(str(svc.ID_MAX_LENGTH)).max(svc.SCORE_PARTS_MAX).optional(),+ providerId: optProvider,+ model: optProvider,+});// Map a service error (carries a `code`) to the right HTTP status. Without// this, asyncHandler defaults everything to 500.@@ -192,4 +213,18 @@ router.post('/:id/evaluate', asyncHandler(async (req, res) => {res.json(result);}));+// POST /api/songs/:id/derive-parts → derive harmony parts (bass, mid/high+// harmonies) from the song's base melody. Returns { scoreParts, llm }; the+// client merges the parts into the editor draft (does NOT auto-save), matching+// the generate/expand flow. 400 if the song has no base score to derive from.+router.post('/:id/derive-parts', asyncHandler(async (req, res) => {+ const body = validateRequest(derivePartsSchema, req.body || {});+ const song = await svc.getSong(req.params.id);+ if (!song) throw new ServerError('Song not found', { status: 404, code: svc.ERR_NOT_FOUND });+ const result = await deriveSongParts({+ song, partIds: body.partIds, providerId: body.providerId, model: body.model,+ });+ res.json(result);+}));+export default router;diff --git a/server/routes/songs.test.js b/server/routes/songs.test.jsindex bf3749e4d5..add542f0d5 100644--- a/server/routes/songs.test.js+++ b/server/routes/songs.test.js@@ -24,6 +24,7 @@ vi.mock('../services/songs.js', async () => {const aiMocks = vi.hoisted(() => ({generateSong: vi.fn(),evaluateSong: vi.fn(),+ deriveSongParts: vi.fn(),}));vi.mock('../services/songsAI.js', () => aiMocks);@@ -235,4 +236,50 @@ describe('songs route', () => {expect(res.status).toBe(404);expect(aiMocks.evaluateSong).not.toHaveBeenCalled();});++ it('PUT /:id accepts a scoreParts array', async () => {+ mocks.updateSong.mockResolvedValue({ id: 'song-1' });+ const res = await request(makeApp())+ .put('/api/songs/song-1')+ .send({ scoreParts: [{ label: 'Bass', role: 'bass', score: '| G2w(x) |' }] });+ expect(res.status).toBe(200);+ const [, patch] = mocks.updateSong.mock.calls[0];+ expect(patch.scoreParts).toHaveLength(1);+ expect(patch.scoreParts[0].score).toBe('| G2w(x) |');+ });++ it('PUT /:id rejects a scorePart without a score', async () => {+ const res = await request(makeApp())+ .put('/api/songs/song-1')+ .send({ scoreParts: [{ label: 'Bass', role: 'bass' }] });+ expect(res.status).toBe(400);+ expect(mocks.updateSong).not.toHaveBeenCalled();+ });++ it('POST /:id/derive-parts returns the derived scoreParts', async () => {+ mocks.getSong.mockResolvedValue({ id: 'song-1', title: '500 Miles', score: '| [G] B4q |' });+ aiMocks.deriveSongParts.mockResolvedValue({+ scoreParts: [{ role: 'bass', label: 'Bass', score: '| G2w |' }], llm: { provider: 'p' },+ });+ const res = await request(makeApp()).post('/api/songs/song-1/derive-parts').send({});+ expect(res.status).toBe(200);+ expect(res.body.scoreParts).toHaveLength(1);+ const [arg] = aiMocks.deriveSongParts.mock.calls[0];+ expect(arg.song.id).toBe('song-1');+ });++ it('POST /:id/derive-parts 404s when the song is missing', async () => {+ mocks.getSong.mockResolvedValue(null);+ const res = await request(makeApp()).post('/api/songs/song-x/derive-parts').send({});+ expect(res.status).toBe(404);+ expect(aiMocks.deriveSongParts).not.toHaveBeenCalled();+ });++ it('POST /:id/derive-parts forwards a partIds restriction', async () => {+ mocks.getSong.mockResolvedValue({ id: 'song-1', score: '| [G] B4q |' });+ aiMocks.deriveSongParts.mockResolvedValue({ scoreParts: [], llm: {} });+ await request(makeApp()).post('/api/songs/song-1/derive-parts').send({ partIds: ['bass', 'high-harmony-1'] });+ const [arg] = aiMocks.deriveSongParts.mock.calls[0];+ expect(arg.partIds).toEqual(['bass', 'high-harmony-1']);+ });});diff --git a/server/services/songs.js b/server/services/songs.jsindex 358ac161b9..2d623825ac 100644--- a/server/services/songs.js+++ b/server/services/songs.js@@ -38,6 +38,7 @@ export const ARTIST_MAX_LENGTH = 200;export const KEY_MAX_LENGTH = 24;export const FIELD_MAX_LENGTH = 4000; // lyrics body / general notesexport const SCORE_MAX_LENGTH = 8000; // sheet-music notation (lead-sheet DSL)+export const SCORE_PARTS_MAX = 12; // harmony variations of the sheet musicexport const LABEL_MAX_LENGTH = 120; // section + layer labelsexport const PART_MAX_LENGTH = 60; // layer voice (e.g. "Bass")export const ID_MAX_LENGTH = 60; // rhythm-shape / layer ids@@ -137,6 +138,27 @@ const sanitizeReference = (r) => {};};+// One sheet-music part — a harmony variation of the song's base score+// ({ id, label, role, score }). `score` is the PortOS lead-sheet DSL (same+// format as the base `score`); a part without notation is meaningless, so it's+// dropped. `role` references a songCraft HARMONY_PARTS id when known (bass,+// mid-harmony-1, high-harmony-1 …) but is free-text-safe so a newer/older client+// vocabulary can't 400. `label` defaults from the role/`Part` so a part card is+// never headerless.+const sanitizeScorePart = (p) => {+ if (!p || typeof p !== 'object') return null;+ const score = trimField(p.score, SCORE_MAX_LENGTH);+ if (!score) return null;+ const label = trimField(p.label, LABEL_MAX_LENGTH);+ const role = trimField(p.role, ID_MAX_LENGTH);+ return {+ id: trimField(p.id, ID_MAX_LENGTH) || `part-${randomUUID().slice(0, 8)}`,+ label: label || 'Part',+ role,+ score,+ };+};+const sanitizeList = (arr, fn, max) =>(Array.isArray(arr) ? arr : []).map(fn)@@ -174,6 +196,11 @@ export const sanitizeSong = (raw) => {// scoreNotation.js). A bounded free-text string — the client parses + renders// it; the server only length-caps it, so a newer/older DSL revision can't 400.score: trimField(raw.score, SCORE_MAX_LENGTH),+ // Harmony variations of the base `score` (bass, mid/high harmonies …), each+ // its own lead-sheet DSL. Absent ⇒ [] — purely additive, so an older peer or+ // a pre-feature record reads back as a song with no parts (no migration of+ // the on-disk shape needed; the field simply appears when the user adds one).+ scoreParts: sanitizeList(raw.scoreParts, sanitizeScorePart, SCORE_PARTS_MAX),notes: trimField(raw.notes, FIELD_MAX_LENGTH),learned: raw.learned === true,sections: sanitizeList(raw.sections, sanitizeSection, SECTIONS_MAX),@@ -199,23 +226,29 @@ export const SEED_SONGS = [id: 'seed-500-miles',title: '500 Miles',artist: 'Peter, Paul and Mary',- key: 'C major',+ key: 'G major',tempo: 68,rhythmShapeId: 'slow-4-4',- notation: 'Verse chords (key of C): C — Am — F — G, four slow bars per line. A gentle 4/4 ballad; let each line breathe across the bar rather than chopping it.',+ 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. A singable arrangement in C (edit it in the Sheet music tab); see- // client/src/lib/scoreNotation.js for the format.+ // 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:+ // migration 073's SCORE_500_MILES constant must stay identical to this (the+ // 073 drift test asserts it) — update both together.score: ['clef: treble',- 'key: C',+ 'key: G','time: 4/4','tempo: 68','',- '| [C] E4q(If) G4q(you) G4q(miss) G4q(the) | [Am] A4h(train) G4q(I\'m) E4q(on) |',- '| [F] F4q(You) A4q(will) A4q(know) A4q(that) | [C] G4h(I) E4q(am) C4q(gone) |',- '| [F] F4q(You) A4q(can) A4q(hear) A4q(the) | [C] G4q(whis-) E4q(tle) C4h(blow) |',- '| [G] D4q(A) F4q(hun-) G4q(dred) rq | [C] C4w(miles) |',+ '| rh [G] D4q(If) D4q(you) |',+ '| [G] B4q.(miss) A4e(the) B4q.(train) A4e(I\'m) |',+ '| [Em] B4h(on) A4q(you) G4q(will) |',+ '| [C] C5q.(know) B4e(that) A4q(I) G4q(am) |',+ '| [Am7] E4h.(gone) 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) |',].join('\n'),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,@@ -460,7 +493,7 @@ export async function updateSong(id, patch) {// Merge field-by-field so an absent key preserves the stored value while a// present key (including empty string / empty array) applies the change.const merged = { ...songs[idx] };- for (const key of ['title', 'artist', 'key', 'tempo', 'rhythmShapeId', 'notation', 'score', 'notes', 'learned', 'sections', 'layers', 'recordings', 'references', 'partnerSongIds']) {+ for (const key of ['title', 'artist', 'key', 'tempo', 'rhythmShapeId', 'notation', 'score', 'scoreParts', 'notes', 'learned', 'sections', 'layers', 'recordings', 'references', 'partnerSongIds']) {if (key in patch) merged[key] = patch[key];}merged.id = id;diff --git a/server/services/songs.test.js b/server/services/songs.test.jsindex ec07925a2e..2a4aa719d9 100644--- a/server/services/songs.test.js+++ b/server/services/songs.test.js@@ -190,6 +190,27 @@ describe('songs service', () => {expect(svc.sanitizeSong({ id: 'x', score: long }).score.length).toBe(svc.SCORE_MAX_LENGTH);});+ it('sanitizes scoreParts — drops scoreless entries, mints ids, defaults labels', () => {+ const song = svc.sanitizeSong({+ id: 'x',+ scoreParts: [+ { id: 'part-keep', label: 'Bass', role: 'bass', score: '| G2w(x) |' },+ { role: 'mid-harmony-1', score: ' | B4q | ' }, // no id/label → minted id, default label+ { label: 'No notes', role: 'bass' }, // no score → dropped+ { score: ' ' }, // blank score → dropped+ ],+ });+ expect(song.scoreParts).toHaveLength(2);+ expect(song.scoreParts[0].id).toBe('part-keep');+ expect(song.scoreParts[1].id).toMatch(/^part-/);+ expect(song.scoreParts[1].label).toBe('Part'); // default when blank+ expect(song.scoreParts[1].score).toBe('| B4q |'); // trimmed+ });++ it('defaults scoreParts to [] when absent (backward compatible)', () => {+ expect(svc.sanitizeSong({ id: 'x' }).scoreParts).toEqual([]);+ });+it('sanitizes references — drops urlless entries, mints ids', () => {const song = svc.sanitizeSong({id: 'x',diff --git a/server/services/songsAI.js b/server/services/songsAI.jsindex a40de1eef8..78a43c1368 100644--- a/server/services/songsAI.js+++ b/server/services/songsAI.js@@ -24,9 +24,11 @@ import { extractJson } from '../lib/jsonExtract.js';import { ServerError } from '../lib/errorHandler.js';import {RHYTHM_SHAPES, VOICE_LAYERS, DIRGE_RHYTHM_SHAPES,+ HARMONY_PARTS, DERIVABLE_HARMONY_PARTS,} from '../lib/songCraftRef.js';import {sanitizeSong, FIELD_MAX_LENGTH, SECTIONS_MAX, LAYERS_MAX,+ SCORE_MAX_LENGTH, SCORE_PARTS_MAX,} from './songs.js';// Strip dangerous control chars that would corrupt the prompt or invite@@ -229,3 +231,116 @@ export function normalizeVerdict(raw) {suggestions: strList(raw?.suggestions),};}++// --- Derive harmony parts --------------------------------------------------+// A compact spec of the PortOS lead-sheet DSL so the model can both READ the base+// melody and WRITE parts in the same format. Mirrors client/src/lib/+// scoreNotation.js — the format is small enough to inline; the worked base score+// in the prompt is the real teacher.+const LEAD_SHEET_SPEC = `PortOS lead-sheet notation:+- Header lines (one per line, before the music): "clef: treble|bass", "key: G", "time: 4/4", "tempo: 68".+- Music: measures separated by "|". Notes are space-separated within a bar.+- A note token is [chord]? PITCH DURATION dots? (lyric)? e.g. [G] B4q.(miss)+ - PITCH = letter A–G + optional accidental (#, b, n) + octave digit (C4 = middle C). e.g. C4, F#4, Bb3.+ - DURATION = w h q e s t (whole, half, quarter, eighth, sixteenth, 32nd). Trailing "." dots it (q. = 1.5 beats).+ - 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.+const partsBrief = (parts) =>+ parts.map((p) => `- ${p.id} ("${p.label}", ${p.register} register): ${p.interval}`).join('\n');++const isDerivedPartsShape = (o) =>+ o && typeof o === 'object' && Array.isArray(o.parts);++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.++# Format (the melody below uses it; your output must too)+${LEAD_SHEET_SPEC}++# Base melody — key: ${key}+${baseScore}++# Parts to write+${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.++# Output contract+Return ONLY a JSON object (no prose, no markdown fence):+{+ "parts": [+ { "id": "bass", "score": "clef: bass\\nkey: ${key.split(/\\s/)[0]}\\ntime: 4/4\\ntempo: 68\\n\\n| ... |" }+ ]+}+Include exactly one entry per requested part id, each a complete lead-sheet string (headers + measures). Each score under ${SCORE_MAX_LENGTH} characters.`;+};++// Project the model's parts onto the canonical scorePart shape. Matches each+// returned id to a known HARMONY_PARTS entry for its label (falling back to the+// model's label, then the id), length-caps the score, and drops parts with no+// notation. Bounded to SCORE_PARTS_MAX.+const normalizeDerivedParts = (rawParts) =>+ (Array.isArray(rawParts) ? rawParts : [])+ .map((p) => {+ if (!p || typeof p !== 'object') return null;+ const score = typeof p.score === 'string' ? p.score.trim().slice(0, SCORE_MAX_LENGTH) : '';+ if (!score) return null;+ const id = typeof p.id === 'string' ? p.id.trim() : '';+ const known = HARMONY_PARTS.find((h) => h.id === id);+ const label = known?.label+ || (typeof p.label === 'string' && p.label.trim())+ || id+ || 'Part';+ return { role: known?.id || id, label, score };+ })+ .filter(Boolean)+ .slice(0, SCORE_PARTS_MAX);++/**+ * Derive harmony parts (bass, mid/high harmonies) from a song's base melody.+ * Returns `{ scoreParts, llm }` — the parts are NOT persisted; the route hands+ * them back for the client to merge into the editor draft (the user reviews ++ * Saves), matching the generate/expand flow. `partIds` (optional) restricts the+ * set; default is every derivable harmony part. Throws 400 if the song has no+ * base score to derive from.+ */+export async function deriveSongParts({ song, partIds, providerId, model } = {}) {+ if (!song || typeof song !== 'object') {+ throw new ServerError('A song is required to derive parts', { status: 400, code: 'VALIDATION_ERROR' });+ }+ if (!clean(song.score)) {+ throw new ServerError('This song has no base sheet music to derive harmony from. Add a melody in the Sheet music editor first.', { status: 400, code: 'NO_BASE_SCORE' });+ }+ // Restrict to the requested ids (when given) but only ever derivable parts —+ // never the melody (that's the input). Empty/unknown selection falls back to+ // the full derivable set so a drifted client can't ask for nothing.+ const wanted = Array.isArray(partIds) && partIds.length+ ? DERIVABLE_HARMONY_PARTS.filter((p) => partIds.includes(p.id))+ : DERIVABLE_HARMONY_PARTS;+ const parts = wanted.length ? wanted : DERIVABLE_HARMONY_PARTS;++ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });+ assertProvider(provider, { message: 'No AI provider available to derive parts', code: 'NO_PROVIDER' });++ const prompt = buildDerivePrompt({ song, parts });+ const { text: raw, model: ranModel } = await runPromptThroughProvider({+ provider, model: selectedModel, prompt, source: 'song-derive-parts',+ });++ const parsed = parseOrThrow(raw, isDerivedPartsShape, 'part derivation');+ const scoreParts = normalizeDerivedParts(parsed.parts);+ if (!scoreParts.length) {+ throw new ServerError('The AI returned no usable harmony parts. Try a different model or rerun.', { status: 502, code: 'LLM_EMPTY' });+ }+ console.log(`🎶 Derived ${scoreParts.length} harmony part(s) for "${clean(song.title) || song.id}" via ${provider.id}/${ranModel || 'default'}`);+ return { scoreParts, llm: { provider: provider.id, model: ranModel || null } };+}diff --git a/server/services/songsAI.test.js b/server/services/songsAI.test.jsindex 8daa3d69ea..a21a5a8de9 100644Binary files a/server/services/songsAI.test.js and b/server/services/songsAI.test.js differ