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: ship four traditional rounds and a cross-song round-stack view
[._.]/ Adam Eivy5b9b38a7f8af
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 4ead807106..d519b9aee9 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -11,6 +11,7 @@- **Manuscript editorial review: "Start fresh" re-run mode** — re-running the editorial pass in the manuscript editor previously always *merged*, leaving every prior open note in place even when a later pass no longer flagged it. A new "Start fresh" checkbox next to "Run editorial review" reconciles the open list against the latest pass: open notes it still finds stay open, open notes it no longer finds are auto-dismissed, and genuinely-new findings are added. Your accepted and dismissed decisions are left untouched. Clearing is done by moving notes to dismissed (never by deleting them), so the change syncs correctly across federated machines instead of being resurrected by a peer. Merge stays the default.- **Manuscript editor: editorial feedback is now shown in-context, not just in a sidebar** — instead of scrolling a disconnected list of notes, each editorial comment is highlighted directly on the text it points to. A header toggle switches between two modes: **Live** (Grammarly-style — the manuscript stays fully editable and each anchored note shows as a severity-toned underline; click the underlined text or its tag to pop the note's card right there with Generate-fix / Accept / Dismiss) and **Review** (a read-through where the prose is annotated and clicking a highlight expands the note inline, with a per-section Edit toggle to drop into free editing). The right sidebar becomes a filterable index (by severity, with open / accepted / dismissed groups and a "located in text" count) that scrolls to and opens any note. The editor now focuses **one issue at a time** with a deep-linkable tab strip (`…/manuscript/<issueNumber>`, each tab badged with its open-note count) instead of one page-length scroll of every issue. Suggested edits can be reviewed as a **side-by-side before/after diff** (default) or the prior stacked inline diff, and a new **Impact preview** shows, per affected issue, how accepting the selected fixes changes the whole manuscript before you commit to them (a single fix can span multiple issues). Notes whose anchor text no longer matches the draft degrade gracefully — they stay listed in the sidebar with no in-text highlight rather than disappearing.- **Songs: a sheet-music view & editor** — each song can now carry real sheet music, rendered as an engraved staff (treble or bass clef, key & time signature, notes with stems/flags/dots, accidentals, ledger lines, rests, chord symbols above and lyrics beneath). It's drawn entirely in-house — no third-party music-notation library — from a small, readable text format ("PortOS lead-sheet notation": `clef:` / `key:` / `time:` / `tempo:` headers, then measures of `[chord] pitch+duration (lyric)` like `[C] E4q(If) G4q(you)`). The **Edit** tab gives you a textarea with a live-updating staff preview, a collapsible format guide, and per-measure beat-count feedback; the **View** tab shows the rendered score full-width above the lyrics. The built-in "500 Miles" now ships with its verse melody, chords, and lyrics as a worked example you can edit and learn from.+- **Songs: built-in singing rounds + a round-stack (quodlibet) view** — four traditional rounds now ship as built-in songs — **Hey Ho Nobody Home**, **Ah Poor Bird** (with an alternate "Oh poor bird, why art thou…" lyric set), **Rose Rose Rose Red**, and **Zum Gali Gali** — each with its melody in sheet music, lyrics, and canon-entry voice layers. Songs can now declare the partners they're sung with: the first three are the classic *quodlibet* — they share one minor chord cycle and can be sung at the same time. In **Edit**, a "Sings with" picker links partner songs; in **View**, a **Stack parts** toggle (linkable as `?stack=1`) renders every partner's melody and lyrics stacked as simultaneous parts and plays their recorded takes layered together on one audio clock. Existing installs receive the four rounds via a migration; the links round-trip and are restorable via "Refresh from template."- **Songs: a read/perform view, built-in defaults, and reference videos** — the song page now has a **View / Edit** toggle (mode lives in the URL, so each view is linkable). **View** is a clean, desktop-wide performance layout — lyrics rendered in full with no cramped sub-scrolling boxes, sections laid out side-by-side to use the screen and cut vertical scrolling, with the recorder kept front-and-centre for playing/recording; **Edit** is the existing workbench, now wider with a two-column lyric grid. Shipped example songs are tagged **Built-in default** (a badge in the Songs list and a banner in the editor) with a **Refresh from template** button that restores the latest bundled lyrics, arrangement, and references while preserving your own recordings and learned progress — so an install that already has an older copy of a default song can renew it on demand. Songs can also carry **reference material**: paste a link to a performance or tutorial, and TikTok video links play inline as embeds in the View tab (other links render as link cards). The built-in "500 Miles" ships with TikTok reference performances and its full set of lyrics.## Changed@@ -27,6 +28,7 @@## Fixed+- **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.- **MortalLoom iCloud writes no longer fail when the data file has been offloaded** — under macOS "Optimize Mac Storage," iCloud can evict `MortalLoom.json` to the cloud (a dataless placeholder) hours after PortOS booted. A write would then fail to read the evicted file within the brief retry window and refuse to overwrite it ("MortalLoom store is unreadable; refusing to overwrite") rather than risk truncating your data — but that also blocked the write entirely. PortOS now pre-warms the file on demand: before refusing, it runs `brctl download` and waits for the file to materialize, then re-reads and proceeds. It also detects a legacy `.icloud` placeholder shadowing the real path so it won't seed a fresh (empty) store on top of evicted data. If the file is genuinely corrupt, or the device is offline and can't download it, PortOS still safely refuses rather than clobbering the iCloud copy. The fire-and-forget boot/settings-change pinning remains as the first line of defense.- **[issue-978] Apps no longer get stuck reading "in review" after a no-op idle check** — when the Chief of Staff's idle review picked an app but had nothing to actually do (no claimable plan item, no new commits or PRs to watch), the app could stay marked as under review until a restart or cleanup pass cleared it. Idle checks that find no work now release the app right away while still spacing out how often it's rechecked.diff --git a/client/src/components/songs/RoundStack.jsx b/client/src/components/songs/RoundStack.jsxnew file mode 100644index 0000000000..68190c35cc--- /dev/null+++ b/client/src/components/songs/RoundStack.jsx@@ -0,0 +1,128 @@+/**+ * RoundStack — render several songs as simultaneous parts (a quodlibet / round+ * stack). Rounds like "Hey Ho Nobody Home", "Ah Poor Bird" and "Rose Rose Rose+ * Red" share one chord cycle and are sung at the same time; this view stacks+ * each partner song's melody (ScoreSheet) and lyrics in one column so a singer+ * can see every part at once, and plays the recorded takes from ALL of them+ * together on a single AudioContext.+ *+ * Read-only. It reuses ScoreSheet (the same SVG staff the editor renders) and+ * createLayeredPlayer (the within-song mixer) widened across songs — no new+ * rendering or audio machinery. `songs` is the primary song followed by its+ * resolved partners; the caller fetches the partner records.+ */++import { useState, useRef, useEffect, useMemo, useCallback } from 'react';+import { Link } from 'react-router-dom';+import { Play, Square, Music, Layers } from 'lucide-react';+import ScoreSheet from './ScoreSheet';+import { scoreHasMusic } from '../../lib/scoreNotation';+import { createLayeredPlayer } from '../../lib/songPlayback';+import { getUploadUrl } from '../../services/api';+import { rhythmShapeLabel } from '../../lib/songCraft';++const hasText = (v) => typeof v === 'string' && v.trim().length > 0;++export default function RoundStack({ songs = [] }) {+ const [playing, setPlaying] = useState(false);+ const playerRef = useRef(null);++ // Every saved take across all stacked songs, keyed by a song-namespaced id so+ // two songs' recordings can't collide in the mixer's id map.+ const takes = useMemo(() => songs.flatMap((s) => (s.recordings || []).map((r) => ({+ id: `${s.id}:${r.id}`,+ url: getUploadUrl(r.filename),+ muted: r.muted,+ }))), [songs]);+ const audibleCount = useMemo(() => takes.filter((t) => !t.muted).length, [takes]);++ // Stop and release the mixer on unmount or when the take set changes (a new+ // recording elsewhere shouldn't keep an old mix playing).+ useEffect(() => () => { playerRef.current?.stop(); }, []);++ const stop = useCallback(() => {+ playerRef.current?.stop();+ setPlaying(false);+ }, []);++ const playAll = useCallback(async () => {+ playerRef.current?.stop();+ const player = createLayeredPlayer(takes);+ player.onEnded(() => setPlaying(false));+ playerRef.current = player;+ setPlaying(true);+ await player.play();+ }, [takes]);++ if (songs.length === 0) return null;++ return (+ <section className="space-y-3">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <h2 className="flex items-center gap-2 text-sm font-semibold text-white">+ <Layers size={15} className="text-port-accent" /> Round stack — {songs.length} parts together+ </h2>+ {audibleCount > 0 && (+ <button+ type="button"+ onClick={playing ? stop : playAll}+ 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"+ >+ {playing ? <Square size={14} /> : <Play size={14} />}+ {playing ? 'Stop' : `Play all parts (${audibleCount})`}+ </button>+ )}+ </div>+ <p className="text-xs text-gray-500">+ These rounds share a chord cycle — each line is a different melody sung at the same time. Record a take on each+ song, then play them stacked.+ </p>++ <div className="space-y-4">+ {songs.map((s, i) => {+ const feel = s.rhythmShapeId ? rhythmShapeLabel(s.rhythmShapeId) : '';+ const sections = s.sections || [];+ return (+ <div key={s.id} className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">+ <div className="flex flex-wrap items-baseline justify-between gap-2">+ <h3 className="flex items-center gap-2 text-sm font-semibold text-white">+ <Music size={14} className="text-port-accent shrink-0" />+ {/* The primary song is the one being viewed; partners link out. */}+ {i === 0 ? (+ <span>{s.title || 'Untitled song'}</span>+ ) : (+ <Link to={`/songs/${s.id}`} className="hover:text-port-accent transition-colors">+ {s.title || 'Untitled song'}+ </Link>+ )}+ </h3>+ <span className="text-xs text-gray-500">+ {[hasText(s.key) && s.key, feel].filter(Boolean).join(' · ')}+ </span>+ </div>++ {scoreHasMusic(s.score) && (+ <div className="overflow-x-auto">+ <ScoreSheet text={s.score} />+ </div>+ )}++ {sections.length > 0 && (+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ {sections.map((sec) => (+ <div key={sec.id}>+ <h4 className="text-xs font-semibold uppercase tracking-wide text-port-accent mb-1">{sec.label || 'Section'}</h4>+ {hasText(sec.lyrics)+ ? <p className="text-sm text-gray-100 whitespace-pre-wrap leading-relaxed">{sec.lyrics}</p>+ : <p className="text-xs text-gray-600 italic">No lyrics</p>}+ </div>+ ))}+ </div>+ )}+ </div>+ );+ })}+ </div>+ </section>+ );+}diff --git a/client/src/components/songs/RoundStack.test.jsx b/client/src/components/songs/RoundStack.test.jsxnew file mode 100644index 0000000000..0b7193b1d4--- /dev/null+++ b/client/src/components/songs/RoundStack.test.jsx@@ -0,0 +1,76 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent } from '@testing-library/react';+import { MemoryRouter } from 'react-router-dom';++// Mock the audio mixer — jsdom has no Web Audio. Capture the takes it receives+// so we can assert RoundStack flattens recordings across ALL stacked songs.+const playerCalls = vi.hoisted(() => ({ takes: null, play: null, stop: null }));+vi.mock('../../lib/songPlayback', () => ({+ createLayeredPlayer: (takes) => {+ playerCalls.takes = takes;+ playerCalls.play = vi.fn().mockResolvedValue(undefined);+ playerCalls.stop = vi.fn();+ return { play: playerCalls.play, stop: playerCalls.stop, onEnded: vi.fn() };+ },+}));+// getUploadUrl is the only thing RoundStack needs from the api barrel.+vi.mock('../../services/api', () => ({ getUploadUrl: (f) => `/api/uploads/${f}` }));++import RoundStack from './RoundStack.jsx';++const SCORE_A = ['clef: treble', 'key: C', 'time: 4/4', '', '| D4q(Hey) D4q(ho) D4h(home) |'].join('\n');+const SCORE_B = ['clef: treble', 'key: C', 'time: 4/4', '', '| F4q(Ah) F4q(poor) F4h(bird) |'].join('\n');++const SONGS = [+ {+ id: 'seed-hey-ho-nobody-home', title: 'Hey Ho Nobody Home', key: 'D minor', score: SCORE_A,+ sections: [{ id: 's1', label: 'Round', lyrics: 'Hey ho nobody home' }],+ recordings: [{ id: 'rec-1', filename: 'a.wav', muted: false }],+ },+ {+ id: 'seed-ah-poor-bird', title: 'Ah Poor Bird', key: 'D minor', score: SCORE_B,+ sections: [{ id: 's2', label: 'Verse', lyrics: 'Ah poor bird' }],+ recordings: [{ id: 'rec-2', filename: 'b.wav', muted: false }],+ },+];++const renderStack = (songs) => render(+ <MemoryRouter><RoundStack songs={songs} /></MemoryRouter>,+);++describe('RoundStack', () => {+ beforeEach(() => { playerCalls.takes = null; });++ it('renders nothing for an empty list', () => {+ const { container } = renderStack([]);+ expect(container.firstChild).toBeNull();+ });++ it('renders a score and lyrics for each stacked song', () => {+ renderStack(SONGS);+ expect(screen.getByText('Hey Ho Nobody Home')).toBeTruthy();+ expect(screen.getByText('Ah Poor Bird')).toBeTruthy();+ expect(screen.getByText('Hey ho nobody home')).toBeTruthy();+ expect(screen.getByText('Ah poor bird')).toBeTruthy();+ // One rendered staff per song.+ expect(screen.getAllByLabelText('Sheet music notation')).toHaveLength(2);+ });++ it('plays the recorded takes from every song together', () => {+ renderStack(SONGS);+ fireEvent.click(screen.getByRole('button', { name: /Play all parts/i }));+ expect(playerCalls.takes).toHaveLength(2);+ // Ids are namespaced by song so two songs' takes can't collide in the mixer.+ expect(playerCalls.takes.map((t) => t.id)).toEqual([+ 'seed-hey-ho-nobody-home:rec-1',+ 'seed-ah-poor-bird:rec-2',+ ]);+ expect(playerCalls.play).toHaveBeenCalled();+ });++ it('hides the play button when no song has an audible take', () => {+ const muted = SONGS.map((s) => ({ ...s, recordings: [] }));+ renderStack(muted);+ expect(screen.queryByRole('button', { name: /Play all parts/i })).toBeNull();+ });+});diff --git a/client/src/components/songs/ScoreSheet.jsx b/client/src/components/songs/ScoreSheet.jsxindex cd7005be6e..a0bed7338b 100644--- a/client/src/components/songs/ScoreSheet.jsx+++ b/client/src/components/songs/ScoreSheet.jsx@@ -42,7 +42,9 @@ const BEAT_PX = 30; // horizontal px per quarter-note beatconst MAX_STRETCH = 1.45; // cap row justification so a short row isn't blown outconst ROW_TOP_PAD = 34; // room above the staff for chord symbols-const ROW_STAFF_TO_LYRIC = 30; // room below the staff for lyrics+const ROW_STAFF_TO_LYRIC = 48; // room below the staff for lyrics + below-staff notes+const LYRIC_BELOW_NOTE = 14; // gap from the lowest notehead to the lyric baseline+const LYRIC_MIN_BELOW_STAFF = 22; // floor so high-only rows keep lyrics close to the staffconst ROW_GAP = 18; // gap between rowsconst ROW_HEIGHT = ROW_TOP_PAD + 4 * GAP + ROW_STAFF_TO_LYRIC + ROW_GAP;@@ -129,9 +131,15 @@ export default function ScoreSheet({ text, className = '' }) {const staffTop = rowTop + ROW_TOP_PAD;const staffBottom = staffTop + 4 * GAP;const chordY = rowTop + 16;- const lyricY = staffBottom + 22;// y for a diatonic step within this row.const yForStep = (step) => staffBottom - (step - bottomLineStep) * STEP;+ // Lyrics sit below the LOWEST notehead in the row, not at a fixed offset —+ // otherwise notes that dip below the staff (ledger-line pitches like A3) draw+ // on top of the lyric text. Floor at LYRIC_MIN_BELOW_STAFF so a row of only+ // high notes still keeps its lyrics tucked close under the staff.+ const rowPitchedNotes = row.rowMeasures.flatMap((rm) => rm.measure.notes).filter((n) => !n.rest);+ const lowestStep = rowPitchedNotes.length ? Math.min(...rowPitchedNotes.map((n) => n.step)) : bottomLineStep;+ const lyricY = Math.max(staffBottom + LYRIC_MIN_BELOW_STAFF, yForStep(lowestStep) + LYRIC_BELOW_NOTE);// Staff: five lines across the full content width.for (let line = 0; line < 5; line += 1) {diff --git a/client/src/components/songs/ScoreSheet.test.jsx b/client/src/components/songs/ScoreSheet.test.jsxindex 6aeca821c2..75d173e5fa 100644--- a/client/src/components/songs/ScoreSheet.test.jsx+++ b/client/src/components/songs/ScoreSheet.test.jsx@@ -72,6 +72,18 @@ describe('ScoreSheet renderer', () => {expect(count(withLedger, 'line')).toBeGreaterThan(6); // 5 staff + 2 barlines + ledger});+ it('places a lyric below a low ledger note, not under its notehead', () => {+ // Regression: A3 sits below the treble staff; with a fixed lyric baseline the+ // notehead drew on top of the syllable. The lyric must sit below the head.+ const html = renderToStaticMarkup(<ScoreSheet text={'| A3q(low) F5q(high) |'} />);+ const headY = Number(/<ellipse[^>]*\bcy="([\d.]+)"/.exec(html)?.[1]);+ const lyricY = Number(new RegExp('<text[^>]*\\by="([\\d.]+)"[^>]*>low<').exec(html)?.[1]);+ expect(Number.isFinite(headY)).toBe(true);+ expect(Number.isFinite(lyricY)).toBe(true);+ // Larger y is further down the page — the lyric baseline must be below the head.+ expect(lyricY).toBeGreaterThan(headY);+ });+it('renders a bass clef score without error', () => {const html = renderToStaticMarkup(<ScoreSheet text={'clef: bass\n| G2q C3q |'} />);expect(html).not.toMatch(/NaN/);diff --git a/client/src/pages/SongEditor.jsx b/client/src/pages/SongEditor.jsxindex bddd9e07e3..874a9271be 100644--- a/client/src/pages/SongEditor.jsx+++ b/client/src/pages/SongEditor.jsx@@ -30,15 +30,20 @@ import {} from 'lucide-react';import toast from '../components/ui/Toast';import { useAsyncAction } from '../hooks/useAsyncAction';-import { getSong, updateSong, refreshSongTemplate } from '../services/api';+import { getSong, updateSong, refreshSongTemplate, listSongs } from '../services/api';import { RHYTHM_SHAPES, VOICE_LAYERS, rhythmShapeLabel } from '../lib/songCraft';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 ScoreSheet from '../components/songs/ScoreSheet';+import RoundStack from '../components/songs/RoundStack';import { scoreHasMusic } from '../lib/scoreNotation';+// 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.+const PARTNERS_MAX = 12;+// Extract a TikTok video id from a share/watch URL so we can render TikTok's// documented iframe Embed Player (https://www.tiktok.com/player/v1/<id>)// instead of loading their embed.js. Returns null for anything that isn't a@@ -102,8 +107,22 @@ export default function SongEditor() {return next;}, { replace: true });}, [setSearchParams]);+ // Round-stack view lives in the URL (?stack=1) so the stacked parts are a+ // linkable view, like ?mode — per the "linkable routes for all views" rule.+ const stackOpen = searchParams.get('stack') === '1';+ const setStack = useCallback((open) => {+ setSearchParams((prev) => {+ const next = new URLSearchParams(prev);+ if (open) next.set('stack', '1');+ else next.delete('stack');+ return next;+ }, { replace: true });+ }, [setSearchParams]);const [song, setSong] = useState(null);const [loading, setLoading] = useState(true);+ // 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([]);useEffect(() => {let cancelled = false;@@ -114,6 +133,35 @@ export default function SongEditor() {return () => { cancelled = true; };}, [id]);+ // Fetch once on mount — the all-songs list resolves partner titles + the+ // editor pick list and doesn't depend on which song is open, so it must not+ // re-fetch on every song navigation.+ useEffect(() => {+ let cancelled = false;+ listSongs({ silent: true })+ .then((data) => { if (!cancelled) setAllSongs(data?.songs || []); })+ .catch(() => { /* the page degrades to no partner resolution */ });+ return () => { cancelled = true; };+ }, []);++ // Resolve this song's partner ids to records (skip any that no longer exist).+ const partnerSongs = useMemo(() => {+ const byId = new Map(allSongs.map((s) => [s.id, s]));+ return (song?.partnerSongIds || []).map((pid) => byId.get(pid)).filter(Boolean);+ }, [allSongs, song?.partnerSongIds]);+ // Other songs to offer as partners in the editor, alphabetical.+ const otherSongs = useMemo(+ () => allSongs.filter((s) => s.id !== id).sort((a, b) => (a.title || '').localeCompare(b.title || '')),+ [allSongs, id],+ );+ const togglePartner = useCallback((pid) => setSong((prev) => {+ if (!prev) return prev;+ const cur = prev.partnerSongIds || [];+ if (cur.includes(pid)) return { ...prev, partnerSongIds: cur.filter((x) => x !== pid) };+ if (cur.length >= PARTNERS_MAX) return prev;+ return { ...prev, partnerSongIds: [...cur, pid] };+ }), []);+// Field setters merge into the in-memory draft; nothing persists until Save.const setField = useCallback((key, value) => {setSong((prev) => (prev ? { ...prev, [key]: value } : prev));@@ -130,6 +178,7 @@ export default function SongEditor() {layers: (song.layers || []).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);@@ -299,6 +348,9 @@ export default function SongEditor() {setField={setField}onRefreshTemplate={refreshTemplate}refreshing={refreshing}+ partnerSongs={partnerSongs}+ stackOpen={stackOpen}+ onToggleStack={setStack}/>)}@@ -465,6 +517,40 @@ export default function SongEditor() {)}</section>+ {/* Sings with — partner songs for the round-stack (quodlibet) view */}+ <section>+ <h2 className="flex items-center gap-2 text-sm font-semibold text-white mb-2">+ <Layers size={15} className="text-port-accent" /> Sings with (round partners)+ </h2>+ <p className="text-xs text-gray-500 mb-2">+ Link songs that are sung at the same time — rounds that share a chord cycle. In View, a “Stack parts” button+ renders them together and plays their takes layered.+ </p>+ {otherSongs.length === 0 ? (+ <p className="text-xs text-gray-500">No other songs yet to pair with.</p>+ ) : (+ <div className="flex flex-wrap gap-1.5">+ {otherSongs.map((s) => {+ const checked = (song.partnerSongIds || []).includes(s.id);+ const atMax = !checked && (song.partnerSongIds || []).length >= PARTNERS_MAX;+ return (+ <button+ key={s.id}+ type="button"+ onClick={() => togglePartner(s.id)}+ disabled={atMax}+ aria-pressed={checked}+ title={atMax ? `Up to ${PARTNERS_MAX} partners` : undefined}+ className={`px-2.5 py-1 text-xs rounded-full border transition-colors disabled:opacity-40 ${checked ? 'bg-port-accent/15 border-port-accent/60 text-white' : 'border-port-border text-gray-300 hover:text-white hover:border-port-accent/60'}`}+ >+ {checked ? '✓ ' : '+ '}{s.title || 'Untitled song'}+ </button>+ );+ })}+ </div>+ )}+ </section>+{/* Vocal takes — record & layered playback */}<SongRecordingsrecordings={song.recordings || []}@@ -569,7 +655,7 @@ export default function SongEditor() {// (no sub-scrollable textareas) and laid out in a responsive grid so short// sections sit side-by-side and use the available desktop width. The recorder// stays interactive (recording mutates the draft; the header Save persists it).-function ReadView({ song, setField, onRefreshTemplate, refreshing }) {+function ReadView({ song, setField, onRefreshTemplate, refreshing, partnerSongs = [], stackOpen = false, onToggleStack }) {const sections = song.sections || [];const layers = song.layers || [];const references = song.references || [];@@ -579,6 +665,10 @@ function ReadView({ song, setField, onRefreshTemplate, refreshing }) {// 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.+ const showingStack = stackOpen && partnerSongs.length > 0;// Label + value badge, two-toned, built on the shared Pill primitive.const metaBadge = (label, value) => (@@ -602,8 +692,34 @@ function ReadView({ song, setField, onRefreshTemplate, refreshing }) {</Pill></div>+ {/* Sings with — partner rounds, with a toggle for the stacked all-parts view. */}+ {partnerSongs.length > 0 && (+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-xs text-gray-500">Sings with:</span>+ {partnerSongs.map((p) => (+ <Link key={p.id} to={`/songs/${p.id}`} className="px-2.5 py-1 text-xs rounded-full border border-port-border text-gray-300 hover:text-white hover:border-port-accent/60">+ {p.title || 'Untitled song'}+ </Link>+ ))}+ <button+ type="button"+ onClick={() => onToggleStack?.(!stackOpen)}+ aria-pressed={stackOpen}+ className={`flex items-center gap-1.5 px-2.5 py-1 text-xs rounded-full border transition-colors ${stackOpen ? 'bg-port-accent text-white border-port-accent' : 'border-port-border text-gray-300 hover:text-white hover:border-port-accent/60'}`}+ >+ <Layers size={13} /> {stackOpen ? 'Hide stack' : 'Stack parts'}+ </button>+ </div>+ )}++ {/* Round stack — every part at once, replacing the single-song reading+ surface while open. */}+ {showingStack && (+ <RoundStack songs={[song, ...partnerSongs]} />+ )}+{/* Sheet music — the rendered staff, full-width so a row of bars fits. */}- {hasScore && (+ {!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">@@ -612,6 +728,7 @@ function ReadView({ song, setField, onRefreshTemplate, refreshing }) {</section>)}+ {!showingStack && (<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">{/* Lyrics — the main reading surface, given the most width. */}<section className="lg:col-span-2 space-y-3">@@ -668,6 +785,7 @@ function ReadView({ song, setField, onRefreshTemplate, refreshing }) {)}</aside></div>+ )}{/* Reference material — TikTok videos embed; other links render as cards. */}{references.length > 0 && (diff --git a/docs/plans/2026-06-07-musical-rounds-quodlibet.md b/docs/plans/2026-06-07-musical-rounds-quodlibet.mdnew file mode 100644index 0000000000..1800bfe68b--- /dev/null+++ b/docs/plans/2026-06-07-musical-rounds-quodlibet.md@@ -0,0 +1,91 @@+# Add built-in musical rounds + a cross-song "round stack" (quodlibet) view++## Context++The songs workbench (shipped in `9be5b79d`) currently seeds one built-in song, "500 Miles". The user wants to ship a set of **traditional musical rounds** as additional built-in songs — and, crucially, wants to treat them as *symbiotic, layerable elements*: a way to render multiple songs stacked together as simultaneous parts (a quodlibet / round-stack), since the user learned these four rounds sung all together.++Two deliverables:+1. **Four new built-in round songs** with notated melodies, lyrics, and canon-entry "layers".+2. **A cross-song layering mechanism** — songs can declare *partner songs* they sing with, and a read-only "round stack" view renders each partner's melody + lyrics stacked as simultaneous parts (and can play their recorded takes together).++### Lyric/spelling check (verified against canonical sources)++- **Hey, Ho! Nobody Home** (English round, Ravenscroft's *Pammelia*, 1609): `Hey, ho, nobody home, / Meat nor drink nor money have I none, / Still I will be merry. / Hey, ho, nobody home.` — user prefers the "Still I will be merry" variant; using that. It's a round in up to 6 voices.+- **Zum Gali Gali** (Israeli/Hebrew round): user's "zum gully gully" → **"Zum gali gali"**. `Zum gali gali gali, zum gali gali (×2) / He'chalutz le'man avodah, / Avodah le'man he'chalutz.` (*"The pioneer is for work; work is for the pioneer."*)+- **Rose, Rose, Rose, Red** (English round): user's spelling correct. `Rose, rose, rose, red, / Will I ever see thee wed? / I will marry at thy will, sire, / At thy will.`+- **Ah, Poor Bird** (English round) — ships **two lyric sections**:+ - *Canonical:* `Ah, poor bird, / Take thy flight, / Far above the sorrows / Of this sad night.`+ - *Alternate (as the user learned it):* `Oh, poor bird, why art thou / Hiding in the shadows / Of this dark house?` — added as a second labeled lyric section so both versions ship.++**Musical note:** Hey Ho + Ah Poor Bird + Rose Rose are the classic *quodlibet* trio — they share one minor-key chord cycle and can be sung simultaneously. Zum Gali Gali is a standalone round (i–V vamp); it's grouped with the others as a performance set per the user, but the notes will be honest that the trio is the harmonically-compatible set.++## Approach++### 1. New `partnerSongIds` field (the "symbiotic link")++Mirror the existing `references` array pattern end-to-end:++- **`server/services/songs.js`**: add `PARTNERS_MAX = 12`; in `sanitizeSong` add `partnerSongIds: sanitizePartnerIds(raw.partnerSongIds, id)` — a helper that keeps only non-empty strings (trim to `ID_MAX_LENGTH`), dedupes, and **drops self-references** (an id equal to the song's own id). Add `'partnerSongIds'` to the merge-key loop in `updateSong` and to the `refreshSongFromTemplate` template spread (it's part of template content).+- **`server/routes/songs.js`**: add `partnerSongIds: z.array(str(ID_MAX_LENGTH)).max(PARTNERS_MAX).optional()` to `songInputSchema` (import `PARTNERS_MAX`).+- Sanitize-on-read defaults it to `[]`, so the existing 500 Miles record needs **no migration** for the field itself.++### 2. Four new built-in round songs (`SEED_SONGS` in `server/services/songs.js`)++Append four entries after `seed-500-miles`. IDs: `seed-hey-ho-nobody-home`, `seed-ah-poor-bird`, `seed-rose-rose-rose-red`, `seed-zum-gali-gali`. Each carries:++- `title`, `artist: 'Traditional'`, `key`, `tempo`, `rhythmShapeId` (e.g. `rubato-free` / `slow-4-4`).+- **`score`**: the round's melody authored in the lead-sheet DSL (`client/src/lib/scoreNotation.js` format). Trio (Hey Ho, Ah Poor Bird, Rose Rose) notated in a **shared no-accidental A-minor** (written with the C key signature, tonic A) so they stack cleanly; Zum Gali Gali in D minor. Melodies authored from the canonical traditional tunes; **verified to parse with zero `errors` and render in `ScoreSheet`** before commit.+- **`sections`**: the corrected lyrics above, one section per round (multi-line). Ah Poor Bird gets **two** sections — "Verse" (canonical) and "Alternate (as learned)" with the user's "Oh, poor bird, why art thou…" version.+- **`layers`**: the canon *entries* — e.g. Hey Ho = 4 layers "Voice 1 (lead)" … "Voice 4 (enters 4th phrase)", each with a note on where it comes in. This reuses the existing `layers` concept for *within-song* staggered round entries (distinct from `partnerSongIds`, which is *across-song* simultaneity).+- **`partnerSongIds`**: each of the four links the other three (bidirectional by convention). `notes` explains the quodlibet trio vs. the standalone Zum Gali Gali honestly.+- `references`: none (left empty; user can add performance links).+- Fixed `createdAt`/`updatedAt` timestamps (string literals, matching the 500 Miles seed convention — scripts can't call `Date.now()`).++`BUILTIN_SONG_IDS` auto-derives from `SEED_SONGS`, so the new ids get the `builtIn` flag + refresh-from-template for free.++### 3. Backfill migration for existing installs++New `scripts/migrations/074-seed-musical-rounds.js`, mirroring `073-seed-500-miles-score.js`:+- Export `const ROUND_SEEDS = [...]` (the four full records).+- `up({ rootDir })`: if `data/songs.json` absent → no-op (fresh installs seed directly); if unparseable / unexpected shape → skip; otherwise for each round **prepend it only if its id isn't already present** (idempotent), bump nothing on skip, write back.+- Drift guard in the test: assert each `ROUND_SEEDS[i]` deep-equals the matching `SEED_SONGS` entry, so the migration copy and the live seed can't diverge (same pattern as `073` asserting `SCORE_500_MILES === seed.score`).++### 4. Cross-song "round stack" view (read-only)++New component **`client/src/components/songs/RoundStack.jsx`**:+- Props: `{ songs }` — the primary song + its resolved partner songs.+- Renders one labeled block per song: title + `<ScoreSheet text={song.score} />` (reused as-is — it's a pure render component) + that song's lyric sections, stacked vertically so all simultaneous parts are visible at once.+- A "Play all parts together" button that flattens every partner song's `recordings` into one `createLayeredPlayer(takes)` call (reusing `client/src/lib/songPlayback.js`) so recorded takes across songs play sample-aligned — the existing within-song mixer pattern, widened across songs.++Integration in **`client/src/pages/SongEditor.jsx`**:+- **ReadView**: when `song.partnerSongIds.length > 0`, show a "Sings with" list (links to each partner) and a **"Stack parts" toggle** controlled by a URL param (`?stack=1`, per the linkable-routes convention) that fetches the partner songs (`getSong` per id, or filter a single `listSongs`) and renders `<RoundStack>`.+- **EDIT mode**: a minimal "Sings with" editor — a checkbox list of the user's *other* songs to toggle membership; writes `partnerSongIds` through the normal Save (`updateSong`). Self is excluded from the list.++No new route/nav-manifest entry (the stack is a URL-param view on the existing `/songs/:id`), and `components/` has no barrel/README requirement (matches `ScoreSheet.jsx`).++## Critical files++- `server/services/songs.js` — `partnerSongIds` sanitizer + helper, four `SEED_SONGS` entries, merge-key + template-spread updates.+- `server/routes/songs.js` — `partnerSongIds` in `songInputSchema`.+- `scripts/migrations/074-seed-musical-rounds.js` (+ `.test.js`) — backfill + drift guard.+- `client/src/components/songs/RoundStack.jsx` (+ `.test.jsx`) — stacked multi-song render; reuses `ScoreSheet` + `createLayeredPlayer`.+- `client/src/pages/SongEditor.jsx` — "Sings with" read/edit UI + `?stack=1` partner fetch.+- Reused as-is: `client/src/components/songs/ScoreSheet.jsx`, `client/src/lib/scoreNotation.js`, `client/src/lib/songPlayback.js`, `client/src/services/apiSongs.js` (`getSong`/`listSongs`/`updateSong`).++## Tests++- `server/services/songs.test.js`: four new seeds present + `builtIn` true; `partnerSongIds` round-trips; self-reference dropped; dedupe; refresh-from-template restores partners.+- `server/routes/songs.test.js`: `partnerSongIds` accepted; over-`PARTNERS_MAX` / non-string array rejected (400).+- `scripts/migrations/074-seed-musical-rounds.test.js`: no-file no-op, fresh-prepend, idempotent re-run, never-clobber-existing, unparseable skip, **drift guard vs `SEED_SONGS`**.+- `client/src/lib/scoreNotation.test.js` (or a `ScoreSheet.test.jsx`): the four round score strings parse with `errors: []` and `scoreHasMusic === true` (DSL-validity guard for the authored melodies).+- `client/src/components/songs/RoundStack.test.jsx`: renders a `ScoreSheet` + lyrics per song; "Play all parts" gathers takes across songs.++## Verification (end-to-end)++1. `cd server && npm test` and `cd client && npm test` — all green, including the new migration drift guard and score-parse tests.+2. `npm run dev`; open `/songs` — confirm the four rounds appear with the "Built-in" badge.+3. Open **Hey Ho Nobody Home** in read mode — confirm the melody renders in `ScoreSheet`, lyrics + 4 canon-entry layers show, and a "Sings with" list links the other three.+4. Click **Stack parts** (`?stack=1`) — confirm all partner melodies + lyrics render stacked; the URL is shareable/linkable.+5. Record a quick take on two partner songs, hit **Play all parts together** — confirm they play layered/aligned.+6. Run a fresh-install simulation (temp `data/`, no `songs.json`) to confirm seeds appear without the migration, then run migration `074` against an old `songs.json` (only 500 Miles) and confirm the four rounds are prepended once and re-runs are no-ops.+7. Run `/simplify` on the diff before committing (per repo workflow).diff --git a/scripts/migrations/074-seed-musical-rounds.js b/scripts/migrations/074-seed-musical-rounds.jsnew file mode 100644index 0000000000..7e33492021--- /dev/null+++ b/scripts/migrations/074-seed-musical-rounds.js@@ -0,0 +1,76 @@+/**+ * Backfill the four built-in traditional rounds — Hey Ho Nobody Home, Ah Poor+ * Bird, Rose Rose Rose Red, and Zum Gali Gali — for installs that seeded+ * data/songs.json before these rounds shipped.+ *+ * Background:+ * server/services/songs.js#SEED_SONGS now ships four rounds in addition to+ * "500 Miles". New seeds only reach an install on its FIRST read of songs (when+ * the file is seeded). An install that already persisted data/songs.json keeps+ * its old records and never sees the new seeds — this migration prepends any of+ * the four that are absent (matched by id), once.+ *+ * Fresh installs need nothing here: SEED_SONGS already includes the rounds, so+ * a missing file is a clean no-op. Re-runs detect the rounds present and skip.+ * A record the user already owns under one of these ids is never clobbered — we+ * only add a round when its id is missing.+ *+ * The records come straight from SEED_SONGS (filtered by id and run through the+ * service's own sanitizer) rather than a hand-copied duplicate, so this+ * migration can never drift from the shipped seed.+ */++import { readFile, writeFile, stat } from 'fs/promises';+import { join } from 'path';+import { SEED_SONGS, sanitizeSong } from '../../server/services/songs.js';++export const ROUND_IDS = [+ 'seed-hey-ho-nobody-home',+ 'seed-ah-poor-bird',+ 'seed-rose-rose-rose-red',+ 'seed-zum-gali-gali',+];++// The shipped round records in canonical on-disk shape — exactly what a fresh+// seed write produces (listSongs persists SEED_SONGS.map(sanitizeSong)).+export const ROUND_SEEDS = ROUND_IDS+ .map((id) => SEED_SONGS.find((s) => s.id === id))+ .map(sanitizeSong);++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 074: no data/songs.json — fresh install seeds the rounds 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 074: 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 present = new Set(doc.songs.map((s) => s && s.id));+ const missing = ROUND_SEEDS.filter((round) => !present.has(round.id));+ if (missing.length === 0) {+ console.log('📦 migration 074: all four rounds already present; nothing to add.');+ return { updated: 0, reason: 'already-present' };+ }++ // Prepend so the new built-ins surface at the top of the user's list.+ doc.songs = [...missing, ...doc.songs];+ await writeFile(path, JSON.stringify(doc, null, 2) + '\n');+ console.log(`📦 migration 074: added ${missing.length} built-in round(s): ${missing.map((s) => s.title).join(', ')}.`);+ return { updated: missing.length };+ },+};diff --git a/scripts/migrations/074-seed-musical-rounds.test.js b/scripts/migrations/074-seed-musical-rounds.test.jsnew file mode 100644index 0000000000..f01e91251e--- /dev/null+++ b/scripts/migrations/074-seed-musical-rounds.test.js@@ -0,0 +1,85 @@+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, { ROUND_IDS, ROUND_SEEDS } from './074-seed-musical-rounds.js';+import { SEED_SONGS, sanitizeSong } from '../../server/services/songs.js';++const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));+const ids = (path) => readJson(path).songs.map((s) => s.id);++describe('migration 074 — backfill the four built-in rounds', () => {+ let rootDir;+ let songsPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-074-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ songsPath = join(rootDir, 'data', 'songs.json');+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('does not drift from the shipped seed rounds', () => {+ // ROUND_SEEDS is derived from SEED_SONGS, so this guards the id list and the+ // sanitized shape: every round id must resolve to a shipped seed.+ expect(ROUND_SEEDS).toHaveLength(ROUND_IDS.length);+ for (const id of ROUND_IDS) {+ const seed = SEED_SONGS.find((s) => s.id === id);+ expect(seed, `SEED_SONGS missing ${id}`).toBeTruthy();+ const round = ROUND_SEEDS.find((s) => s.id === id);+ expect(round).toEqual(sanitizeSong(seed));+ }+ });++ it('no-ops when data/songs.json is missing (fresh install seeds it directly)', async () => {+ const result = await migration.up({ rootDir });+ expect(result).toEqual({ updated: 0, reason: 'no-file' });+ expect(existsSync(songsPath)).toBe(false);+ });++ it('prepends all four rounds onto an install that lacks them', async () => {+ writeJson(songsPath, { songs: [{ id: 'seed-500-miles', title: '500 Miles' }] });+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(4);+ expect(ids(songsPath)).toEqual([...ROUND_IDS, 'seed-500-miles']);+ // The persisted record carries the full shipped content (melody + lyrics).+ const heyHo = readJson(songsPath).songs.find((s) => s.id === 'seed-hey-ho-nobody-home');+ expect(heyHo.title).toBe('Hey Ho Nobody Home');+ expect(heyHo.score).toContain('Hey');+ expect(heyHo.partnerSongIds).toContain('seed-ah-poor-bird');+ });++ it('only adds the rounds that are missing', async () => {+ writeJson(songsPath, { songs: [{ id: 'seed-ah-poor-bird', title: 'mine' }] });+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(3);+ // The user's existing ah-poor-bird record is untouched (not clobbered).+ const ahPoorBird = readJson(songsPath).songs.find((s) => s.id === 'seed-ah-poor-bird');+ expect(ahPoorBird.title).toBe('mine');+ expect(ids(songsPath)).not.toContain(undefined);+ });++ it('is idempotent across re-runs', async () => {+ writeJson(songsPath, { songs: [{ id: 'seed-500-miles' }] });+ await migration.up({ rootDir });+ const second = await migration.up({ rootDir });+ expect(second).toEqual({ updated: 0, reason: 'already-present' });+ });++ 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' });+ });++ it('skips an unexpected shape (no songs array)', async () => {+ writeJson(songsPath, { notSongs: true });+ const result = await migration.up({ rootDir });+ expect(result).toEqual({ updated: 0, reason: 'unexpected-shape' });+ });+});diff --git a/server/routes/songs.js b/server/routes/songs.jsindex dee1fd2164..44f5da12b6 100644--- a/server/routes/songs.js+++ b/server/routes/songs.js@@ -83,6 +83,9 @@ const songInputSchema = z.object({layers: z.array(layerSchema).max(svc.LAYERS_MAX).optional(),recordings: z.array(recordingSchema).max(svc.RECORDINGS_MAX).optional(),references: z.array(referenceSchema).max(svc.REFERENCES_MAX).optional(),+ // Ids of other songs sung together with this one (round-stack partners). The+ // service dedupes and drops self-references; the schema only bounds the list.+ partnerSongIds: z.array(str(svc.ID_MAX_LENGTH)).max(svc.PARTNERS_MAX).optional(),});// AI generate/evaluate inputs. providerId/model are optional overrides; thediff --git a/server/routes/songs.test.js b/server/routes/songs.test.jsindex be822d6c57..bf3749e4d5 100644--- a/server/routes/songs.test.js+++ b/server/routes/songs.test.js@@ -157,6 +157,23 @@ describe('songs route', () => {expect(res.status).toBe(200);});+ it('PUT /:id accepts a partnerSongIds array', async () => {+ mocks.updateSong.mockResolvedValue({ id: 'song-1' });+ const res = await request(makeApp()).put('/api/songs/song-1').send({+ partnerSongIds: ['seed-ah-poor-bird', 'seed-rose-rose-rose-red'],+ });+ expect(res.status).toBe(200);+ const [, patch] = mocks.updateSong.mock.calls[0];+ expect(patch.partnerSongIds).toEqual(['seed-ah-poor-bird', 'seed-rose-rose-rose-red']);+ });++ it('PUT /:id rejects more than PARTNERS_MAX partner ids', async () => {+ const tooMany = Array.from({ length: 20 }, (_, i) => `seed-${i}`);+ const res = await request(makeApp()).put('/api/songs/song-1').send({ partnerSongIds: tooMany });+ expect(res.status).toBe(400);+ expect(mocks.updateSong).not.toHaveBeenCalled();+ });+it('POST /:id/refresh-template returns the refreshed built-in song', async () => {mocks.refreshSongFromTemplate.mockResolvedValue({ id: 'seed-500-miles', title: '500 Miles', builtIn: true });const res = await request(makeApp()).post('/api/songs/seed-500-miles/refresh-template');diff --git a/server/services/songs.js b/server/services/songs.jsindex 288af7f438..358ac161b9 100644--- a/server/services/songs.js+++ b/server/services/songs.js@@ -47,6 +47,7 @@ export const SECTIONS_MAX = 60;export const LAYERS_MAX = 24;export const RECORDINGS_MAX = 64; // saved vocal takes for layered playbackexport const REFERENCES_MAX = 12; // reference links/videos (e.g. TikTok)+export const PARTNERS_MAX = 12; // partner-song ids (rounds sung together)export const URL_MAX_LENGTH = 512; // uploaded-file path/url// Trim a string field, returning '' for non-strings. Mirrors the@@ -142,6 +143,19 @@ const sanitizeList = (arr, fn, max) =>.filter(Boolean).slice(0, max);+// Partner-song ids — the "symbiotic" link that lets rounds declare which other+// songs they're sung together with (a quodlibet stack). Keeps only non-empty+// strings, dedupes, and drops a self-reference (a song can't partner itself —+// that would make the round-stack render the same song twice). `selfId` is the+// owning song's id so the self-drop survives a hand-edited file.+const sanitizePartnerIds = (arr, selfId) => {+ const seen = new Set();+ return (Array.isArray(arr) ? arr : [])+ .map((v) => trimField(v, ID_MAX_LENGTH))+ .filter((id) => id && id !== selfId && !seen.has(id) && seen.add(id))+ .slice(0, PARTNERS_MAX);+};+// Project a stored or inbound record onto the canonical song shape. Used on// read (defends hand-edited JSON) and on write (normalizes the input).export const sanitizeSong = (raw) => {@@ -166,6 +180,8 @@ export const sanitizeSong = (raw) => {layers: sanitizeList(raw.layers, sanitizeLayer, LAYERS_MAX),recordings: sanitizeList(raw.recordings, sanitizeRecording, RECORDINGS_MAX),references: sanitizeList(raw.references, sanitizeReference, REFERENCES_MAX),+ // Ids of other songs this one is sung together with (round-stack partners).+ partnerSongIds: sanitizePartnerIds(raw.partnerSongIds, id),// Derived from the shipped-seed id set, NOT from `raw` — so the flag can't// be lost on edit or spoofed on a hand-edited custom song. A built-in// default can be restored to its shipped content via refreshSongFromTemplate.@@ -226,6 +242,150 @@ export const SEED_SONGS = [createdAt: '2026-01-01T00:00:00.000Z',updatedAt: '2026-01-01T00:00:00.000Z',},+ // --- Traditional rounds -------------------------------------------------+ // Four singable rounds that the user learned as a set. The first three —+ // Hey Ho Nobody Home, Ah Poor Bird, Rose Rose Rose Red — are the classic+ // English quodlibet: all in the same minor key, they can be sung at the same+ // time. Zum Gali Gali shares the key and rounds out the set. Each links the+ // others via partnerSongIds, so the editor's round-stack view can render them+ // together. Melodies are scored with no key signature (D Dorian / D minor,+ // all naturals) so they stack cleanly; the `key` field names the tonality.+ {+ id: 'seed-hey-ho-nobody-home',+ title: 'Hey Ho Nobody Home',+ artist: 'Traditional',+ key: 'D minor (Dorian)',+ tempo: 76,+ rhythmShapeId: 'slow-4-4',+ notation: 'A round in up to six voices (Ravenscroft\'s Pammelia, 1609). New voices enter one two-bar phrase behind the last. Scored in D with no key signature — D Dorian, B natural. Melody after Jack Campin\'s D-minor round transcription.',+ score: [+ 'clef: treble',+ 'key: C',+ 'time: 4/4',+ 'tempo: 76',+ '',+ '| G4h(Hey) D4h(ho) | G4q(no-) G4e(bo-) G4e(dy) D4h(home) |',+ '| G4q(Meat) G4q(nor) A4q(drink) A4q(nor) | B4e(mon-) B4e(ey) B4e(have) B4e(I) A4h(none) |',+ '| D5q(Still) C5q(I) D5q(will) C5q(be) | B4h(mer-) A4h(ry) |',+ ].join('\n'),+ notes: 'One of the oldest English rounds. Sung with Ah Poor Bird and Rose Rose Rose Red it forms a classic three-round quodlibet — all three share one minor chord cycle and can be sung at the same time. Keep it light and lilting despite the minor key.',+ learned: false,+ sections: [+ { id: 'sec-round', label: 'Round', lyrics: 'Hey, ho, nobody home,\nMeat nor drink nor money have I none,\nStill I will be merry.\nHey, ho, nobody home.' },+ ],+ layers: [+ { id: 'voice-1', label: 'Voice 1 (lead)', part: 'Any', notes: 'Starts the round and sings it straight through. Everyone learns this line first.' },+ { id: 'voice-2', label: 'Voice 2', part: 'Any', notes: 'Enters as Voice 1 reaches "Meat nor drink…" (phrase 2) — one full phrase behind the lead.' },+ { id: 'voice-3', label: 'Voice 3', part: 'Any', notes: 'Enters at "Still I will be merry" (phrase 3); the three phrases stack into the full minor chord.' },+ { id: 'voice-4', label: 'Voice 4', part: 'Any', notes: 'Optional fourth entry: comes in as Voice 1 loops back to the top, doubling the lead in unison or an octave up.' },+ ],+ references: [],+ partnerSongIds: ['seed-ah-poor-bird', 'seed-rose-rose-rose-red', 'seed-zum-gali-gali'],+ createdAt: '2026-06-07T00:00:00.000Z',+ updatedAt: '2026-06-07T00:00:00.000Z',+ },+ {+ id: 'seed-ah-poor-bird',+ title: 'Ah Poor Bird',+ artist: 'Traditional',+ key: 'D minor',+ tempo: 72,+ rhythmShapeId: 'slow-4-4',+ notation: 'A four-phrase round (8 bars). Voices enter every two bars. The melody climbs the minor scale to a leap in the third phrase, then settles back to the tonic. Scored in D minor with no key signature (all naturals).',+ score: [+ 'clef: treble',+ 'key: C',+ 'time: 4/4',+ 'tempo: 72',+ '',+ '| D4h(Ah) E4h(poor) | F4w(bird) |',+ '| F4h(take) G4h(thy) | A4w(flight) |',+ '| A4q(far) D5q(a-) D5q(bove) C5q(the) | D5h(sor-) A4q(rows) G4q(of) |',+ '| F4h(this) E4h(sad) | D4w(night) |',+ ].join('\n'),+ notes: 'A gentle English lament-round. Combines with Hey Ho Nobody Home and Rose Rose Rose Red as a quodlibet. Two lyric sets ship: the common "take thy flight" verse and the "Oh poor bird, why art thou…" variant.',+ learned: false,+ sections: [+ { id: 'sec-verse', label: 'Verse', lyrics: 'Ah, poor bird,\nTake thy flight,\nFar above the sorrows\nOf this sad night.' },+ { id: 'sec-alt', label: 'Alternate (as learned)', lyrics: 'Oh, poor bird, why art thou\nHiding in the shadows\nOf this dark house?' },+ ],+ layers: [+ { id: 'voice-1', label: 'Voice 1 (lead)', part: 'Any', notes: 'Sings the climbing phrase straight through. The round is four 2-bar phrases.' },+ { id: 'voice-2', label: 'Voice 2', part: 'Any', notes: 'Enters at "take thy flight" (bar 3), two bars behind the lead.' },+ { id: 'voice-3', label: 'Voice 3', part: 'Any', notes: 'Enters at "far above the sorrows" (bar 5).' },+ { id: 'voice-4', label: 'Voice 4', part: 'Any', notes: 'Enters at "of this sad night" (bar 7) — four voices fill the lament.' },+ ],+ references: [],+ partnerSongIds: ['seed-hey-ho-nobody-home', 'seed-rose-rose-rose-red', 'seed-zum-gali-gali'],+ createdAt: '2026-06-07T00:00:00.000Z',+ updatedAt: '2026-06-07T00:00:00.000Z',+ },+ {+ id: 'seed-rose-rose-rose-red',+ title: 'Rose Rose Rose Red',+ artist: 'Traditional',+ key: 'D minor',+ tempo: 76,+ rhythmShapeId: 'slow-4-4',+ notation: 'A four-phrase English round (i–VII–V harmony), 8 bars. Voices enter every two bars. Scored in D minor with no key signature (all naturals).',+ score: [+ 'clef: treble',+ 'key: C',+ 'time: 4/4',+ 'tempo: 76',+ '',+ '| D4h(Rose) C4h(rose) | D4h(rose) A3h(red) |',+ '| D4q(Will) D4q(I) E4q(ev-) E4q(er) | F4q(see) G4q(thee) E4h(wed) |',+ '| A4q(I) A4q(will) G4q(mar-) A4q(ry) | F4q(at) G4e(thy) F4e E4q(will) A3q(sir) |',+ '| D4h(At) C4q(thy) E4q(will) | D4w |',+ ].join('\n'),+ notes: 'The third of the classic quodlibet trio with Hey Ho Nobody Home and Ah Poor Bird — all three stack in the same key. A favourite singing-round.',+ learned: false,+ sections: [+ { id: 'sec-round', label: 'Round', lyrics: 'Rose, rose, rose, red,\nWill I ever see thee wed?\nI will marry at thy will, sire,\nAt thy will.' },+ ],+ layers: [+ { id: 'voice-1', label: 'Voice 1 (lead)', part: 'Any', notes: 'Sings the round straight through. Four 2-bar phrases.' },+ { id: 'voice-2', label: 'Voice 2', part: 'Any', notes: 'Enters at "Will I ever see thee wed" (bar 3).' },+ { id: 'voice-3', label: 'Voice 3', part: 'Any', notes: 'Enters at "I will marry…" (bar 5).' },+ { id: 'voice-4', label: 'Voice 4', part: 'Any', notes: 'Enters at "At thy will" (bar 7) — four voices complete the harmony.' },+ ],+ references: [],+ partnerSongIds: ['seed-hey-ho-nobody-home', 'seed-ah-poor-bird', 'seed-zum-gali-gali'],+ createdAt: '2026-06-07T00:00:00.000Z',+ updatedAt: '2026-06-07T00:00:00.000Z',+ },+ {+ id: 'seed-zum-gali-gali',+ title: 'Zum Gali Gali',+ artist: 'Traditional',+ key: 'D minor',+ tempo: 112,+ rhythmShapeId: 'driving-4-4',+ notation: 'The refrain chant, repeated. Scored in D minor with no key signature (all naturals). Loop it as many times as you like; a second voice entering one phrase behind turns it into a round.',+ score: [+ 'clef: treble',+ 'key: C',+ 'time: 4/4',+ 'tempo: 112',+ '',+ '| D4q(Zoom) D4e(gul-) E4e(ly) F4e(gul-) E4e(ly) F4e(gul-) E4e(ly) | D4q(zoom) D4e(gul-) D4e(ly) A3q(gul-) C4q(ly) |',+ '| D4q(Zoom) D4e(gul-) E4e(ly) F4e(gul-) E4e(ly) F4e(gul-) E4e(ly) | D4q(zoom) D4e(gul-) D4e(ly) A3q(gul-) C4q(ly) |',+ ].join('\n'),+ notes: 'A simple chant on repeat — sung here as "zoom gully gully gully, zoom gully gully" (the refrain of the Israeli round Zum Gali Gali). Loop it as a driving ostinato; a second voice entering a phrase late turns it into a round. Shares the key with the English trio and rounds out the set.',+ learned: false,+ sections: [+ { id: 'sec-chant', label: 'Chant', lyrics: 'Zoom gully gully gully, zoom gully gully,\nZoom gully gully gully, zoom gully gully.' },+ ],+ layers: [+ { id: 'voice-1', label: 'Voice 1 (lead)', part: 'Any', notes: 'Chants the line and keeps it going on repeat — the engine the others ride on.' },+ { id: 'voice-2', label: 'Voice 2', part: 'Any', notes: 'Enters a phrase behind Voice 1 so the two halves of the chant overlap into harmony.' },+ ],+ references: [],+ partnerSongIds: ['seed-hey-ho-nobody-home', 'seed-ah-poor-bird', 'seed-rose-rose-rose-red'],+ createdAt: '2026-06-07T00:00:00.000Z',+ updatedAt: '2026-06-07T00:00:00.000Z',+ },];// Ids of the bundled built-in default songs. The sanitizer stamps each read@@ -300,7 +460,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']) {+ for (const key of ['title', 'artist', 'key', 'tempo', 'rhythmShapeId', 'notation', 'score', '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 8ae91902fb..ec07925a2e 100644--- a/server/services/songs.test.js+++ b/server/services/songs.test.js@@ -21,6 +21,9 @@ vi.mock('../lib/fileUtils.js', async () => {});import * as svc from './songs.js';+// The score DSL parser is a pure, dependency-free client module — import it here+// so the seeded scores are validated against the real parser at the source.+import { parseScore } from '../../client/src/lib/scoreNotation.js';const STATE_FILE = join(scratch.dir, 'data', 'songs.json');@@ -262,4 +265,59 @@ describe('songs service', () => {await expect(svc.refreshSongFromTemplate(custom.id)).rejects.toMatchObject({ code: svc.ERR_NOT_BUILTIN });await expect(svc.refreshSongFromTemplate('song-nope')).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });});++ it('seeds the four traditional rounds as built-ins with parseable scores', async () => {+ const songs = await svc.listSongs();+ for (const title of ['Hey Ho Nobody Home', 'Ah Poor Bird', 'Rose Rose Rose Red', 'Zum Gali Gali']) {+ const round = songs.find((s) => s.title === title);+ expect(round, `missing seed "${title}"`).toBeTruthy();+ expect(round.builtIn).toBe(true);+ expect(round.score).toContain('clef: treble');+ }+ });++ it('ships parseable sheet-music scores on every seeded song', async () => {+ const songs = await svc.listSongs();+ const withScore = songs.filter((s) => s.score);+ expect(withScore.length).toBeGreaterThan(0);+ for (const s of withScore) {+ const parsed = parseScore(s.score);+ expect(parsed.errors, `${s.title}: ${parsed.errors.join('; ')}`).toEqual([]);+ // Every measure should be a full bar (4 beats in these 4/4 scores) and the+ // score must contain at least one note.+ expect(parsed.measures.some((m) => m.notes.length > 0)).toBe(true);+ for (const [i, m] of parsed.measures.entries()) {+ expect(Math.abs(m.beats - 4) < 1e-9, `${s.title} bar ${i + 1} = ${m.beats} beats`).toBe(true);+ }+ }+ });++ it('links the three classic quodlibet rounds to each other as partners', async () => {+ const songs = await svc.listSongs();+ const heyHo = songs.find((s) => s.id === 'seed-hey-ho-nobody-home');+ expect(heyHo.partnerSongIds).toEqual(+ expect.arrayContaining(['seed-ah-poor-bird', 'seed-rose-rose-rose-red', 'seed-zum-gali-gali']),+ );+ // The link is symmetric — each partner names Hey Ho back.+ for (const id of heyHo.partnerSongIds) {+ const partner = songs.find((s) => s.id === id);+ expect(partner.partnerSongIds).toContain('seed-hey-ho-nobody-home');+ }+ });++ it('sanitizes partnerSongIds — drops blanks, dedupes, and drops self-references', () => {+ const song = svc.sanitizeSong({+ id: 'seed-rose-rose-rose-red',+ partnerSongIds: ['seed-ah-poor-bird', '', ' ', 'seed-ah-poor-bird', 'seed-rose-rose-rose-red', 42],+ });+ // 'seed-rose-rose-rose-red' (self) and the dup/blanks/non-string are removed.+ expect(song.partnerSongIds).toEqual(['seed-ah-poor-bird']);+ });++ it('defaults partnerSongIds to [] and round-trips a patch', async () => {+ const song = await svc.createSong({ title: 'Solo' });+ expect(song.partnerSongIds).toEqual([]);+ const patched = await svc.updateSong(song.id, { partnerSongIds: [song.id, 'song-other'] });+ expect(patched.partnerSongIds).toEqual(['song-other']); // self dropped+ });});