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
rename Songs workbench to Rounds (full-stack: route, API, data file, migration 120)
[._.]/ Adam Eivye401c849fc10
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 445974822e..0b5c3ef350 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -3,6 +3,7 @@## Changed- The **Social Agents** page now lives under the **Chief of Staff** sidebar section instead of **Brain**, in both the sidebar and the ⌘K / voice nav manifest.+- The **Songs** workbench is now called **Rounds** (its real subject is musical rounds — Hey Ho Nobody Home, the quodlibet trio, the "500 Miles" worked example). This is a full-stack rename: the page moved from `/songs` to `/rounds`, the API from `/api/songs` to `/api/rounds`, and the on-disk store from `data/songs.json` to `data/rounds.json` (top-level `songs[]` → `rounds[]`, per-record `partnerSongIds` → `partnerRoundIds`). An auto-running migration (120) converts existing installs on the next boot/update, preserving every saved round, recording, and training-progress record — nothing to do by hand. The ⌘K palette and voice navigation still resolve "songs"/"song" to the page, so old muscle memory keeps working.## Fixeddiff --git a/client/src/App.jsx b/client/src/App.jsxindex 85c1782a0a..9d0517519c 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -49,9 +49,9 @@ const UniverseBuilder = lazyWithReload(() => import('./pages/UniverseBuilder'));const Universes = lazyWithReload(() => import('./pages/Universes'));const Authors = lazyWithReload(() => import('./pages/Authors'));const Catalog = lazyWithReload(() => import('./pages/Catalog'));-const Songs = lazyWithReload(() => import('./pages/Songs'));-const SongEditor = lazyWithReload(() => import('./pages/SongEditor'));-const SongsGuide = lazyWithReload(() => import('./pages/SongsGuide'));+const Rounds = lazyWithReload(() => import('./pages/Rounds'));+const RoundEditor = lazyWithReload(() => import('./pages/RoundEditor'));+const RoundsGuide = lazyWithReload(() => import('./pages/RoundsGuide'));const CatalogIngest = lazyWithReload(() => import('./pages/CatalogIngest'));const CatalogIngredient = lazyWithReload(() => import('./pages/CatalogIngredient'));const VideoTimeline = lazyWithReload(() => import('./pages/VideoTimeline'));@@ -292,9 +292,9 @@ export default function App() {at `/universes/:universeId`; `new` is the create-mode sentinel(UniverseBuilder treats it as no-id → blank draft). Universe ids areUUIDs, so `new` can never collide with a real record. */}- <Route path="songs" element={<Songs />} />- <Route path="songs/guide" element={<SongsGuide />} />- <Route path="songs/:id" element={<SongEditor />} />+ <Route path="rounds" element={<Rounds />} />+ <Route path="rounds/guide" element={<RoundsGuide />} />+ <Route path="rounds/:id" element={<RoundEditor />} /><Route path="catalog" element={<Catalog />} /><Route path="catalog/ingest" element={<CatalogIngest />} /><Route path="catalog/:type/:id" element={<CatalogIngredient />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 237f20d3c7..0222ed425b 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -204,9 +204,9 @@ const navItems = [{ to: '/importer', label: 'Importer', icon: FileInput },{ to: '/media', label: 'Media Gen', icon: Layers },{ to: '/mood-boards', label: 'Mood Boards', icon: Palette },+ { to: '/rounds', label: 'Rounds', icon: Music },{ to: '/pipeline', label: 'Series Pipeline', icon: WorkflowIcon, dynamic: 'pipelineSeries' },{ to: '/sharing', label: 'Sharing', icon: Share2 },- { to: '/songs', label: 'Songs', icon: Music },{ to: '/story-builder', label: 'Story Builder', icon: Wand2 },{ to: '/universes', label: 'Universes', icon: Globe, dynamic: 'universes' },{ to: '/writers-room', label: 'Writers Room', icon: NotebookPen },@@ -1128,10 +1128,10 @@ export default function Layout() {location.pathname === '/prompts' ||location.pathname === '/review' ||location.pathname.startsWith('/settings') ||- // Song EDITOR (/songs/:id) and the Learning Guide (/songs/guide)- // are full-width and own their own scroll; the bare /songs index+ // Round EDITOR (/rounds/:id) and the Learning Guide (/rounds/guide)+ // are full-width and own their own scroll; the bare /rounds index// (list + create form) takes the normal padded+scrolling main.- location.pathname.startsWith('/songs/') ||+ location.pathname.startsWith('/rounds/') ||location.pathname.startsWith('/wiki') ||// Only the universe EDITOR (/universes/:id, /universes/new) is// full-width — it manages its own scroll. The /universes indexdiff --git a/client/src/components/songs/RoundStack.jsx b/client/src/components/songs/RoundStack.jsxindex 711112a7a5..1b99868c9d 100644--- a/client/src/components/songs/RoundStack.jsx+++ b/client/src/components/songs/RoundStack.jsx@@ -127,7 +127,7 @@ export default function RoundStack({ songs = [] }) {{i === 0 ? (<span>{s.title || 'Untitled song'}</span>) : (- <Link to={`/songs/${s.id}`} className="hover:text-port-accent transition-colors">+ <Link to={`/rounds/${s.id}`} className="hover:text-port-accent transition-colors">{s.title || 'Untitled song'}</Link>)}diff --git a/client/src/components/songs/SongAiPanel.jsx b/client/src/components/songs/SongAiPanel.jsxindex 9fe9112681..e7a33d43fe 100644--- a/client/src/components/songs/SongAiPanel.jsx+++ b/client/src/components/songs/SongAiPanel.jsx@@ -3,10 +3,10 @@** Two single-shot actions (the synchronous universe-builder pattern, not* streaming):- * - Generate / Expand → POST /api/songs/:id/generate, merges the returned+ * - Generate / Expand → POST /api/rounds/:id/generate, merges the returned* fields into the editor draft via `onApplyGenerated` (the parent owns Save,* so generation never silently overwrites a persisted song).- * - Evaluate → POST /api/songs/:id/evaluate, renders a score + strengths /+ * - Evaluate → POST /api/rounds/:id/evaluate, renders a score + strengths /* weaknesses / suggestions verdict inline (read-only, no mutation).** Provider/model default to the active provider server-side; no picker here@@ -16,7 +16,7 @@import { useState } from 'react';import { Sparkles, Wand2, ClipboardCheck, Loader2 } from 'lucide-react';import toast from '../ui/Toast';-import { generateSongFor, evaluateSong } from '../../services/api';+import { generateRoundFor, evaluateRound } from '../../services/api';const scoreColor = (n) => {if (n == null) return 'text-gray-400';@@ -33,7 +33,7 @@ export default function SongAiPanel({ songId, onApplyGenerated }) {const runGenerate = async (expandExisting) => {setBusy(expandExisting ? 'expand' : 'generate');- const data = await generateSongFor(+ const data = await generateRoundFor(songId,{ brief: brief.trim(), mood: mood.trim(), expandExisting },{ silent: true },@@ -48,7 +48,7 @@ export default function SongAiPanel({ songId, onApplyGenerated }) {const runEvaluate = async () => {setBusy('evaluate');- const data = await evaluateSong(songId, {}, { silent: true })+ const data = await evaluateRound(songId, {}, { silent: true }).catch((err) => { toast.error(err?.message || 'Evaluation failed'); return null; });setBusy(null);if (data?.evaluation) setVerdict(data.evaluation);diff --git a/client/src/components/songs/SongScoreParts.jsx b/client/src/components/songs/SongScoreParts.jsxindex 3ae43368f7..d4ffee5de6 100644--- a/client/src/components/songs/SongScoreParts.jsx+++ b/client/src/components/songs/SongScoreParts.jsx@@ -5,7 +5,7 @@* stack when sung together.** Two ways to fill it:- * - "Derive with AI" → POST /api/songs/:id/derive-parts reads the song's SAVED+ * - "Derive with AI" → POST /api/rounds/: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) —@@ -23,7 +23,7 @@ import toast from '../ui/Toast';import ScoreSheet from './ScoreSheet.jsx';import ProviderModelSelector from '../ProviderModelSelector.jsx';import useProviderModels from '../../hooks/useProviderModels.js';-import { deriveSongParts } from '../../services/api';+import { deriveRoundParts } from '../../services/api';import { HARMONY_PARTS, harmonyPartLabel, harmonyPartOrder } from '../../lib/songCraft';import { scoreHasMusic } from '../../lib/scoreNotation';@@ -73,7 +73,7 @@ export default function SongScoreParts({ songId, baseScore = '', baseDirty = falconst derive = async () => {setDeriving(true);- const data = await deriveSongParts(songId, { providerId: selectedProviderId, model: selectedModel }, { silent: true })+ const data = await deriveRoundParts(songId, { providerId: selectedProviderId, model: selectedModel }, { silent: true }).catch((err) => { toast.error(err?.message || 'Could not derive harmony parts'); return null; });setDeriving(false);if (!data?.scoreParts?.length) return;diff --git a/client/src/lib/metronome.js b/client/src/lib/metronome.jsindex b6e15e9b54..8a08998ca4 100644--- a/client/src/lib/metronome.js+++ b/client/src/lib/metronome.js@@ -16,8 +16,8 @@import { parseScore } from './scoreNotation.js';-// BPM band — mirrors the server `tempo` validation (services/songs.js-// TEMPO_MIN / TEMPO_MAX, also enforced by the Zod schema in routes/songs.js).+// BPM band — mirrors the server `tempo` validation (services/rounds.js+// TEMPO_MIN / TEMPO_MAX, also enforced by the Zod schema in routes/rounds.js).export const METRONOME_BPM_MIN = 20;export const METRONOME_BPM_MAX = 320;export const DEFAULT_BPM = 120;diff --git a/client/src/pages/SongEditor.jsx b/client/src/pages/RoundEditor.jsxsimilarity index 95%rename from client/src/pages/SongEditor.jsxrename to client/src/pages/RoundEditor.jsxindex 0655c0d462..452c0705d0 100644--- a/client/src/pages/SongEditor.jsx+++ b/client/src/pages/RoundEditor.jsx@@ -1,5 +1,5 @@/**- * Song editor — /songs/:id.+ * Round editor — /rounds/:id.** Two URL-param-driven modes (`?mode=read` default, `?mode=edit`):* - READ: a clean, desktop-wide performance view — lyrics rendered in full@@ -9,7 +9,7 @@* - EDIT: the editing workbench — metadata, lyric sections, voice layers, and* free-text notation + arrangement notes.*- * Full-width route (Layout.jsx isFullWidth matches `/songs/`) so this page owns+ * Full-width route (Layout.jsx isFullWidth matches `/rounds/`) so this page owns* its own vertical scroll, mirroring WritersRoomGuide's column layout. The mode* lives in the URL (not local state) so a view is linkable — per the project's* "linkable routes for all views" convention.@@ -30,7 +30,7 @@ import {} from 'lucide-react';import toast from '../components/ui/Toast';import { useAsyncAction } from '../hooks/useAsyncAction';-import { getSong, updateSong, refreshSongTemplate, listSongs } from '../services/api';+import { getRound, updateRound, refreshRoundTemplate, listRounds } from '../services/api';import { RHYTHM_SHAPES, VOICE_LAYERS, rhythmShapeLabel } from '../lib/songCraft';import Pill from '../components/ui/Pill';import SongAiPanel from '../components/songs/SongAiPanel';@@ -45,7 +45,7 @@ import { scoreHasMusic, parseScore } from '../lib/scoreNotation';import { createMultiScorePlayer, DEFAULT_BPM } from '../lib/scorePlayback';import { harmonyPartOrder } from '../lib/songCraft';-// Cap on partner songs — mirrors services/songs.js PARTNERS_MAX. Used only to+// Cap on partner songs — mirrors services/rounds.js PARTNERS_MAX. Used only to// disable adding more in the editor; the server enforces the real bound.const PARTNERS_MAX = 12;@@ -79,7 +79,7 @@ const localId = (prefix) => `${prefix}-new-${localSeq++}`;// (preset ids like `lead`, server-assigned uuids) so dedup + matching survive.const stripTempId = (row) => (TEMP_ID_RE.test(row.id) ? { ...row, id: '' } : row);-// Mirror the server tempo band (services/songs.js TEMPO_MIN/MAX). We clamp on+// Mirror the server tempo band (services/rounds.js TEMPO_MIN/MAX). We clamp on// BLUR, not on every keystroke — clamping each keystroke would turn typing// "68" into "208" (the lone "6" clamps up to 20 first). While editing we keep// the raw parsed number; clampTempo runs on blur so the saved value lands in@@ -99,7 +99,7 @@ const clampTempo = (n) => {return Math.max(TEMPO_MIN, Math.min(TEMPO_MAX, Math.round(n)));};-export default function SongEditor() {+export default function RoundEditor() {const { id } = useParams();const navigate = useNavigate();const [searchParams, setSearchParams] = useSearchParams();@@ -149,22 +149,22 @@ export default function SongEditor() {// hides the editor (and its Save button) until the new song arrives.setLoading(true);setSong(null);- getSong(id, { silent: true })- .then((data) => { if (!cancelled) setServerSong(data?.song || null); })- .catch((err) => { if (!cancelled) toast.error(err?.message || 'Failed to load song'); })+ getRound(id, { silent: true })+ .then((data) => { if (!cancelled) setServerSong(data?.round || null); })+ .catch((err) => { if (!cancelled) toast.error(err?.message || 'Failed to load round'); }).finally(() => { if (!cancelled) setLoading(false); });return () => { cancelled = true; };}, [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+ // stays mounted across /rounds/:id navigation, so a once-on-mount fetch would// leave partner records (titles, saved takes) stale after editing a partner// and navigating back. The list is small and single-user, so re-fetching on// navigation is cheap and keeps the round stack honest.useEffect(() => {let cancelled = false;- listSongs({ silent: true })- .then((data) => { if (!cancelled) setAllSongs(data?.songs || []); })+ listRounds({ silent: true })+ .then((data) => { if (!cancelled) setAllSongs(data?.rounds || []); }).catch(() => { /* the page degrades to no partner resolution */ });return () => { cancelled = true; };}, [id]);@@ -172,8 +172,8 @@ export default function SongEditor() {// 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]);+ return (song?.partnerRoundIds || []).map((pid) => byId.get(pid)).filter(Boolean);+ }, [allSongs, song?.partnerRoundIds]);// 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 || '')),@@ -181,10 +181,10 @@ export default function SongEditor() {);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) };+ const cur = prev.partnerRoundIds || [];+ if (cur.includes(pid)) return { ...prev, partnerRoundIds: cur.filter((x) => x !== pid) };if (cur.length >= PARTNERS_MAX) return prev;- return { ...prev, partnerSongIds: [...cur, pid] };+ return { ...prev, partnerRoundIds: [...cur, pid] };}), []);// Field setters merge into the in-memory draft; nothing persists until Save.@@ -205,23 +205,23 @@ export default function SongEditor() {scoreParts: (song.scoreParts || []).map(stripTempId),recordings: (song.recordings || []).map(stripTempId),references: (song.references || []).map(stripTempId),- partnerSongIds: song.partnerSongIds || [],+ partnerRoundIds: song.partnerRoundIds || [],};- const data = await updateSong(id, patch, { silent: true });- if (data?.song) setServerSong(data.song);- toast.success('Song saved');- return data?.song;- }, { errorMessage: 'Failed to save song' });+ const data = await updateRound(id, patch, { silent: true });+ if (data?.round) setServerSong(data.round);+ toast.success('Round saved');+ return data?.round;+ }, { errorMessage: 'Failed to save round' });// Restore a built-in default to its shipped content (lyrics, layers,// references). Persists server-side immediately and preserves the user's// recordings + learned progress; replaces any local unsaved edits, so the// BuiltInBanner gates this behind an inline confirm.const [refreshTemplate, refreshing] = useAsyncAction(async () => {- const data = await refreshSongTemplate(id, { silent: true });- if (data?.song) setServerSong(data.song);+ const data = await refreshRoundTemplate(id, { silent: true });+ if (data?.round) setServerSong(data.round);toast.success('Refreshed from the bundled template');- return data?.song;+ return data?.round;}, { errorMessage: 'Failed to refresh from template' });// Merge an AI-generated draft into the editor. The server returns canonical@@ -301,13 +301,13 @@ export default function SongEditor() {}, [song?.layers]);if (loading) {- return <div className="p-6 text-sm text-gray-500">Loading song…</div>;+ return <div className="p-6 text-sm text-gray-500">Loading round…</div>;}if (!song) {return (<div className="p-6">- <p className="text-sm text-gray-400 mb-4">Song not found.</p>- <Link to="/songs" className="text-port-accent hover:underline">← Back to Songs</Link>+ <p className="text-sm text-gray-400 mb-4">Round not found.</p>+ <Link to="/rounds" className="text-port-accent hover:underline">← Back to Rounds</Link></div>);}@@ -321,15 +321,15 @@ export default function SongEditor() {<div className="flex items-center gap-3 px-4 py-3 border-b border-port-border bg-port-card shrink-0"><buttontype="button"- onClick={() => navigate('/songs')}+ onClick={() => navigate("/rounds")}className="p-1 text-gray-400 hover:text-white transition-colors"- title="Back to Songs"- aria-label="Back to Songs"+ title="Back to Rounds"+ aria-label="Back to Rounds"><ArrowLeft size={18} /></button><Music size={18} className="text-port-accent shrink-0" />- <span className="text-white font-semibold truncate flex-1 min-w-0">{song.title || 'Untitled song'}</span>+ <span className="text-white font-semibold truncate flex-1 min-w-0">{song.title || 'Untitled round'}</span>{/* View / Edit toggle — mode lives in the URL so each view is linkable. */}<div className="flex items-center rounded-lg border border-port-border overflow-hidden shrink-0"><button@@ -350,7 +350,7 @@ export default function SongEditor() {</button></div><Link- to="/songs/guide"+ to="/rounds/guide"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"><BookOpen size={14} />@@ -486,7 +486,7 @@ export default function SongEditor() {</div><p className="text-xs text-gray-500 mb-2">Build foundation-first: melody, then bass, then the mid & high harmonies. See the{' '}- <Link to="/songs/guide" className="text-port-accent hover:underline">Learning Guide</Link> for the full ladder.+ <Link to="/rounds/guide" className="text-port-accent hover:underline">Learning Guide</Link> for the full ladder.</p>{remainingPresets.length > 0 && (<div className="flex flex-wrap gap-1.5 mb-3">@@ -550,16 +550,16 @@ export default function SongEditor() {<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+ Link rounds that are sung at the same time — rounds that share a chord cycle. In View, a “Stack parts” buttonrenders 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>+ <p className="text-xs text-gray-500">No other rounds 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;+ const checked = (song.partnerRoundIds || []).includes(s.id);+ const atMax = !checked && (song.partnerRoundIds || []).length >= PARTNERS_MAX;return (<buttonkey={s.id}@@ -570,7 +570,7 @@ export default function SongEditor() {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'}+ {checked ? '✓ ' : '+ '}{s.title || 'Untitled round'}</button>);})}@@ -741,8 +741,8 @@ function ReadView({ song, setField, onRefreshTemplate, refreshing, partnerSongs<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 key={p.id} to={`/rounds/${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 round'}</Link>))}<buttondiff --git a/client/src/pages/SongEditor.test.jsx b/client/src/pages/RoundEditor.test.jsxsimilarity index 62%rename from client/src/pages/SongEditor.test.jsxrename to client/src/pages/RoundEditor.test.jsxindex c12c3a1638..1f77ee4ea6 100644--- a/client/src/pages/SongEditor.test.jsx+++ b/client/src/pages/RoundEditor.test.jsx@@ -3,12 +3,12 @@ import { render, screen, fireEvent, waitFor } from '@testing-library/react';import { MemoryRouter, Routes, Route, useNavigate } from 'react-router-dom';// Mock the api barrel — the editor only needs these few calls, and we control-// getSong timing to exercise the song→song navigation load window.+// getRound timing to exercise the round→round navigation load window.const api = vi.hoisted(() => ({- getSong: vi.fn(),- listSongs: vi.fn(),- updateSong: vi.fn(),- refreshSongTemplate: vi.fn(),+ getRound: vi.fn(),+ listRounds: vi.fn(),+ updateRound: vi.fn(),+ refreshRoundTemplate: vi.fn(),getUploadUrl: (f) => `/api/uploads/${f}`,resolveB: null,}));@@ -19,36 +19,36 @@ vi.mock('../components/songs/SongRecordings', () => ({ default: () => null }));vi.mock('../components/songs/SongScoreEditor', () => ({ default: () => null }));vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));-import SongEditor from './SongEditor.jsx';+import RoundEditor from './RoundEditor.jsx';const song = (id, title) => ({id, title, artist: '', key: '', tempo: null, rhythmShapeId: '', notation: '', score: '',notes: '', learned: false, sections: [], layers: [], recordings: [], references: [],- partnerSongIds: [], builtIn: false, createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',+ partnerRoundIds: [], builtIn: false, createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',});function Harness() {const navigate = useNavigate();return (<>- <button type="button" onClick={() => navigate('/songs/b')}>go-b</button>- <Routes><Route path="/songs/:id" element={<SongEditor />} /></Routes>+ <button type="button" onClick={() => navigate('/rounds/b')}>go-b</button>+ <Routes><Route path="/rounds/:id" element={<RoundEditor />} /></Routes></>);}-describe('SongEditor song→song navigation', () => {+describe('RoundEditor round→round navigation', () => {beforeEach(() => {- api.getSong.mockReset();- api.listSongs.mockReset().mockResolvedValue({ songs: [song('a', 'Song A'), song('b', 'Song B')] });- api.getSong.mockImplementation((id) => {- if (id === 'a') return Promise.resolve({ song: song('a', 'Song A') });- return new Promise((res) => { api.resolveB = () => res({ song: song('b', 'Song B') }); }); // deferred+ api.getRound.mockReset();+ api.listRounds.mockReset().mockResolvedValue({ rounds: [song('a', 'Song A'), song('b', 'Song B')] });+ api.getRound.mockImplementation((id) => {+ if (id === 'a') return Promise.resolve({ round: song('a', 'Song A') });+ return new Promise((res) => { api.resolveB = () => res({ round: song('b', 'Song B') }); }); // deferred});});it('clears the previous draft while the next song loads (no stale-save window)', async () => {- render(<MemoryRouter initialEntries={['/songs/a']}><Harness /></MemoryRouter>);+ render(<MemoryRouter initialEntries={['/rounds/a']}><Harness /></MemoryRouter>);await waitFor(() => expect(screen.getByText('Song A')).toBeTruthy());// Navigate to the partner song; its fetch is still pending.@@ -56,7 +56,7 @@ describe('SongEditor song→song navigation', () => {// The old draft must be gone (so a Save can't write Song A into Song B) and// the loading state shown until the new song arrives.- await waitFor(() => expect(screen.getByText(/Loading song/)).toBeTruthy());+ await waitFor(() => expect(screen.getByText(/Loading round/)).toBeTruthy());expect(screen.queryByText('Song A')).toBeNull();expect(screen.queryByRole('button', { name: /^Save$/ })).toBeNull();diff --git a/client/src/pages/Songs.jsx b/client/src/pages/Rounds.jsxsimilarity index 60%rename from client/src/pages/Songs.jsxrename to client/src/pages/Rounds.jsxindex 0aa8aa5d55..a1c1f64d95 100644--- a/client/src/pages/Songs.jsx+++ b/client/src/pages/Rounds.jsx@@ -1,11 +1,11 @@/**- * Songs page — a cappella song workbench index.+ * Rounds page — a cappella round workbench index.*- * Lists every song the user is writing or learning and lets them create, open,- * or delete any of them. The heavy editor lives at `/songs/:id`; the learning+ * Lists every round the user is writing or learning and lets them create, open,+ * or delete any of them. The heavy editor lives at `/rounds/:id`; the learning* reference (dirge rhythm shapes, the layer ladder, notation help) lives at- * `/songs/guide`. Mirrors the Universes index — a plain padded+scrolling page- * (NOT full-width), one card/row per song.+ * `/rounds/guide`. Mirrors the Universes index — a plain padded+scrolling page+ * (NOT full-width), one card/row per round.*/import { useEffect, useState, useCallback } from 'react';@@ -14,63 +14,65 @@ import { Music, Plus, Trash2, BookOpen, CheckCircle2, Circle, Wand2 } from 'luciimport toast from '../components/ui/Toast';import { timeAgo } from '../utils/formatters';import { useAsyncAction } from '../hooks/useAsyncAction';-import { listSongs, createSong, deleteSong, generateSong } from '../services/api';+import { listRounds, createRound, deleteRound, generateRound } from '../services/api';import { RHYTHM_SHAPES } from '../lib/songCraft';const shapeLabel = (id) => RHYTHM_SHAPES.find((s) => s.id === id)?.label || null;-export default function Songs() {+export default function Rounds() {const navigate = useNavigate();- const [songs, setSongs] = useState([]);+ const [rounds, setRounds] = useState([]);const [loading, setLoading] = useState(true);const [title, setTitle] = useState('');const [artist, setArtist] = useState('');- // Two-step delete confirm (no window.confirm) — the armed song id.+ // Two-step delete confirm (no window.confirm) — the armed round id.const [armed, setArmed] = useState(null);useEffect(() => {- listSongs({ silent: true })- .then((data) => setSongs(Array.isArray(data?.songs) ? data.songs : []))- .catch((err) => toast.error(err?.message || 'Failed to load songs'))+ listRounds({ silent: true })+ .then((data) => setRounds(Array.isArray(data?.rounds) ? data.rounds : []))+ .catch((err) => toast.error(err?.message || 'Failed to load rounds')).finally(() => setLoading(false));}, []);const [create, creating] = useAsyncAction(async () => {const name = title.trim();- if (!name) { toast.error('Give the song a title'); return null; }- const data = await createSong({ title: name, artist: artist.trim() }, { silent: true });- const song = data?.song;- // A blank new song has nothing to read — open straight into edit mode.- if (song) navigate(`/songs/${song.id}?mode=edit`);- return song;- }, { errorMessage: 'Failed to create song' });+ if (!name) { toast.error('Give the round a title'); return null; }+ const data = await createRound({ title: name, artist: artist.trim() }, { silent: true });+ const round = data?.round;+ // A blank new round has nothing to read — open straight into edit mode.+ if (round) navigate(`/rounds/${round.id}?mode=edit`);+ return round;+ }, { errorMessage: 'Failed to create round' });// Generate a full draft from the title/artist as a brief, persist it, then- // open the editor on the new song. Two server calls (generate → create) keep+ // open the editor on the new round. Two server calls (generate → create) keep// the AI service stateless about storage; the editor's own Generate/Expand- // buttons drive subsequent rounds.+ // buttons drive subsequent rounds. NOTE: the generate endpoint returns the+ // drafted arrangement under `song` (the AI payload shape); create returns the+ // stored record under `round`.const [generate, generating] = useAsyncAction(async () => {const name = title.trim();- const data = await generateSong(+ const data = await generateRound({ title: name || undefined, artist: artist.trim() || undefined },{ silent: true },);const fields = data?.song;if (!fields) { toast.error('Generation produced nothing — try again'); return null; }- const created = await createSong(fields, { silent: true });- const song = created?.song;+ const created = await createRound(fields, { silent: true });+ const round = created?.round;// Unlike a blank create, a generated draft already has lyrics — open the// read view so the user sees the result, then toggle to Edit to refine.- if (song) navigate(`/songs/${song.id}`);- return song;- }, { errorMessage: 'Failed to generate song' });+ if (round) navigate(`/rounds/${round.id}`);+ return round;+ }, { errorMessage: 'Failed to generate round' });- const onDelete = useCallback(async (song) => {- if (armed !== song.id) { setArmed(song.id); return; }+ const onDelete = useCallback(async (round) => {+ if (armed !== round.id) { setArmed(round.id); return; }setArmed(null);- await deleteSong(song.id, { silent: true })- .then(() => setSongs((prev) => prev.filter((s) => s.id !== song.id)))- .catch((err) => toast.error(err?.message || 'Failed to delete song'));+ await deleteRound(round.id, { silent: true })+ .then(() => setRounds((prev) => prev.filter((s) => s.id !== round.id)))+ .catch((err) => toast.error(err?.message || 'Failed to delete round'));}, [armed]);return (@@ -78,10 +80,10 @@ export default function Songs() {<div className="flex items-center justify-between gap-3 mb-2"><div className="flex items-center gap-3"><Music className="w-6 h-6 text-port-accent" />- <h1 className="text-2xl font-bold text-white">Songs</h1>+ <h1 className="text-2xl font-bold text-white">Rounds</h1></div><Link- to="/songs/guide"+ to="/rounds/guide"className="flex items-center gap-2 px-3 py-2 text-sm rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50"><BookOpen size={16} />@@ -89,7 +91,7 @@ export default function Songs() {</Link></div><p className="text-sm text-gray-400 mb-6">- Write and learn a cappella songs — dirges, ballads, and harmonies. Track lyrics,+ Write and learn a cappella rounds — dirges, ballads, and harmonies. Track lyrics,rhythm shapes, and the voice layers you're stacking.</p>@@ -99,9 +101,9 @@ export default function Songs() {className="bg-port-card border border-port-border rounded-lg p-4 mb-6 flex flex-col sm:flex-row gap-3 sm:items-end"><div className="flex-1">- <label htmlFor="song-title" className="block text-xs text-gray-400 mb-1">Title</label>+ <label htmlFor="round-title" className="block text-xs text-gray-400 mb-1">Title</label><input- id="song-title"+ id="round-title"type="text"value={title}onChange={(e) => setTitle(e.target.value)}@@ -110,9 +112,9 @@ export default function Songs() {/></div><div className="flex-1">- <label htmlFor="song-artist" className="block text-xs text-gray-400 mb-1">Artist (optional)</label>+ <label htmlFor="round-artist" className="block text-xs text-gray-400 mb-1">Artist (optional)</label><input- id="song-artist"+ id="round-artist"type="text"value={artist}onChange={(e) => setArtist(e.target.value)}@@ -127,7 +129,7 @@ export default function Songs() {className="flex items-center justify-center gap-2 px-4 py-2 text-sm rounded-lg bg-port-accent text-white hover:bg-port-accent/90 disabled:opacity-50"><Plus size={16} />- New Song+ New Round</button><buttontype="button"@@ -144,47 +146,47 @@ export default function Songs() {{/* List */}{loading ? (- <p className="text-sm text-gray-500">Loading songs…</p>- ) : songs.length === 0 ? (- <p className="text-sm text-gray-500">No songs yet — write your first above.</p>+ <p className="text-sm text-gray-500">Loading rounds…</p>+ ) : rounds.length === 0 ? (+ <p className="text-sm text-gray-500">No rounds yet — write your first above.</p>) : (<ul className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">- {songs.map((song) => {- const shape = shapeLabel(song.rhythmShapeId);- const layerCount = song.layers?.length || 0;+ {rounds.map((round) => {+ const shape = shapeLabel(round.rhythmShapeId);+ const layerCount = round.layers?.length || 0;return (<li- key={song.id}+ key={round.id}className="group bg-port-card border border-port-border rounded-lg flex items-center gap-3 px-4 py-3 hover:border-port-accent/50">- <Link to={`/songs/${song.id}`} className="flex-1 min-w-0">+ <Link to={`/rounds/${round.id}`} className="flex-1 min-w-0"><div className="flex items-center gap-2 min-w-0">- {song.learned+ {round.learned? <CheckCircle2 size={16} className="text-port-success shrink-0" aria-label="Learned" />: <Circle size={16} className="text-gray-600 shrink-0" aria-label="In progress" />}- <span className="flex-1 min-w-0 text-white font-medium truncate" title={song.title}>{song.title}</span>- {song.builtIn && (+ <span className="flex-1 min-w-0 text-white font-medium truncate" title={round.title}>{round.title}</span>+ {round.builtIn && (<span className="shrink-0 inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] uppercase tracking-wide bg-port-accent/10 text-port-accent border border-port-accent/20">Built-in</span>)}</div><div className="flex flex-wrap gap-x-3 gap-y-0.5 text-xs text-gray-500 mt-1 pl-6">- {song.artist && <span className="text-gray-400">{song.artist}</span>}- {song.key && <span>Key: {song.key}</span>}- {song.tempo && <span>{song.tempo} BPM</span>}+ {round.artist && <span className="text-gray-400">{round.artist}</span>}+ {round.key && <span>Key: {round.key}</span>}+ {round.tempo && <span>{round.tempo} BPM</span>}{shape && <span>{shape}</span>}{layerCount > 0 && <span>{layerCount} layer{layerCount === 1 ? '' : 's'}</span>}- {song.updatedAt && <span>Edited {timeAgo(song.updatedAt)}</span>}+ {round.updatedAt && <span>Edited {timeAgo(round.updatedAt)}</span>}</div></Link><buttontype="button"- onClick={() => onDelete(song)}- onBlur={() => setArmed((cur) => (cur === song.id ? null : cur))}- className={`p-2 shrink-0 ${armed === song.id ? 'text-port-error' : 'text-gray-500 hover:text-port-error'}`}- aria-label={armed === song.id ? `Confirm delete ${song.title}` : `Delete ${song.title}`}- title={armed === song.id ? 'Click again to confirm delete' : 'Delete song'}+ onClick={() => onDelete(round)}+ onBlur={() => setArmed((cur) => (cur === round.id ? null : cur))}+ className={`p-2 shrink-0 ${armed === round.id ? 'text-port-error' : 'text-gray-500 hover:text-port-error'}`}+ aria-label={armed === round.id ? `Confirm delete ${round.title}` : `Delete ${round.title}`}+ title={armed === round.id ? 'Click again to confirm delete' : 'Delete round'}><Trash2 size={16} /></button>diff --git a/client/src/pages/SongsGuide.jsx b/client/src/pages/RoundsGuide.jsxsimilarity index 95%rename from client/src/pages/SongsGuide.jsxrename to client/src/pages/RoundsGuide.jsxindex ec7730db4e..62bf3ee1d0 100644--- a/client/src/pages/SongsGuide.jsx+++ b/client/src/pages/RoundsGuide.jsx@@ -1,11 +1,11 @@/**- * Songs Guide — deep-linkable learning reference at /songs/guide.+ * Rounds Guide — deep-linkable learning reference at /rounds/guide.** Renders directly from the canonical reference data in lib/songCraft.js so the* dirge rhythm shapes, the foundation-first layer ladder, the practice* sequence, and the notation primers stay in sync with the Song editor's* pickers (which read the same arrays). The parent <main> is full-width /- * overflow-hidden (Layout.jsx isFullWidth matches `/songs/`), so this page owns+ * overflow-hidden (Layout.jsx isFullWidth matches `/rounds/`), so this page owns* its own vertical scroll — mirrors WritersRoomGuide.*/@@ -71,20 +71,20 @@ function SectionHeading({ icon: Icon, title, subtitle }) {);}-export default function SongsGuide() {+export default function RoundsGuide() {return (<div className="flex flex-col h-full"><div className="flex items-center gap-3 px-4 py-3 border-b border-port-border bg-port-card shrink-0"><Link- to="/songs"+ to="/rounds"className="p-1 text-gray-400 hover:text-white transition-colors"- title="Back to Songs"- aria-label="Back to Songs"+ title="Back to Rounds"+ aria-label="Back to Rounds"><ArrowLeft size={18} /></Link><Music size={18} className="text-port-accent shrink-0" />- <span className="text-white font-semibold">Songs · Learning Guide</span>+ <span className="text-white font-semibold">Rounds · Learning Guide</span></div><div className="flex-1 overflow-y-auto p-4 md:p-6">diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 7bb8aa5ecc..1fb3c3a13f 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -50,7 +50,7 @@ export * from './apiUniverseBuilder.js';export * from './apiAuthors.js';export * from './apiPipeline.js';export * from './apiSharing.js';-export * from './apiSongs.js';+export * from './apiRounds.js';export * from './apiPeerSync.js';export * from './apiSyncReview.js';export * from './apiCreativeDirector.js';diff --git a/client/src/services/apiRounds.js b/client/src/services/apiRounds.jsnew file mode 100644index 0000000000..2253d40574--- /dev/null+++ b/client/src/services/apiRounds.js@@ -0,0 +1,48 @@+import { request } from './apiCore.js';++// Rounds workbench API surface (a cappella round writing + learning). Every+// helper takes an optional `options` arg so callers with their own `.catch`+// toast can pass `{ silent: true }` to avoid a double-toast (project+// convention). The id path param is URL-encoded.++const enc = encodeURIComponent;++export const listRounds = (options) => request('/rounds', options);++export const getRound = (id, options) => request(`/rounds/${enc(id)}`, options);++export const createRound = (body = {}, options) =>+ request('/rounds', { method: 'POST', body: JSON.stringify(body), ...options });++export const updateRound = (id, patch, options) =>+ request(`/rounds/${enc(id)}`, { method: 'PUT', body: JSON.stringify(patch), ...options });++export const deleteRound = (id, options) =>+ request(`/rounds/${enc(id)}`, { method: 'DELETE', ...options });++// Reset a built-in default song's shipped content (metadata/lyrics/layers/+// references) to the current bundled template → { song }. Preserves the user's+// recordings + learned progress. 400 if the song isn't a built-in default.+export const refreshRoundTemplate = (id, options) =>+ request(`/rounds/${enc(id)}/refresh-template`, { method: 'POST', ...options });++// AI: draft a brand-new arrangement from a brief (no id, not persisted) →+// { song, llm }. body: { title?, artist?, brief?, mood?, providerId?, model? }.+export const generateRound = (body = {}, options) =>+ request('/rounds/generate', { method: 'POST', body: JSON.stringify(body), ...options });++// AI: expand/redraft an existing song → { song, llm }. Pass expandExisting:true+// to fold the stored draft into the prompt. Client merges the result; no save.+export const generateRoundFor = (id, body = {}, options) =>+ request(`/rounds/${enc(id)}/generate`, { method: 'POST', body: JSON.stringify(body), ...options });++// AI: critique a stored arrangement → { evaluation, llm }. Read-only server-side.+export const evaluateRound = (id, body = {}, options) =>+ request(`/rounds/${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 deriveRoundParts = (id, body = {}, options) =>+ request(`/rounds/${enc(id)}/derive-parts`, { method: 'POST', body: JSON.stringify(body), ...options });diff --git a/client/src/services/apiSongs.js b/client/src/services/apiSongs.jsdeleted file mode 100644index b937008de2..0000000000--- a/client/src/services/apiSongs.js+++ /dev/null@@ -1,48 +0,0 @@-import { request } from './apiCore.js';--// Songs workbench API surface (a cappella song writing + learning). Every-// helper takes an optional `options` arg so callers with their own `.catch`-// toast can pass `{ silent: true }` to avoid a double-toast (project-// convention). The id path param is URL-encoded.--const enc = encodeURIComponent;--export const listSongs = (options) => request('/songs', options);--export const getSong = (id, options) => request(`/songs/${enc(id)}`, options);--export const createSong = (body = {}, options) =>- request('/songs', { method: 'POST', body: JSON.stringify(body), ...options });--export const updateSong = (id, patch, options) =>- request(`/songs/${enc(id)}`, { method: 'PUT', body: JSON.stringify(patch), ...options });--export const deleteSong = (id, options) =>- request(`/songs/${enc(id)}`, { method: 'DELETE', ...options });--// Reset a built-in default song's shipped content (metadata/lyrics/layers/-// references) to the current bundled template → { song }. Preserves the user's-// recordings + learned progress. 400 if the song isn't a built-in default.-export const refreshSongTemplate = (id, options) =>- request(`/songs/${enc(id)}/refresh-template`, { method: 'POST', ...options });--// AI: draft a brand-new arrangement from a brief (no id, not persisted) →-// { song, llm }. body: { title?, artist?, brief?, mood?, providerId?, model? }.-export const generateSong = (body = {}, options) =>- request('/songs/generate', { method: 'POST', body: JSON.stringify(body), ...options });--// AI: expand/redraft an existing song → { song, llm }. Pass expandExisting:true-// to fold the stored draft into the prompt. Client merges the result; no save.-export const generateSongFor = (id, body = {}, options) =>- request(`/songs/${enc(id)}/generate`, { method: 'POST', body: JSON.stringify(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/docs/plans/2026-06-20-music-studio-and-rounds-rename.md b/docs/plans/2026-06-20-music-studio-and-rounds-rename.mdnew file mode 100644index 0000000000..770e311782--- /dev/null+++ b/docs/plans/2026-06-20-music-studio-and-rounds-rename.md@@ -0,0 +1,181 @@+# Rename Songs→Rounds + new Music studio (Artists, Albums, Tracks, Ace-Step gen)++## Context++The **Songs** page (`/songs`) is an a cappella composition/learning workbench (rounds, harmony parts,+recordings, score notation) backed by `data/songs.json` + `/api/songs` + `server/services/songs.js`. Its+real subject is musical *rounds*, so we're renaming it to **Rounds** (full-stack, per user decision).++Separately we want a new **Music** studio under the *Create* section for generating music with local+OSS tools (Ace-Step first; room for Google Music / ElevenLabs / Suno later), organized into+**tracks/singles** and **albums**, each with **album art** (AI-generated via the existing image-gen+options *or* uploaded) and a **designing artist** persona managed like Authors.++Key discovery: PortOS already has most of the music backbone — `server/services/pipeline/musicGen.js`+(engine-agnostic `ENGINES` registry: `musicgen` + `audioldm2`, sidecar+venv gated, `generateMusic()`),+`server/services/pipeline/musicLibrary.js` (`data/music/` shared library), venv provisioning in+`scripts/setup-image-video.sh` + `server/lib/pythonSetup.js`, and the `imageGen/` provider-dispatcher+for album art. **Authors** (`server/services/authors/{index,logic,db,file}.js`) is the exact db-primary,+federated, soft-delete template to mirror for Artists/Albums/Tracks. So this is mostly *composition of+existing patterns*, not green-field.++**Delivery: phased — 4 sequenced PRs off this branch**, each independently reviewable/shippable.++---++## Phase 1 — Songs → Rounds full-stack rename (PR 1)++Full-stack rename incl. data file + API. Songs are **not federated today** (absent from+`schemaVersions.js`, `peerSync.js`), so the rename has **zero cross-install sync surface** — no+`schemaVersions` bump needed (we keep Rounds local-only, matching Songs today).++**Data migration** — new `scripts/migrations/0NN-rename-songs-to-rounds-data.js`, modeled on+`scripts/migrations/031-world-to-universe-data-rename.js` (idempotent: skip if already migrated, warn if+both files exist):+- `data/songs.json` → `data/rounds.json`+- top-level key `songs[]` → `rounds[]`+- grep for cross-file refs (`songId`, partner song ids, dashboard widget refs) and rewrite+- add a `.test.js` beside it (migrations carry tests here, e.g. `074-*.test.js`)++**Server rename:**+- `server/services/songs.js` → `rounds.js` (`STATE_PATH` → `data/rounds.json`; rename exported+ identifiers `listSongs`→`listRounds`, etc., keep bounds constants)+- `server/services/songsAI.js` → `roundsAI.js`+- `server/routes/songs.js` → `routes/rounds.js` (mount `/api/rounds` in `server/index.js:547`)+- `server/lib/songCraftRef.js` → `roundCraftRef.js` (consumed by guide)+- nav manifest `server/lib/navManifest.js:34-35`: `nav.create.songs`→`nav.create.rounds`,+ `/songs`→`/rounds`, label `Songs`→`Rounds`, update aliases/keywords+- rename `*.test.js` siblings; update migrations `073-079,086` imports (`services/songs.js`→`rounds.js`)++**Client rename:**+- `pages/Songs.jsx`→`Rounds.jsx`, `SongEditor.jsx`→`RoundEditor.jsx`, `SongsGuide.jsx`→`RoundsGuide.jsx`+- `services/apiSongs.js`→`apiRounds.js` (paths `/songs`→`/rounds`, fn names), update `services/api.js:53`+- `App.jsx:52-54,295-297` lazy imports + routes (`/songs*`→`/rounds*`)+- `Layout.jsx:209` sidebar link + `:1134` full-width prefix `/songs/`→`/rounds/`+- `components/songs/` dir + `lib/song*.js` + `hooks/useSongTraining.js`: keep internal names to limit+ churn, but rename the *page-facing* pieces and `/songs/:id` links in `RoundStack.jsx`, `RoundEditor`,+ `RoundsGuide`. (Component-internal "song" vocabulary may stay — user-facing label/route is the contract.)++**Verify:** `cd server && npm test`; `cd client && npm test`; boot (`npm run dev`), confirm `/rounds`+loads, create/edit/delete a round, `/rounds/guide` renders, ⌘K "rounds" navigates, and a fresh boot+runs the migration (rename a copy of `data/songs.json` back and watch it convert). Grep for stray+`/songs` / `Songs` references.++---++## Phase 2 — Music page shell + Artist management (PR 2)++New **Music** page under *Create* + **Artists** (designing-artist personas), mirroring **Authors** 1:1.++**Artists entity (db-primary, federated — mirror `server/services/authors/`):**+- `server/services/artists/{logic,db,file,index}.js` — copy authors, id `artist-<uuid>`; fields:+ `name`, `bio`, `genre`, `musicalStyle` (voice/production notes for gen prompts),+ `physicalDescription` + `portraitStyle` (for portrait render), `portraitImageUrl` (gen/upload/gallery).+ Reuse `logic.js` sanitize/build/patch/merge shapes verbatim.+- Postgres `artists` table: add DDL to `server/scripts/init-db.sql` (after authors ~768) **and**+ `ensureSchema()` in `server/lib/db.js` (~946) — same `id/name/data JSONB/timestamps/deleted` shape ++ `idx_artists_live`.+- `server/routes/artists.js` (mirror `routes/authors.js`); mount in `server/index.js`.+- **Federation registration** (mirror the author touch-points found in exploration):+ `schemaVersions.js` (`PORTOS_SCHEMA_VERSIONS.artists:1`, `RECORD_KIND_SCHEMA_CATEGORIES.artist`),+ `peerSync.js` (`PEER_SUBSCRIBABLE_KINDS`, `KIND_TO_CATEGORY`, merge handler, asset manifest for+ portrait, syncability), `syncWire.js` sanitizer case, tombstone GC sweep. Auto-subscribe on create.+- `client/src/services/apiArtists.js` (mirror `apiAuthors.js`, re-export from `api.js`).++**Music page + Artist UI:**+- `client/src/pages/Music.jsx` — landing/studio: tabs or sections for **Artists**, **Albums**, **Tracks**+ (URL-param routed per convention, e.g. `/music/artists`, not local tab state). Start with the Artists+ tab fully working; Albums/Tracks land in Phase 3.+- Artist editor: master-detail copy of `pages/Authors.jsx` (portrait via `generateImage` /+ `uploadGalleryImage` / `GalleryImagePicker`, `useMediaJobProgress`, `buildHeadshotPrompt`→+ `buildPortraitPrompt`). Reuse `components/pipeline/AuthorPicker.jsx` → new `ArtistPicker.jsx`.+- Nav: add `App.jsx` routes, `Layout.jsx` *Create* sidebar link (alphabetical: "Music" sits between+ "Mood Boards" and "Series Pipeline"), and `NAV_COMMANDS` entries in `navManifest.js`+ (`nav.create.music`, `nav.create.music-artists`, …).++**Verify:** `server`+`client` tests (add `artists/*.test.js`, `routes/artists.test.js` mirroring+authors); boot, create an Artist, generate + upload a portrait, ⌘K "music"/"artists" navigates,+`navManifest.test.js` + `palette.test.js` green.++---++## Phase 3 — Albums + Tracks data model, album art, library + playback (PR 3)++**Albums & Tracks (db-primary, federated — same authors template):**+- `server/services/albums/` — id `album-<uuid>`; fields: `title`, `artistId` (FK) + `artist`+ (denormalized name, like series→author), `description`, `genre`, `releaseYear`, `coverImageUrl`+ (gen/upload), `trackIds[]` (ordered). DDL + ensureSchema + routes + federation (cover image as synced+ asset) + `apiAlbums.js`.+- `server/services/tracks/` — id `track-<uuid>`; fields: `title`, `albumId?` (null = single), `artistId`,+ `lyrics`, `prompt`, `engine`, `modelId`, `durationSec`, `audioFilename` (points into `data/music/`+ via `musicLibrary.js`), `order`. DDL + ensureSchema + routes + federation (audio file as synced asset,+ mirroring author headshot-filename asset path) + `apiTracks.js`.+- Reuse `server/services/pipeline/musicLibrary.js` for the actual audio files (`data/music/`); tracks+ store the library filename, not bytes.++**Album art** — reuse image-gen wholesale: `/image-gen/generate` (cover prompt from album+title+genre+artist style, e.g. 1024×1024) and `/image-gen/upload` + `GalleryImagePicker`, storing+`coverImageUrl` exactly like author headshots. No new image infra.++**Album/Track UI (in `Music.jsx`):** album grid + detail (cover, artist via `ArtistPicker`, ordered+track list, add/reorder/remove), track editor (title/lyrics/prompt/engine/duration + audio player).+Reuse `formatTimecode`/`formatDurationMs` from `client/src/utils/formatters.js`, `useLockToggle`,+existing audio `<audio>` playback pattern from AudioStage. Upload audio via the `/api/uploads` or+music-library upload path.++**Verify:** tests for albums/tracks services+routes; boot, create an album under an artist, generate ++upload cover art, add tracks (upload an mp3/wav), reorder, play back in-page; confirm album/track+records federate (asset manifest includes cover + audio).++---++## Phase 4 — Ace-Step engine + real generation wired to Tracks (PR 4)++Add **Ace-Step** as a third `ENGINES` entry in `server/services/pipeline/musicGen.js` — the registry is+already engine-agnostic, so this is additive. Ace-Step is full-song (prompt **+ lyrics + duration**),+richer than the background-music sidecars, so extend the sidecar contract with an optional `--lyrics`+flag (musicgen/audioldm2 ignore it).++- **Python sidecar** `scripts/generate_acestep.py` — mirror `generate_musicgen.py`/`generate_audioldm2.py`+ contract: `--model --text [--lyrics] --duration --output --runtime-dir`, emit `STAGE:` progress lines+ + final `RESULT:{json}` (path, durationSec), write WAV to `--output`. Ace-Step supports Apple Silicon+ (MPS) per upstream (https://github.com/ace-step/ACE-Step-1.5).+- **Venv provisioning** — add `INSTALL_ACESTEP=1` block to `scripts/setup-image-video.sh`+ (clone `ace-step/ACE-Step-1.5`, create `~/.portos/venv-acestep`, pip install its requirements, model+ weights lazy-download on first run via HF, gated by `hfTokenEnv()`), and resolver constants in+ `server/lib/pythonSetup.js` (`ACESTEP_VENV_*`, `ACESTEP_RUNTIME_DIR`, `resolveAcestepPython`).+- **Registry entry** in `musicGen.js`: `ENGINES.acestep` (models/duration window/scriptPath/resolver/+ installEnv `INSTALL_ACESTEP`). `generateMusic({ engine:'acestep', prompt, lyrics, durationSec })`+ works through the existing gate (503 with install hint when venv missing — exactly like FLUX.2).+ Thread `lyrics` through `buildSidecarArgs`.+- **Standalone generation route** — new `server/routes/music.js` `POST /api/music/generate` (the pipeline+ path is audio-stage-internal; the Music studio needs its own). Calls `generateMusic`, lands the WAV in+ `musicLibrary`, and on success creates/updates a **Track** with the engine/model/lyrics/prompt+ metadata + `audioFilename`. Long renders: reuse `mediaJobQueue` (new `kind:'music'`) for async + SSE+ progress, mirroring image-gen — or run inline with the existing AbortSignal cancel if acceptable.+- **UI** in the Track editor: engine picker (musicgen/audioldm2/acestep), readiness gate via+ `isEngineReady`/a `/api/music/engines` status endpoint (show "Run `INSTALL_ACESTEP=1 …`" hint when not+ provisioned), prompt+lyrics+duration inputs, Generate button → SSE progress → attach audio to track.++**Verify:** unit-test `buildSidecarArgs` lyrics threading + engine registry (no Python needed, like+`musicGen.test.js`); on the M5 Max box (128GB) run `INSTALL_ACESTEP=1 bash scripts/setup-image-video.sh`,+generate a real short track from the Music page, confirm WAV lands in `data/music/`, plays back, and the+Track record persists with correct metadata. Confirm graceful 503 + install hint when venv absent.++---++## Cross-cutting notes++- **CLAUDE.md compliance:** every new `apiX.js`/lib module → barrel `index.js` + `README.md` row (enforced+ by `index.test.js`); all route inputs Zod-validated (POST + PUT/PATCH `.partial()`); new pages → both+ `<Route>` **and** `NAV_COMMANDS`; sidebar stays alphabetical; new entities follow `docs/STORAGE.md`+ db-primary classification (Postgres, not new `data/*.json`); schema parity when adding fields.+- **Tests:** never run `*.db.test.js` against real `portos` DB — use `npm run test:db` (→ `portos_test`).+ Mirror authors' `file.js` backend so service tests run without Postgres.+- **Federation schemaVersions:** Artists/Albums/Tracks each get their own per-category gate (`artists`,+ `albums`, `tracks`) so a newer peer can't corrupt an older one; follow the authors `v1` precedent+ comment block in `schemaVersions.js`.+- **Run `/simplify`** after each phase's substantive work; commit + open PR per phase (rebase-merge, no+ squash, no AI attribution per global instructions).+- **Defer/PLAN.md:** future engines (Google Music/ElevenLabs/Suno as `external` HTTP providers mirroring+ `imageGen/external.js`) are explicitly out of scope here — capture as a PLAN.md item after Phase 4.diff --git a/scripts/migrations/073-seed-500-miles-score.js b/scripts/migrations/073-seed-500-miles-score.jsindex 1e21e43cd4..0c4b8e695d 100644--- a/scripts/migrations/073-seed-500-miles-score.js+++ b/scripts/migrations/073-seed-500-miles-score.js@@ -3,16 +3,16 @@* installs that seeded it before the Sheet music feature existed.** Background:- * `server/services/songs.js#SEED_SONGS` now ships a `score` (the verse melody+ * `server/services/rounds.js#SEED_ROUNDS` now ships a `score` (the verse melody* in the PortOS lead-sheet DSL), but that only reaches installs on their FIRST* read of songs (when the file is seeded). An install that already persisted* `data/songs.json` keeps its old `seed-500-miles` record, which has no score.* This migration adds the shipped score to that record IF it has none — a* user who already wrote their own score is never clobbered. The user can also* pull the latest bundled content any time via the song's "Refresh from- * template" button (refreshSongFromTemplate), which carries the score too.+ * template" button (refreshRoundFromTemplate), which carries the score too.*- * Fresh installs need nothing here: SEED_SONGS already includes the score, so+ * Fresh installs need nothing here: SEED_ROUNDS already includes the score, so* a missing file is a clean no-op. Re-runs detect the score is present and skip.*/@@ -21,8 +21,8 @@ import { join } from 'path';const SONG_ID = 'seed-500-miles';-// The shipped melody — kept identical to SEED_SONGS[seed-500-miles].score in-// server/services/songs.js (the migration test asserts they match, so a drift+// The shipped melody — kept identical to SEED_ROUNDS[seed-500-miles].score in+// server/services/rounds.js (the migration test asserts they match, so a drift// fails CI rather than silently shipping two different scores). Now the full// song (all verses + closing coda) in G major; migration 075 upgrades installs// that still hold the earlier C-major backfill.diff --git a/scripts/migrations/073-seed-500-miles-score.test.js b/scripts/migrations/073-seed-500-miles-score.test.jsindex a8d30d2952..fd83f23b3b 100644--- a/scripts/migrations/073-seed-500-miles-score.test.js+++ b/scripts/migrations/073-seed-500-miles-score.test.js@@ -4,7 +4,7 @@ import { tmpdir } from 'os';import { join } from 'path';import migration, { SCORE_500_MILES } from './073-seed-500-miles-score.js';-import { SEED_SONGS } from '../../server/services/songs.js';+import { SEED_ROUNDS } from '../../server/services/rounds.js';const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));@@ -25,7 +25,7 @@ describe('migration 073 — backfill 500 Miles sheet-music score', () => {});it('does not drift from the shipped seed score', () => {- const seed = SEED_SONGS.find((s) => s.id === 'seed-500-miles');+ const seed = SEED_ROUNDS.find((s) => s.id === 'seed-500-miles');expect(seed.score).toBe(SCORE_500_MILES);});diff --git a/scripts/migrations/074-seed-musical-rounds.js b/scripts/migrations/074-seed-musical-rounds.jsindex 7e33492021..6260bb72d7 100644--- a/scripts/migrations/074-seed-musical-rounds.js+++ b/scripts/migrations/074-seed-musical-rounds.js@@ -4,25 +4,25 @@* data/songs.json before these rounds shipped.** Background:- * server/services/songs.js#SEED_SONGS now ships four rounds in addition to+ * server/services/rounds.js#SEED_ROUNDS 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+ * Fresh installs need nothing here: SEED_ROUNDS 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+ * The records come straight from SEED_ROUNDS (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';+import { SEED_ROUNDS, sanitizeRound } from '../../server/services/rounds.js';export const ROUND_IDS = ['seed-hey-ho-nobody-home',@@ -32,10 +32,10 @@ export const ROUND_IDS = [];// The shipped round records in canonical on-disk shape — exactly what a fresh-// seed write produces (listSongs persists SEED_SONGS.map(sanitizeSong)).+// seed write produces (listRounds persists SEED_ROUNDS.map(sanitizeRound)).export const ROUND_SEEDS = ROUND_IDS- .map((id) => SEED_SONGS.find((s) => s.id === id))- .map(sanitizeSong);+ .map((id) => SEED_ROUNDS.find((s) => s.id === id))+ .map(sanitizeRound);const fileExists = (path) => stat(path).then(() => true, (err) => {if (err.code === 'ENOENT') return false;diff --git a/scripts/migrations/074-seed-musical-rounds.test.js b/scripts/migrations/074-seed-musical-rounds.test.jsindex f01e91251e..cc075e5999 100644--- a/scripts/migrations/074-seed-musical-rounds.test.js+++ b/scripts/migrations/074-seed-musical-rounds.test.js@@ -4,7 +4,7 @@ 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';+import { SEED_ROUNDS, sanitizeRound } from '../../server/services/rounds.js';const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));@@ -25,14 +25,14 @@ describe('migration 074 — backfill the four built-in rounds', () => {});it('does not drift from the shipped seed rounds', () => {- // ROUND_SEEDS is derived from SEED_SONGS, so this guards the id list and the+ // ROUND_SEEDS is derived from SEED_ROUNDS, 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 seed = SEED_ROUNDS.find((s) => s.id === id);+ expect(seed, `SEED_ROUNDS missing ${id}`).toBeTruthy();const round = ROUND_SEEDS.find((s) => s.id === id);- expect(round).toEqual(sanitizeSong(seed));+ expect(round).toEqual(sanitizeRound(seed));}});@@ -51,7 +51,7 @@ describe('migration 074 — backfill the four built-in rounds', () => {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');+ expect(heyHo.partnerRoundIds).toContain('seed-ah-poor-bird');});it('only adds the rounds that are missing', async () => {diff --git a/scripts/migrations/075-correct-500-miles-melody.test.js b/scripts/migrations/075-correct-500-miles-melody.test.jsindex fe9f3ae6bb..360e209e54 100644--- a/scripts/migrations/075-correct-500-miles-melody.test.js+++ b/scripts/migrations/075-correct-500-miles-melody.test.js@@ -5,7 +5,7 @@ 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';+import { SEED_ROUNDS } from '../../server/services/rounds.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).@@ -40,7 +40,7 @@ describe('migration 075 — correct 500 Miles melody to G major', () => {});it('the corrected score equals the shipped seed (no drift)', () => {- const seed = SEED_SONGS.find((s) => s.id === 'seed-500-miles');+ const seed = SEED_ROUNDS.find((s) => s.id === 'seed-500-miles');expect(seed.score).toBe(NEW_SCORE);expect(seed.key).toBe('G major');});diff --git a/scripts/migrations/076-seed-500-miles-harmony-parts.js b/scripts/migrations/076-seed-500-miles-harmony-parts.jsindex 85ebdcd313..5dfea5c629 100644--- a/scripts/migrations/076-seed-500-miles-harmony-parts.js+++ b/scripts/migrations/076-seed-500-miles-harmony-parts.js@@ -4,7 +4,7 @@* no sheet-music parts.** Background:- * `server/services/songs.js#SEED_SONGS` now ships "500 Miles" with a full+ * `server/services/rounds.js#SEED_ROUNDS` now ships "500 Miles" with a full* chord-tone harmony stack (SEED_500_MILES_SCORE_PARTS) as the worked example* for the AI-derive feature. Fresh installs seed it directly. An install that* already persisted `data/songs.json` keeps its existing `seed-500-miles`@@ -21,7 +21,7 @@import { readFile, writeFile, stat } from 'fs/promises';import { join } from 'path';-import { SEED_500_MILES_SCORE_PARTS } from '../../server/services/songs.js';+import { SEED_500_MILES_SCORE_PARTS } from '../../server/services/rounds.js';const SONG_ID = 'seed-500-miles';diff --git a/scripts/migrations/076-seed-500-miles-harmony-parts.test.js b/scripts/migrations/076-seed-500-miles-harmony-parts.test.jsindex 20e639e5d5..08f01d344f 100644--- a/scripts/migrations/076-seed-500-miles-harmony-parts.test.js+++ b/scripts/migrations/076-seed-500-miles-harmony-parts.test.js@@ -4,7 +4,7 @@ import { tmpdir } from 'os';import { join } from 'path';import migration from './076-seed-500-miles-harmony-parts.js';-import { SEED_500_MILES_SCORE_PARTS, SEED_SONGS } from '../../server/services/songs.js';+import { SEED_500_MILES_SCORE_PARTS, SEED_ROUNDS } from '../../server/services/rounds.js';import { parseScore } from '../../client/src/lib/scoreNotation.js';const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');@@ -26,7 +26,7 @@ describe('migration 076 — seed 500 Miles harmony parts', () => {});it('the seed song carries the five shipped harmony parts (single source)', () => {- const seed = SEED_SONGS.find((s) => s.id === 'seed-500-miles');+ const seed = SEED_ROUNDS.find((s) => s.id === 'seed-500-miles');expect(seed.scoreParts).toBe(SEED_500_MILES_SCORE_PARTS);expect(SEED_500_MILES_SCORE_PARTS.map((p) => p.role)).toEqual(['bass', 'mid-harmony-2', 'mid-harmony-1', 'high-harmony-2', 'high-harmony-1',diff --git a/scripts/migrations/086-seed-round-harmony-parts.js b/scripts/migrations/086-seed-round-harmony-parts.jsindex 80e974b84a..d19a5586ac 100644--- a/scripts/migrations/086-seed-round-harmony-parts.js+++ b/scripts/migrations/086-seed-round-harmony-parts.js@@ -4,7 +4,7 @@* rounds before they carried a voice stack.** Background:- * `server/services/songs.js#SEED_SONGS` now ships each round (Hey Ho Nobody+ * `server/services/rounds.js#SEED_ROUNDS` now ships each round (Hey Ho Nobody* Home, Ah Poor Bird, Rose Rose Rose Red, Zum Gali Gali) with its canonic voice* stack (SEED_ROUND_SCORE_PARTS) — the melody entering a fixed number of bars* late per voice. This is what gives every round (not just 500 Miles) the@@ -23,7 +23,7 @@import { readFile, writeFile, stat } from 'fs/promises';import { join } from 'path';-import { SEED_ROUND_SCORE_PARTS } from '../../server/services/songs.js';+import { SEED_ROUND_SCORE_PARTS } from '../../server/services/rounds.js';const fileExists = (path) => stat(path).then(() => true, (err) => {if (err.code === 'ENOENT') return false;diff --git a/scripts/migrations/086-seed-round-harmony-parts.test.js b/scripts/migrations/086-seed-round-harmony-parts.test.jsindex f04a938a4f..5fde5eebdd 100644--- a/scripts/migrations/086-seed-round-harmony-parts.test.js+++ b/scripts/migrations/086-seed-round-harmony-parts.test.js@@ -4,7 +4,7 @@ import { tmpdir } from 'os';import { join } from 'path';import migration from './086-seed-round-harmony-parts.js';-import { SEED_ROUND_SCORE_PARTS, SEED_SONGS } from '../../server/services/songs.js';+import { SEED_ROUND_SCORE_PARTS, SEED_ROUNDS } from '../../server/services/rounds.js';import { parseScore } from '../../client/src/lib/scoreNotation.js';const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');@@ -28,7 +28,7 @@ describe('migration 086 — seed round harmony (canon voice) parts', () => {it('every round seed carries its shipped canon voice parts (single source)', () => {for (const id of ROUND_IDS) {- const seed = SEED_SONGS.find((s) => s.id === id);+ const seed = SEED_ROUNDS.find((s) => s.id === id);expect(seed.scoreParts).toBe(SEED_ROUND_SCORE_PARTS[id]);expect(seed.scoreParts.length).toBeGreaterThan(0);}@@ -36,7 +36,7 @@ describe('migration 086 — seed round harmony (canon voice) parts', () => {it('each canon voice is the melody delayed by whole-bar rests and parses cleanly', () => {for (const id of ROUND_IDS) {- const song = SEED_SONGS.find((s) => s.id === id);+ const song = SEED_ROUNDS.find((s) => s.id === id);const melodyBars = parseScore(song.score).measures.length;song.scoreParts.forEach((part, i) => {const parsed = parseScore(part.score);diff --git a/scripts/migrations/120-rename-songs-to-rounds-data.js b/scripts/migrations/120-rename-songs-to-rounds-data.jsnew file mode 100644index 0000000000..8e1c4d09cb--- /dev/null+++ b/scripts/migrations/120-rename-songs-to-rounds-data.js@@ -0,0 +1,101 @@+/**+ * Rename the "Songs" workbench data on disk to "Rounds".+ *+ * Background:+ * The a cappella workbench was renamed from "Songs" to "Rounds" (its real+ * subject is musical rounds — Hey Ho Nobody Home, the quodlibet trio, the+ * 500 Miles worked example). The full-stack rename moved the service from+ * `server/services/songs.js` → `rounds.js` (STATE_PATH `data/songs.json` →+ * `data/rounds.json`, top-level key `songs: []` → `rounds: []`) and the per-+ * record `partnerSongIds` field → `partnerRoundIds`, plus the route+ * `/api/songs` → `/api/rounds`. Existing installs already have their data in+ * `data/songs.json`; without this migration the renamed service reads a+ * missing `data/rounds.json` and re-seeds, stranding the user's saved rounds,+ * recordings and training progress.+ *+ * Steps (each idempotent — a re-run after partial completion is safe):+ * 1. Rename `data/songs.json` → `data/rounds.json`.+ * 2. In that file, rename the top-level `songs` key → `rounds`.+ * 3. Rename every `partnerSongIds` field → `partnerRoundIds` (text-rewrite so+ * the user's formatting + the rest of each record is untouched).+ *+ * Edge cases:+ * - If both `songs.json` and `rounds.json` exist (interrupted migration, hand-+ * rename), the rename step skips with a warning; steps 2–3 still run against+ * `rounds.json`.+ * - Songs are NOT federated (absent from schemaVersions.js / peerSync.js) and+ * no other data file references a song id, so there are no cross-file foreign+ * keys to rewrite — unlike the World→Universe rename (migration 031).+ */++import { readFile, writeFile, rename, stat } from 'fs/promises';+import { join } from 'path';++const fileExists = (path) => stat(path).then(() => true, (err) => {+ if (err.code === 'ENOENT') return false;+ throw err;+});++const readText = async (path) => readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+});++const readJson = async (path) => {+ const raw = await readText(path);+ if (raw == null) return null;+ return JSON.parse(raw);+};++const writeJson = (path, value) =>+ writeFile(path, JSON.stringify(value, null, 2) + '\n');++async function renameSongsFile(dataDir) {+ const oldPath = join(dataDir, 'songs.json');+ const newPath = join(dataDir, 'rounds.json');+ const [hasOld, hasNew] = await Promise.all([fileExists(oldPath), fileExists(newPath)]);+ if (hasOld && hasNew) {+ console.warn(`⚠️ migration 120: both songs.json and rounds.json exist — leaving files alone (resolve manually)`);+ return false;+ }+ if (!hasOld) return false;+ await rename(oldPath, newPath);+ console.log(`🎵→🔁 migration 120: renamed songs.json → rounds.json`);+ return true;+}++async function renameTopLevelKey(dataDir) {+ const path = join(dataDir, 'rounds.json');+ const doc = await readJson(path);+ if (!doc || typeof doc !== 'object') return false;+ if (Array.isArray(doc.rounds)) return false; // already migrated+ if (!Array.isArray(doc.songs)) return false; // nothing to do+ const { songs, ...rest } = doc;+ await writeJson(path, { rounds: songs, ...rest });+ console.log(`🔁 migration 120: renamed top-level "songs" → "rounds" (${songs.length} entries)`);+ return true;+}++// Text-rewrite a single JSON key without re-stringifying the whole file —+// preserves the user's formatting and keeps the diff minimal. Only matches the+// `"<fromKey>":` token so substrings inside string values can't collide.+async function renameJsonField(path, fromKey, toKey, label) {+ const raw = await readText(path);+ if (raw == null) return 0;+ const pattern = new RegExp(`"${fromKey}"\\s*:`, 'g');+ const count = (raw.match(pattern) || []).length;+ if (count === 0) return 0;+ const next = raw.replace(pattern, `"${toKey}":`);+ await writeFile(path, next);+ console.log(`🔄 migration 120: renamed ${count} "${fromKey}" → "${toKey}" key(s) in ${label}`);+ return count;+}++export default {+ async up({ rootDir }) {+ const dataDir = join(rootDir, 'data');+ await renameSongsFile(dataDir);+ await renameTopLevelKey(dataDir);+ await renameJsonField(join(dataDir, 'rounds.json'), 'partnerSongIds', 'partnerRoundIds', 'rounds.json');+ },+};diff --git a/scripts/migrations/120-rename-songs-to-rounds-data.test.js b/scripts/migrations/120-rename-songs-to-rounds-data.test.jsnew file mode 100644index 0000000000..8d3349dc2b--- /dev/null+++ b/scripts/migrations/120-rename-songs-to-rounds-data.test.js@@ -0,0 +1,80 @@+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 './120-rename-songs-to-rounds-data.js';++const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++describe('migration 120 — rename songs.json → rounds.json', () => {+ let rootDir;+ let songsPath;+ let roundsPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-120-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ songsPath = join(rootDir, 'data', 'songs.json');+ roundsPath = join(rootDir, 'data', 'rounds.json');+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('renames the file, the top-level key, and the partnerSongIds field', async () => {+ writeJson(songsPath, {+ songs: [+ { id: 'seed-hey-ho', title: 'Hey Ho', partnerSongIds: ['seed-ah-poor-bird'] },+ { id: 'round-custom', title: 'Mine', partnerSongIds: [] },+ ],+ });+ await migration.up({ rootDir });++ expect(existsSync(songsPath)).toBe(false);+ expect(existsSync(roundsPath)).toBe(true);+ const doc = readJson(roundsPath);+ expect(Array.isArray(doc.rounds)).toBe(true);+ expect(doc).not.toHaveProperty('songs');+ expect(doc.rounds[0].partnerRoundIds).toEqual(['seed-ah-poor-bird']);+ expect(doc.rounds[0]).not.toHaveProperty('partnerSongIds');+ expect(doc.rounds[1].partnerRoundIds).toEqual([]);+ });++ it('no-ops when neither songs.json nor rounds.json exists (fresh install)', async () => {+ await migration.up({ rootDir });+ expect(existsSync(songsPath)).toBe(false);+ expect(existsSync(roundsPath)).toBe(false);+ });++ it('is idempotent — a second run after migrating changes nothing', async () => {+ writeJson(songsPath, { songs: [{ id: 'r1', partnerSongIds: ['r2'] }] });+ await migration.up({ rootDir });+ const afterFirst = readFileSync(roundsPath, 'utf-8');+ await migration.up({ rootDir });+ expect(readFileSync(roundsPath, 'utf-8')).toBe(afterFirst);+ expect(existsSync(songsPath)).toBe(false);+ });++ it('leaves files alone when BOTH songs.json and rounds.json exist (resolve manually), but still normalizes rounds.json', async () => {+ writeJson(songsPath, { songs: [{ id: 'legacy' }] });+ writeJson(roundsPath, { songs: [{ id: 'r1', partnerSongIds: ['r2'] }] });+ await migration.up({ rootDir });++ // The rename is skipped (both present), so songs.json is untouched…+ expect(existsSync(songsPath)).toBe(true);+ // …but rounds.json still gets the top-level key + field normalization.+ const doc = readJson(roundsPath);+ expect(Array.isArray(doc.rounds)).toBe(true);+ expect(doc.rounds[0].partnerRoundIds).toEqual(['r2']);+ });++ it('does not touch an already-migrated rounds.json (rounds key present)', async () => {+ writeJson(roundsPath, { rounds: [{ id: 'r1', partnerRoundIds: ['r2'] }] });+ const before = readFileSync(roundsPath, 'utf-8');+ await migration.up({ rootDir });+ expect(readFileSync(roundsPath, 'utf-8')).toBe(before);+ });+});diff --git a/server/index.js b/server/index.jsindex 6c6236db44..70e9f6ec5c 100644--- a/server/index.js+++ b/server/index.js@@ -131,7 +131,7 @@ import { initLoraTraining } from './services/loraTraining/index.js';import sdapiRoutes from './routes/sdapi.js';import openclawRoutes from './routes/openclaw.js';import sharingRoutes from './routes/sharing.js';-import songsRoutes from './routes/songs.js';+import roundsRoutes from './routes/rounds.js';import peerSyncRoutes from './routes/peerSync.js';import { initSharing } from './services/sharing/index.js';import askRoutes from './routes/ask.js';@@ -544,7 +544,7 @@ app.use('/api/lora-training', loraTrainingRoutes);app.use('/sdapi/v1', sdapiRoutes);app.use('/api/openclaw', openclawRoutes);app.use('/api/sharing', sharingRoutes);-app.use('/api/songs', songsRoutes);+app.use('/api/rounds', roundsRoutes);app.use('/api/peer-sync', peerSyncRoutes);app.use('/api/ask', askRoutes);diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 8d3a0975ed..a5cc6dc910 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -31,8 +31,8 @@ export const NAV_COMMANDS = [{ id: 'nav.create.sharing', path: '/sharing', label: 'Sharing', section: 'Create', aliases: ['sharing', 'share', 'buckets', 'share-buckets'], keywords: ['google drive', 'dropbox', 'icloud', 'syncthing', 'export', 'import', 'collaborate', 'federation', 'peer', 'cross-network'] },{ id: 'nav.create.sharing-duplicates', path: '/sharing/duplicates', label: 'Duplicates', section: 'Create', aliases: ['duplicates', 'duplicate-universes', 'duplicate-series', 'dedupe', 'merge-duplicates'], keywords: ['duplicate', 'merge', 'rename', 'same name', 'two copies', 'reconcile', 'collision'] },{ id: 'nav.create.story-builder', path: '/story-builder', label: 'Story Builder', section: 'Create', aliases: ['story-builder', 'storybuilder', 'guided', 'new-story', 'story-wizard'], keywords: ['idea', 'universe', 'arc', 'reader map', 'guided', 'wizard', 'linear', 'lock', 'front door', 'episode', 'series'] },- { id: 'nav.create.songs', path: '/songs', label: 'Songs', section: 'Create', aliases: ['songs', 'song', 'music', 'a-cappella', 'acappella', 'sing'], keywords: ['song', 'lyrics', 'melody', 'harmony', 'dirge', 'ballad', 'a cappella', 'vocal', 'choir', 'singing', 'arrangement', '500 miles'] },- { id: 'nav.create.songs-guide', path: '/songs/guide', label: 'Songs Guide', section: 'Create', aliases: ['songs-guide', 'song-guide', 'singing-guide', 'song-learning'], keywords: ['rhythm shapes', 'dirge', 'voice layers', 'harmony', 'notation', 'lead sheet', 'solfege', 'learn song', 'a cappella', 'singing help'] },+ { id: 'nav.create.rounds', path: '/rounds', label: 'Rounds', section: 'Create', aliases: ['rounds', 'round', 'songs', 'song', 'a-cappella', 'acappella', 'sing'], keywords: ['round', 'song', 'lyrics', 'melody', 'harmony', 'dirge', 'ballad', 'a cappella', 'vocal', 'choir', 'singing', 'arrangement', 'quodlibet', '500 miles'] },+ { id: 'nav.create.rounds-guide', path: '/rounds/guide', label: 'Rounds Guide', section: 'Create', aliases: ['rounds-guide', 'round-guide', 'songs-guide', 'song-guide', 'singing-guide', 'round-learning'], keywords: ['rhythm shapes', 'dirge', 'voice layers', 'harmony', 'notation', 'lead sheet', 'solfege', 'learn round', 'learn song', 'a cappella', 'singing help'] },{ id: 'nav.create.sharing-conflicts', path: '/sharing/conflicts', label: 'Conflicts', section: 'Create', aliases: ['conflicts', 'sync-conflicts', 'edit-conflicts', 'conflict-journal'], keywords: ['conflict', 'overwrite', 'lost edit', 'restore', 'merge fields', 'last write wins', 'diverged', 'recover'] },{ id: 'nav.media.loras', path: '/media/loras', label: 'LoRAs', section: 'Create', aliases: ['loras', 'lora', 'lora-manager', 'civitai'], keywords: ['lora', 'civitai', 'fine-tune', 'style adapter', 'realstagram', 'photoreal', 'flux lora'] },{ id: 'nav.media.training', path: '/media/training', label: 'LoRA Training', section: 'Create', aliases: ['training', 'lora-training', 'train-lora', 'datasets', 'character-lora'], keywords: ['fine-tune', 'dataset', 'caption', 'dreambooth', 'character consistency', 'train', 'flux lora'] },diff --git a/server/lib/songCraftRef.js b/server/lib/songCraftRef.jsindex ca967cc3e2..20d313ced9 100644--- a/server/lib/songCraftRef.js+++ b/server/lib/songCraftRef.js@@ -7,7 +7,7 @@* and voice-layer ids/labels/roles — so it can inject them into the AI* generate/evaluate prompts and the model returns ids the editor pickers already* understand. Kept as a deliberate, small mirror (not a shared import: client- * and server are separate packages) — `server/services/songs.js` already+ * and server are separate packages) — `server/services/rounds.js` already* documents this mirror relationship for the sanitizer's id vocabulary.** Pure data, no imports. If you add/rename a shape or layer id here, mirror itdiff --git a/server/routes/songs.js b/server/routes/rounds.jssimilarity index 71%rename from server/routes/songs.jsrename to server/routes/rounds.jsindex ec1ed0ed21..96fba5f9e1 100644--- a/server/routes/songs.js+++ b/server/routes/rounds.js@@ -1,14 +1,14 @@/**- * Songs API+ * Rounds API*- * GET /api/songs → { songs }- * GET /api/songs/:id → { song }- * POST /api/songs → { song } (body: songInputSchema)- * PUT /api/songs/:id → { song } (body: songInputSchema.partial())- * DELETE /api/songs/:id → { id }+ * GET /api/rounds → { rounds }+ * GET /api/rounds/:id → { round }+ * POST /api/rounds → { round } (body: roundInputSchema)+ * PUT /api/rounds/:id → { round } (body: roundInputSchema.partial())+ * DELETE /api/rounds/:id → { id }*- * The a cappella song workbench: write/arrange songs and track which voice- * layers you're learning. Bounds come from services/songs.js so the Zod schema+ * The a cappella round workbench: write/arrange rounds and track which voice+ * layers you're learning. Bounds come from services/rounds.js so the Zod schema* here and the service-layer sanitizer agree by construction (the dashboard-* layouts pattern).*/@@ -17,8 +17,8 @@ import { Router } from 'express';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, deriveSongParts } from '../services/songsAI.js';+import * as svc from '../services/rounds.js';+import { generateRound, evaluateRound, deriveRoundParts } from '../services/roundsAI.js';const router = Router();@@ -63,7 +63,7 @@ const accuracySchema = z.object({});// A saved vocal take. `filename` is the /api/uploads file the audio is served-// from (the client uploads the WAV first, then PUTs the song with the returned+// from (the client uploads the WAV first, then PUTs the round with the returned// filename). Numbers are accepted for the mixer; the service clamps them.// `pitchTrack`/`accuracy` are optional per-take pitch analysis (#1027) — absent// on legacy/unscored takes, persisted so the tuner history isn't recomputed.@@ -118,10 +118,10 @@ const referenceSchema = z.object({// No `.default('')` on these fields: `.partial()` (used for PUT) materializes a// default for an *omitted* key, which would turn a single-field PUT into a-// wipe of every other field via updateSong's `'key' in patch` merge. Leaving+// wipe of every other field via updateRound's `'key' in patch` merge. Leaving// them plain-optional keeps omitted keys absent (preserve) vs present-empty// (clear); the service's `trimField` coerces a present `undefined`/'' anyway.-const songInputSchema = z.object({+const roundInputSchema = z.object({title: str(svc.TITLE_MAX_LENGTH).optional(),artist: str(svc.ARTIST_MAX_LENGTH).optional(),key: str(svc.KEY_MAX_LENGTH).optional(),@@ -138,15 +138,15 @@ const songInputSchema = z.object({notes: str(svc.FIELD_MAX_LENGTH).optional(),learned: z.boolean().optional(),// Training progress (#1028) — per-scope rolling accuracy history. Optional and- // absent-tolerant: a legacy/untrained song omits it; the service bounds + clamps.+ // absent-tolerant: a legacy/untrained round omits it; the service bounds + clamps.progress: progressSchema,sections: z.array(sectionSchema).max(svc.SECTIONS_MAX).optional(),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+ // Ids of other rounds 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(),+ partnerRoundIds: z.array(str(svc.ID_MAX_LENGTH)).max(svc.PARTNERS_MAX).optional(),});// AI generate/evaluate inputs. providerId/model are optional overrides; the@@ -158,7 +158,7 @@ const generateSchema = z.object({artist: str(svc.ARTIST_MAX_LENGTH).optional(),brief: str(svc.FIELD_MAX_LENGTH).optional(),mood: str(svc.FIELD_MAX_LENGTH).optional(),- // When true, the target song (route :id) is folded into the prompt so+ // When true, the target round (route :id) is folded into the prompt so// "generate" expands the existing draft instead of starting blank.expandExisting: z.boolean().optional(),providerId: optProvider,@@ -168,7 +168,7 @@ const evaluateSchema = z.object({providerId: optProvider,model: optProvider,});-// Derive harmony parts from the song's base score. `partIds` optionally restricts+// Derive harmony parts from the round'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({@@ -179,98 +179,98 @@ const derivePartsSchema = z.object({// Map a service error (carries a `code`) to the right HTTP status. Without// this, asyncHandler defaults everything to 500.-const mapSongError = (err) => {+const mapRoundError = (err) => {if (err?.code === svc.ERR_NOT_FOUND) return new ServerError(err.message, { status: 404, code: err.code });if (err?.code === svc.ERR_NOT_BUILTIN) return new ServerError(err.message, { status: 400, code: err.code });return err;};-const rethrowSongError = (err) => { throw mapSongError(err); };+const rethrowRoundError = (err) => { throw mapRoundError(err); };router.get('/', asyncHandler(async (req, res) => {- const songs = await svc.listSongs();- res.json({ songs });+ const rounds = await svc.listRounds();+ res.json({ rounds });}));router.get('/:id', asyncHandler(async (req, res) => {- const song = await svc.getSong(req.params.id);- if (!song) throw new ServerError('Song not found', { status: 404, code: svc.ERR_NOT_FOUND });- res.json({ song });+ const round = await svc.getRound(req.params.id);+ if (!round) throw new ServerError('Round not found', { status: 404, code: svc.ERR_NOT_FOUND });+ res.json({ round });}));router.post('/', asyncHandler(async (req, res) => {- const input = validateRequest(songInputSchema, req.body || {});- const song = await svc.createSong(input).catch(rethrowSongError);- res.json({ song });+ const input = validateRequest(roundInputSchema, req.body || {});+ const round = await svc.createRound(input).catch(rethrowRoundError);+ res.json({ round });}));router.put('/:id', asyncHandler(async (req, res) => {- const patch = validateRequest(songInputSchema.partial(), req.body || {});- const song = await svc.updateSong(req.params.id, patch).catch(rethrowSongError);- res.json({ song });+ const patch = validateRequest(roundInputSchema.partial(), req.body || {});+ const round = await svc.updateRound(req.params.id, patch).catch(rethrowRoundError);+ res.json({ round });}));router.delete('/:id', asyncHandler(async (req, res) => {- const result = await svc.deleteSong(req.params.id).catch(rethrowSongError);+ const result = await svc.deleteRound(req.params.id).catch(rethrowRoundError);res.json(result);}));-// POST /api/songs/:id/refresh-template → reset a built-in default song's shipped+// POST /api/rounds/:id/refresh-template → reset a built-in default round's shipped// content (metadata/lyrics/layers/notation) to the current bundled template,// preserving the user's own recordings + learned progress. 400 if not built-in.router.post('/:id/refresh-template', asyncHandler(async (req, res) => {- const song = await svc.refreshSongFromTemplate(req.params.id).catch(rethrowSongError);- res.json({ song });+ const round = await svc.refreshRoundFromTemplate(req.params.id).catch(rethrowRoundError);+ res.json({ round });}));// --- AI generate / evaluate --------------------------------------------------// POST /api/songs/generate → draft a brand-new arrangement from a brief. Does-// NOT persist — returns { song: <fields>, llm } the client merges/creates from.+// POST /api/rounds/generate → draft a brand-new arrangement from a brief. Does+// NOT persist — returns { round: <fields>, llm } the client merges/creates from.// (Routed before /:id/* so a literal `/generate` can't be read as an id.)router.post('/generate', asyncHandler(async (req, res) => {const body = validateRequest(generateSchema, req.body || {});- const result = await generateSong(body);+ const result = await generateRound(body);res.json(result);}));-// POST /api/songs/:id/generate → expand the stored song (when expandExisting)-// or draft fresh using its title/artist as the brief. Returns { song, llm };+// POST /api/rounds/:id/generate → expand the stored round (when expandExisting)+// or draft fresh using its title/artist as the brief. Returns { round, llm };// the client merges into the editor draft (does not auto-save).router.post('/:id/generate', asyncHandler(async (req, res) => {const body = validateRequest(generateSchema, req.body || {});- const existing = await svc.getSong(req.params.id);- if (!existing) throw new ServerError('Song not found', { status: 404, code: svc.ERR_NOT_FOUND });- const result = await generateSong({+ const existing = await svc.getRound(req.params.id);+ if (!existing) throw new ServerError('Round not found', { status: 404, code: svc.ERR_NOT_FOUND });+ const result = await generateRound({title: body.title ?? existing.title,artist: body.artist ?? existing.artist,brief: body.brief,mood: body.mood,- existingSong: body.expandExisting ? existing : undefined,+ existingRound: body.expandExisting ? existing : undefined,providerId: body.providerId,model: body.model,});res.json(result);}));-// POST /api/songs/:id/evaluate → critique the stored arrangement. Read-only:-// returns { evaluation, llm } without mutating the song.+// POST /api/rounds/:id/evaluate → critique the stored arrangement. Read-only:+// returns { evaluation, llm } without mutating the round.router.post('/:id/evaluate', asyncHandler(async (req, res) => {const body = validateRequest(evaluateSchema, 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 evaluateSong({ song, providerId: body.providerId, model: body.model });+ const round = await svc.getRound(req.params.id);+ if (!round) throw new ServerError('Round not found', { status: 404, code: svc.ERR_NOT_FOUND });+ const result = await evaluateRound({ song: round, providerId: body.providerId, model: body.model });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+// POST /api/rounds/:id/derive-parts → derive harmony parts (bass, mid/high+// harmonies) from the round'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.+// the generate/expand flow. 400 if the round 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,+ const round = await svc.getRound(req.params.id);+ if (!round) throw new ServerError('Round not found', { status: 404, code: svc.ERR_NOT_FOUND });+ const result = await deriveRoundParts({+ song: round, partIds: body.partIds, providerId: body.providerId, model: body.model,});res.json(result);}));diff --git a/server/routes/songs.test.js b/server/routes/rounds.test.jssimilarity index 51%rename from server/routes/songs.test.jsrename to server/routes/rounds.test.jsindex c8d558bb27..8effffe46d 100644--- a/server/routes/songs.test.js+++ b/server/routes/rounds.test.js@@ -4,56 +4,56 @@ import { request } from '../lib/testHelper.js';import { errorMiddleware } from '../lib/errorHandler.js';// Mock the service so the test isolates the ROUTE's validation/merge contract:-// we assert exactly what the route forwards to updateSong, independent of the-// JSON-file persistence (covered by services/songs.test.js).+// we assert exactly what the route forwards to updateRound, independent of the+// JSON-file persistence (covered by services/rounds.test.js).const mocks = vi.hoisted(() => ({- listSongs: vi.fn(),- getSong: vi.fn(),- createSong: vi.fn(),- updateSong: vi.fn(),- deleteSong: vi.fn(),- refreshSongFromTemplate: vi.fn(),+ listRounds: vi.fn(),+ getRound: vi.fn(),+ createRound: vi.fn(),+ updateRound: vi.fn(),+ deleteRound: vi.fn(),+ refreshRoundFromTemplate: vi.fn(),}));-vi.mock('../services/songs.js', async () => {- const actual = await vi.importActual('../services/songs.js');+vi.mock('../services/rounds.js', async () => {+ const actual = await vi.importActual('../services/rounds.js');return { ...actual, ...mocks };});// Mock the AI layer so route tests don't spawn a provider — assert the route's// validation + service wiring, not the LLM call.const aiMocks = vi.hoisted(() => ({- generateSong: vi.fn(),- evaluateSong: vi.fn(),- deriveSongParts: vi.fn(),+ generateRound: vi.fn(),+ evaluateRound: vi.fn(),+ deriveRoundParts: vi.fn(),}));-vi.mock('../services/songsAI.js', () => aiMocks);+vi.mock('../services/roundsAI.js', () => aiMocks);-import songsRoutes from './songs.js';+import roundsRoutes from './rounds.js';const makeApp = () => {const app = express();app.use(express.json());- app.use('/api/songs', songsRoutes);+ app.use('/api/rounds', roundsRoutes);app.use(errorMiddleware);return app;};-describe('songs route', () => {+describe('rounds route', () => {beforeEach(() => {for (const fn of Object.values(mocks)) fn.mockReset();for (const fn of Object.values(aiMocks)) fn.mockReset();});it('GET / returns the song list', async () => {- mocks.listSongs.mockResolvedValue([{ id: 'song-1', title: 'A' }]);- const res = await request(makeApp()).get('/api/songs');+ mocks.listRounds.mockResolvedValue([{ id: 'song-1', title: 'A' }]);+ const res = await request(makeApp()).get('/api/rounds');expect(res.status).toBe(200);- expect(res.body.songs).toEqual([{ id: 'song-1', title: 'A' }]);+ expect(res.body.rounds).toEqual([{ id: 'song-1', title: 'A' }]);});it('GET /:id 404s with a NOT_FOUND code when the song is missing', async () => {- mocks.getSong.mockResolvedValue(null);- const res = await request(makeApp()).get('/api/songs/song-nope');+ mocks.getRound.mockResolvedValue(null);+ const res = await request(makeApp()).get('/api/rounds/song-nope');expect(res.status).toBe(404);expect(res.body.code).toBe('NOT_FOUND');});@@ -61,15 +61,15 @@ describe('songs route', () => {it('PUT /:id forwards ONLY the keys the client sent — omitted fields are not clobbered', async () => {// Regression guard: a `.default('')` on the schema fields would make// .partial() materialize defaults for omitted keys, so a title-only PUT- // would wipe artist/key/notation/notes via updateSong's `key in patch`+ // would wipe artist/key/notation/notes via updateRound's `key in patch`// merge. The route must forward a patch containing ONLY `title`.- mocks.updateSong.mockResolvedValue({ id: 'song-1', title: 'Renamed' });+ mocks.updateRound.mockResolvedValue({ id: 'song-1', title: 'Renamed' });const res = await request(makeApp())- .put('/api/songs/song-1')+ .put('/api/rounds/song-1').send({ title: 'Renamed' });expect(res.status).toBe(200);- expect(mocks.updateSong).toHaveBeenCalledTimes(1);- const [, patch] = mocks.updateSong.mock.calls[0];+ expect(mocks.updateRound).toHaveBeenCalledTimes(1);+ const [, patch] = mocks.updateRound.mock.calls[0];expect(patch).toEqual({ title: 'Renamed' });expect('artist' in patch).toBe(false);expect('key' in patch).toBe(false);@@ -77,61 +77,61 @@ describe('songs route', () => {});it('PUT /:id preserves an explicit empty-string clear (present, not absent)', async () => {- mocks.updateSong.mockResolvedValue({ id: 'song-1', key: '' });- await request(makeApp()).put('/api/songs/song-1').send({ key: '' });- const [, patch] = mocks.updateSong.mock.calls[0];+ mocks.updateRound.mockResolvedValue({ id: 'song-1', key: '' });+ await request(makeApp()).put('/api/rounds/song-1').send({ key: '' });+ const [, patch] = mocks.updateRound.mock.calls[0];expect('key' in patch).toBe(true);expect(patch.key).toBe('');});it('PUT /:id maps a service NOT_FOUND to a 404', async () => {- mocks.updateSong.mockRejectedValue(Object.assign(new Error('nope'), { code: 'NOT_FOUND' }));- const res = await request(makeApp()).put('/api/songs/song-x').send({ title: 'x' });+ mocks.updateRound.mockRejectedValue(Object.assign(new Error('nope'), { code: 'NOT_FOUND' }));+ const res = await request(makeApp()).put('/api/rounds/song-x').send({ title: 'x' });expect(res.status).toBe(404);expect(res.body.code).toBe('NOT_FOUND');});it('POST / rejects an over-long title with a 400', async () => {const res = await request(makeApp())- .post('/api/songs')+ .post('/api/rounds').send({ title: 'x'.repeat(5000) });expect(res.status).toBe(400);- expect(mocks.createSong).not.toHaveBeenCalled();+ expect(mocks.createRound).not.toHaveBeenCalled();});it('POST / rejects a tempo outside the supported band', async () => {- const res = await request(makeApp()).post('/api/songs').send({ title: 'A', tempo: 9000 });+ const res = await request(makeApp()).post('/api/rounds').send({ title: 'A', tempo: 9000 });expect(res.status).toBe(400);});it('DELETE /:id returns the deleted id', async () => {- mocks.deleteSong.mockResolvedValue({ id: 'song-1' });- const res = await request(makeApp()).delete('/api/songs/song-1');+ mocks.deleteRound.mockResolvedValue({ id: 'song-1' });+ const res = await request(makeApp()).delete('/api/rounds/song-1');expect(res.status).toBe(200);expect(res.body.id).toBe('song-1');});it('PUT /:id accepts a recordings array', async () => {- mocks.updateSong.mockResolvedValue({ id: 'song-1' });- const res = await request(makeApp()).put('/api/songs/song-1').send({+ mocks.updateRound.mockResolvedValue({ id: 'song-1' });+ const res = await request(makeApp()).put('/api/rounds/song-1').send({recordings: [{ layerId: 'lead', filename: 'abc-vocal.wav', durationMs: 1200, peak: 0.4 }],});expect(res.status).toBe(200);- const [, patch] = mocks.updateSong.mock.calls[0];+ const [, patch] = mocks.updateRound.mock.calls[0];expect(patch.recordings[0].filename).toBe('abc-vocal.wav');});it('PUT /:id rejects a recording with a peak outside 0–1', async () => {- const res = await request(makeApp()).put('/api/songs/song-1').send({+ const res = await request(makeApp()).put('/api/rounds/song-1').send({recordings: [{ filename: 'x.wav', peak: 5 }],});expect(res.status).toBe(400);- expect(mocks.updateSong).not.toHaveBeenCalled();+ expect(mocks.updateRound).not.toHaveBeenCalled();});it('PUT /:id accepts a recording with pitchTrack + accuracy analysis (#1027)', async () => {- mocks.updateSong.mockResolvedValue({ id: 'song-1' });- const res = await request(makeApp()).put('/api/songs/song-1').send({+ mocks.updateRound.mockResolvedValue({ id: 'song-1' });+ const res = await request(makeApp()).put('/api/rounds/song-1').send({recordings: [{filename: 'take.wav',pitchTrack: [{ tMs: 0, hz: 220, cents: -3, clarity: 0.9 }, { tMs: 50, hz: null }],@@ -139,181 +139,181 @@ describe('songs route', () => {}],});expect(res.status).toBe(200);- const [, patch] = mocks.updateSong.mock.calls[0];+ const [, patch] = mocks.updateRound.mock.calls[0];expect(patch.recordings[0].pitchTrack).toHaveLength(2);expect(patch.recordings[0].accuracy.percentInTune).toBe(80);});it('PUT /:id accepts a legacy recording with no pitch analysis (absent-tolerant)', async () => {- mocks.updateSong.mockResolvedValue({ id: 'song-1' });- const res = await request(makeApp()).put('/api/songs/song-1').send({+ mocks.updateRound.mockResolvedValue({ id: 'song-1' });+ const res = await request(makeApp()).put('/api/rounds/song-1').send({recordings: [{ filename: 'legacy.wav', durationMs: 500 }],});expect(res.status).toBe(200);- const [, patch] = mocks.updateSong.mock.calls[0];+ const [, patch] = mocks.updateRound.mock.calls[0];expect(patch.recordings[0]).not.toHaveProperty('pitchTrack');});it('PUT /:id rejects a pitchTrack exceeding the bound', async () => {const tooMany = Array.from({ length: 4001 }, (_, i) => ({ tMs: i }));- const res = await request(makeApp()).put('/api/songs/song-1').send({+ const res = await request(makeApp()).put('/api/rounds/song-1').send({recordings: [{ filename: 'x.wav', pitchTrack: tooMany }],});expect(res.status).toBe(400);- expect(mocks.updateSong).not.toHaveBeenCalled();+ expect(mocks.updateRound).not.toHaveBeenCalled();});it('PUT /:id accepts a references array', async () => {- mocks.updateSong.mockResolvedValue({ id: 'song-1' });- const res = await request(makeApp()).put('/api/songs/song-1').send({+ mocks.updateRound.mockResolvedValue({ id: 'song-1' });+ const res = await request(makeApp()).put('/api/rounds/song-1').send({references: [{ url: 'https://www.tiktok.com/@u/video/123', label: 'TikTok' }],});expect(res.status).toBe(200);- const [, patch] = mocks.updateSong.mock.calls[0];+ const [, patch] = mocks.updateRound.mock.calls[0];expect(patch.references[0].url).toBe('https://www.tiktok.com/@u/video/123');});it('PUT /:id rejects a reference without a url', async () => {- const res = await request(makeApp()).put('/api/songs/song-1').send({+ const res = await request(makeApp()).put('/api/rounds/song-1').send({references: [{ label: 'no url' }],});expect(res.status).toBe(400);- expect(mocks.updateSong).not.toHaveBeenCalled();+ expect(mocks.updateRound).not.toHaveBeenCalled();});it('PUT /:id accepts an empty-url reference (a blank row is dropped server-side, not rejected)', async () => {// The editor seeds new reference rows as { url: '' }; saving must not 400 —// the service drops the blank row. Guards against a future `.min(1)` that// would reject in-progress rows on save.- mocks.updateSong.mockResolvedValue({ id: 'song-1' });- const res = await request(makeApp()).put('/api/songs/song-1').send({+ mocks.updateRound.mockResolvedValue({ id: 'song-1' });+ const res = await request(makeApp()).put('/api/rounds/song-1').send({references: [{ url: '' }],});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'],+ it('PUT /:id accepts a partnerRoundIds array', async () => {+ mocks.updateRound.mockResolvedValue({ id: 'song-1' });+ const res = await request(makeApp()).put('/api/rounds/song-1').send({+ partnerRoundIds: ['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']);+ const [, patch] = mocks.updateRound.mock.calls[0];+ expect(patch.partnerRoundIds).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 });+ const res = await request(makeApp()).put('/api/rounds/song-1').send({ partnerRoundIds: tooMany });expect(res.status).toBe(400);- expect(mocks.updateSong).not.toHaveBeenCalled();+ expect(mocks.updateRound).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');+ mocks.refreshRoundFromTemplate.mockResolvedValue({ id: 'seed-500-miles', title: '500 Miles', builtIn: true });+ const res = await request(makeApp()).post('/api/rounds/seed-500-miles/refresh-template');expect(res.status).toBe(200);- expect(res.body.song.builtIn).toBe(true);- expect(mocks.refreshSongFromTemplate).toHaveBeenCalledWith('seed-500-miles');+ expect(res.body.round.builtIn).toBe(true);+ expect(mocks.refreshRoundFromTemplate).toHaveBeenCalledWith('seed-500-miles');});it('POST /:id/refresh-template maps NOT_BUILTIN to a 400', async () => {- mocks.refreshSongFromTemplate.mockRejectedValue(Object.assign(new Error('nope'), { code: 'NOT_BUILTIN' }));- const res = await request(makeApp()).post('/api/songs/song-custom/refresh-template');+ mocks.refreshRoundFromTemplate.mockRejectedValue(Object.assign(new Error('nope'), { code: 'NOT_BUILTIN' }));+ const res = await request(makeApp()).post('/api/rounds/song-custom/refresh-template');expect(res.status).toBe(400);expect(res.body.code).toBe('NOT_BUILTIN');});it('POST /generate returns the generated fields (no id needed)', async () => {- aiMocks.generateSong.mockResolvedValue({ song: { title: 'New', sections: [] }, llm: { provider: 'p' } });- const res = await request(makeApp()).post('/api/songs/generate').send({ brief: 'a lament' });+ aiMocks.generateRound.mockResolvedValue({ song: { title: 'New', sections: [] }, llm: { provider: 'p' } });+ const res = await request(makeApp()).post('/api/rounds/generate').send({ brief: 'a lament' });expect(res.status).toBe(200);expect(res.body.song.title).toBe('New');- expect(aiMocks.generateSong).toHaveBeenCalledTimes(1);+ expect(aiMocks.generateRound).toHaveBeenCalledTimes(1);});it('POST /generate coerces an empty providerId to undefined (use default)', async () => {- aiMocks.generateSong.mockResolvedValue({ song: { title: 'X' }, llm: {} });- await request(makeApp()).post('/api/songs/generate').send({ providerId: '' });- const [arg] = aiMocks.generateSong.mock.calls[0];+ aiMocks.generateRound.mockResolvedValue({ song: { title: 'X' }, llm: {} });+ await request(makeApp()).post('/api/rounds/generate').send({ providerId: '' });+ const [arg] = aiMocks.generateRound.mock.calls[0];expect(arg.providerId).toBeUndefined();});it('POST /:id/generate 404s when the song is missing', async () => {- mocks.getSong.mockResolvedValue(null);- const res = await request(makeApp()).post('/api/songs/song-nope/generate').send({});+ mocks.getRound.mockResolvedValue(null);+ const res = await request(makeApp()).post('/api/rounds/song-nope/generate').send({});expect(res.status).toBe(404);- expect(aiMocks.generateSong).not.toHaveBeenCalled();+ expect(aiMocks.generateRound).not.toHaveBeenCalled();});it('POST /:id/generate passes the stored song when expandExisting is set', async () => {- mocks.getSong.mockResolvedValue({ id: 'song-1', title: 'Stored', artist: 'PPM' });- aiMocks.generateSong.mockResolvedValue({ song: { title: 'Bigger' }, llm: {} });- const res = await request(makeApp()).post('/api/songs/song-1/generate').send({ expandExisting: true });+ mocks.getRound.mockResolvedValue({ id: 'song-1', title: 'Stored', artist: 'PPM' });+ aiMocks.generateRound.mockResolvedValue({ song: { title: 'Bigger' }, llm: {} });+ const res = await request(makeApp()).post('/api/rounds/song-1/generate').send({ expandExisting: true });expect(res.status).toBe(200);- const [arg] = aiMocks.generateSong.mock.calls[0];- expect(arg.existingSong).toEqual({ id: 'song-1', title: 'Stored', artist: 'PPM' });+ const [arg] = aiMocks.generateRound.mock.calls[0];+ expect(arg.existingRound).toEqual({ id: 'song-1', title: 'Stored', artist: 'PPM' });expect(arg.title).toBe('Stored'); // falls back to the stored title});it('POST /:id/evaluate returns the verdict', async () => {- mocks.getSong.mockResolvedValue({ id: 'song-1', title: 'A' });- aiMocks.evaluateSong.mockResolvedValue({ evaluation: { score: 72, strengths: [] }, llm: {} });- const res = await request(makeApp()).post('/api/songs/song-1/evaluate').send({});+ mocks.getRound.mockResolvedValue({ id: 'song-1', title: 'A' });+ aiMocks.evaluateRound.mockResolvedValue({ evaluation: { score: 72, strengths: [] }, llm: {} });+ const res = await request(makeApp()).post('/api/rounds/song-1/evaluate').send({});expect(res.status).toBe(200);expect(res.body.evaluation.score).toBe(72);});it('POST /:id/evaluate 404s when the song is missing', async () => {- mocks.getSong.mockResolvedValue(null);- const res = await request(makeApp()).post('/api/songs/song-x/evaluate').send({});+ mocks.getRound.mockResolvedValue(null);+ const res = await request(makeApp()).post('/api/rounds/song-x/evaluate').send({});expect(res.status).toBe(404);- expect(aiMocks.evaluateSong).not.toHaveBeenCalled();+ expect(aiMocks.evaluateRound).not.toHaveBeenCalled();});it('PUT /:id accepts a scoreParts array', async () => {- mocks.updateSong.mockResolvedValue({ id: 'song-1' });+ mocks.updateRound.mockResolvedValue({ id: 'song-1' });const res = await request(makeApp())- .put('/api/songs/song-1')+ .put('/api/rounds/song-1').send({ scoreParts: [{ label: 'Bass', role: 'bass', score: '| G2w(x) |' }] });expect(res.status).toBe(200);- const [, patch] = mocks.updateSong.mock.calls[0];+ const [, patch] = mocks.updateRound.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')+ .put('/api/rounds/song-1').send({ scoreParts: [{ label: 'Bass', role: 'bass' }] });expect(res.status).toBe(400);- expect(mocks.updateSong).not.toHaveBeenCalled();+ expect(mocks.updateRound).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({+ mocks.getRound.mockResolvedValue({ id: 'song-1', title: '500 Miles', score: '| [G] B4q |' });+ aiMocks.deriveRoundParts.mockResolvedValue({scoreParts: [{ role: 'bass', label: 'Bass', score: '| G2w |' }], llm: { provider: 'p' },});- const res = await request(makeApp()).post('/api/songs/song-1/derive-parts').send({});+ const res = await request(makeApp()).post('/api/rounds/song-1/derive-parts').send({});expect(res.status).toBe(200);expect(res.body.scoreParts).toHaveLength(1);- const [arg] = aiMocks.deriveSongParts.mock.calls[0];+ const [arg] = aiMocks.deriveRoundParts.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({});+ mocks.getRound.mockResolvedValue(null);+ const res = await request(makeApp()).post('/api/rounds/song-x/derive-parts').send({});expect(res.status).toBe(404);- expect(aiMocks.deriveSongParts).not.toHaveBeenCalled();+ expect(aiMocks.deriveRoundParts).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];+ mocks.getRound.mockResolvedValue({ id: 'song-1', score: '| [G] B4q |' });+ aiMocks.deriveRoundParts.mockResolvedValue({ scoreParts: [], llm: {} });+ await request(makeApp()).post('/api/rounds/song-1/derive-parts').send({ partIds: ['bass', 'high-harmony-1'] });+ const [arg] = aiMocks.deriveRoundParts.mock.calls[0];expect(arg.partIds).toEqual(['bass', 'high-harmony-1']);});});diff --git a/server/services/songs.js b/server/services/rounds.jssimilarity index 93%rename from server/services/songs.jsrename to server/services/rounds.jsindex 8cbbb45a42..58e3c3d652 100644--- a/server/services/songs.js+++ b/server/services/rounds.js@@ -1,16 +1,16 @@/**- * Songs workbench+ * Rounds workbench*- * Write, arrange, and learn a cappella songs (e.g. "500 Miles" by Peter, Paul- * and Mary). Each song stores its key/tempo/rhythm-shape, lyric sections, and+ * Write, arrange, and learn a cappella rounds (e.g. "500 Miles" by Peter, Paul+ * and Mary). Each round stores its key/tempo/rhythm-shape, lyric sections, and* the voice layers (lead / bass / harmony / drone / counter-melody) the user is- * stacking — plus per-layer learning notes. Persisted to data/songs.json.+ * stacking — plus per-layer learning notes. Persisted to data/rounds.json.** Pure-ish CRUD over a single JSON file: PortOS is single-user (see CLAUDE.md* "Security Model"), so a per-file write queue serializes the read-modify-write* cycle rather than guarding against competing humans.*- * Shape bounds are exported so routes/songs.js builds its Zod schema from the+ * Shape bounds are exported so routes/rounds.js builds its Zod schema from the* same source — sanitize-on-read and validate-at-the-boundary agree by* construction. The rhythm-shape and layer id vocabularies mirror* client/src/lib/songCraft.js; unknown ids are accepted (free-text fallback)@@ -22,7 +22,7 @@ import { randomUUID } from 'crypto';import { PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';-const STATE_PATH = join(PATHS.data, 'songs.json');+const STATE_PATH = join(PATHS.data, 'rounds.json');// Service errors carry a `code` field so routes map to HTTP status without// string-matching on err.message (which breaks on rename).@@ -32,7 +32,7 @@ export const ERR_NOT_FOUND = 'NOT_FOUND';export const ERR_NOT_BUILTIN = 'NOT_BUILTIN';const makeErr = (message, code) => Object.assign(new Error(message), { code });-// --- Shape bounds (shared with routes/songs.js#songInputSchema) -------------+// --- Shape bounds (shared with routes/rounds.js#roundInputSchema) -------------export const TITLE_MAX_LENGTH = 200;export const ARTIST_MAX_LENGTH = 200;export const KEY_MAX_LENGTH = 24;@@ -52,7 +52,7 @@ export const PARTNERS_MAX = 12; // partner-song ids (rounds sung togetherexport const URL_MAX_LENGTH = 512; // uploaded-file path/url// Per-take pitch analysis (#1027). The pitch track is a DOWNSAMPLED tuner trace// kept for replay/training so it isn't recomputed on every open; bound it so a-// long take can't bloat data/songs.json. `accuracy.perNote` mirrors the+// long take can't bloat data/rounds.json. `accuracy.perNote` mirrors the// color-match grade-per-note array (#1025), bounded the same way a score can't// be arbitrarily long.export const PITCH_TRACK_MAX = 4000; // downsampled tuner samples per take@@ -235,7 +235,7 @@ const sanitizeRecording = (r) => {};// Absent ⇒ omit (legacy/unscored take); present ⇒ sanitize + bound via the// shared sanitizeList. Keeping the keys off the object when there's no- // analysis avoids a wave of empty arrays in data/songs.json on every take.+ // analysis avoids a wave of empty arrays in data/rounds.json on every take.const pitchTrack = sanitizeList(r.pitchTrack, sanitizePitchSample, PITCH_TRACK_MAX);if (pitchTrack.length) rec.pitchTrack = pitchTrack;const accuracy = sanitizeAccuracy(r.accuracy);@@ -305,13 +305,13 @@ const sanitizePartnerIds = (arr, selfId) => {// 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) => {+export const sanitizeRound = (raw) => {if (!raw || typeof raw !== 'object') return null;const id = trimField(raw.id, ID_MAX_LENGTH);if (!id) return null;const song = {id,- title: trimField(raw.title, TITLE_MAX_LENGTH) || 'Untitled song',+ title: trimField(raw.title, TITLE_MAX_LENGTH) || 'Untitled round',artist: trimField(raw.artist, ARTIST_MAX_LENGTH),key: trimField(raw.key, KEY_MAX_LENGTH),tempo: sanitizeTempo(raw.tempo),@@ -333,11 +333,11 @@ export const sanitizeSong = (raw) => {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),+ partnerRoundIds: sanitizePartnerIds(raw.partnerRoundIds, 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.- builtIn: BUILTIN_SONG_IDS.has(id),+ // default can be restored to its shipped content via refreshRoundFromTemplate.+ builtIn: BUILTIN_ROUND_IDS.has(id),createdAt: typeof raw.createdAt === 'string' ? raw.createdAt : new Date().toISOString(),updatedAt: typeof raw.updatedAt === 'string' ? raw.updatedAt : new Date().toISOString(),};@@ -355,7 +355,7 @@ export const sanitizeSong = (raw) => {// PortOS DSL, voiced from the chord-tone map (NOT parallel intervals): a// hymn-like root–fifth bass, two sustained inner pads, a sustained upper pad// that carries the F#→G leading tone on D7, and a sparse top descant that enters-// late. Kept as a named export so SEED_SONGS and migration 076 share ONE source+// late. Kept as a named export so SEED_ROUNDS and migration 076 share ONE source// (no drift). Voicing roles/ranges mirror songCraft.js HARMONY_PARTS.export const SEED_500_MILES_SCORE_PARTS = [{@@ -435,7 +435,7 @@ export const SEED_500_MILES_SCORE_PARTS = [// itself, each voice entering a fixed number of bars late. Rather than hand-// transcribe the staggered voices (which could drift from the tune), we DERIVE// each canon voice from the one melody string below: every voice is provably the-// same melody, just delayed by whole-bar rests. SEED_SONGS uses these for both a+// same melody, just delayed by whole-bar rests. SEED_ROUNDS uses these for both a// round's base `score` and its `scoreParts`, and migration 086 backfills the// parts onto installs that seeded the rounds before they carried a voice stack.@@ -538,7 +538,7 @@ const ZUM_SCORE_PARTS = [];// The canonic voice stacks for the four rounds, keyed by song id. Shared by-// SEED_SONGS (below) and migration 086 so there's ONE source — no drift.+// SEED_ROUNDS (below) and migration 086 so there's ONE source — no drift.export const SEED_ROUND_SCORE_PARTS = {'seed-hey-ho-nobody-home': HEY_HO_SCORE_PARTS,'seed-ah-poor-bird': AH_POOR_BIRD_SCORE_PARTS,@@ -549,7 +549,7 @@ export const SEED_ROUND_SCORE_PARTS = {// Seeded on first read so a fresh install opens on a worked example — the song// the feature was designed around. Mirrors the dirge `slow-4-4` rhythm shape// and the foundation-first layer ladder from songCraft.js.-export const SEED_SONGS = [+export const SEED_ROUNDS = [{id: 'seed-500-miles',title: '500 Miles',@@ -657,7 +657,7 @@ export const SEED_SONGS = [// 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+ // others via partnerRoundIds, 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.{@@ -686,7 +686,7 @@ export const SEED_SONGS = [{ 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'],+ partnerRoundIds: ['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',},@@ -715,7 +715,7 @@ export const SEED_SONGS = [{ 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'],+ partnerRoundIds: ['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',},@@ -743,7 +743,7 @@ export const SEED_SONGS = [{ 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'],+ partnerRoundIds: ['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',},@@ -770,18 +770,18 @@ export const SEED_SONGS = [{ 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'],+ partnerRoundIds: ['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-// song with `builtIn` from this set, and refreshSongFromTemplate restores a-// built-in's shipped content from the matching SEED_SONGS entry. A user who+// song with `builtIn` from this set, and refreshRoundFromTemplate restores a+// built-in's shipped content from the matching SEED_ROUNDS entry. A user who// already has the song installed (older shipped lyrics) renews it on demand.-export const BUILTIN_SONG_IDS = new Set(SEED_SONGS.map((s) => s.id));-const seedTemplate = (id) => SEED_SONGS.find((s) => s.id === id) || null;+export const BUILTIN_ROUND_IDS = new Set(SEED_ROUNDS.map((s) => s.id));+const seedTemplate = (id) => SEED_ROUNDS.find((s) => s.id === id) || null;// Serialize the read-modify-write cycle so two mutations issued back-to-back// (e.g. a rename PUT followed by a layer edit) each merge against the freshest@@ -793,70 +793,70 @@ const enqueue = createFileWriteQueue();// malformed, returns the seed in-memory without persisting it. Mutations call// this inside their enqueue() so the read-modify-write cycle never re-enters// the queue (which would deadlock).-async function readSongs() {+async function readRounds() {const state = await readJSONFile(STATE_PATH, null, { allowArray: false });- if (!state || !Array.isArray(state.songs)) {- return SEED_SONGS.map(sanitizeSong).filter(Boolean);+ if (!state || !Array.isArray(state.rounds)) {+ return SEED_ROUNDS.map(sanitizeRound).filter(Boolean);}- return state.songs.map(sanitizeSong).filter(Boolean);+ return state.rounds.map(sanitizeRound).filter(Boolean);}// Public read. On first read (file absent) it persists the seed so the example// is stable and editable — but the seed write is routed through the SAME queue// as mutations and re-checks inside the queue, so a create that landed first// can't be clobbered by a late seed write (read-path lazy-init race).-export async function listSongs() {+export async function listRounds() {const state = await readJSONFile(STATE_PATH, null, { allowArray: false });- if (state && Array.isArray(state.songs)) {- return state.songs.map(sanitizeSong).filter(Boolean);+ if (state && Array.isArray(state.rounds)) {+ return state.rounds.map(sanitizeRound).filter(Boolean);}return enqueue(async () => {// Re-check inside the queue: a queued create may have already written the// file (with seed + new song). If so, don't overwrite it with bare seed.const fresh = await readJSONFile(STATE_PATH, null, { allowArray: false });- if (fresh && Array.isArray(fresh.songs)) {- return fresh.songs.map(sanitizeSong).filter(Boolean);+ if (fresh && Array.isArray(fresh.rounds)) {+ return fresh.rounds.map(sanitizeRound).filter(Boolean);}- const seeded = SEED_SONGS.map(sanitizeSong).filter(Boolean);- await atomicWrite(STATE_PATH, { songs: seeded });+ const seeded = SEED_ROUNDS.map(sanitizeRound).filter(Boolean);+ await atomicWrite(STATE_PATH, { rounds: seeded });return seeded;});}-export async function getSong(id) {- const songs = await listSongs();+export async function getRound(id) {+ const songs = await listRounds();return songs.find((s) => s.id === id) || null;}-export async function createSong(input) {+export async function createRound(input) {return enqueue(async () => {- const songs = await readSongs();+ const songs = await readRounds();const now = new Date().toISOString();- const song = sanitizeSong({ ...input, id: `song-${randomUUID()}`, createdAt: now, updatedAt: now });+ const song = sanitizeRound({ ...input, id: `round-${randomUUID()}`, createdAt: now, updatedAt: now });songs.unshift(song);- await atomicWrite(STATE_PATH, { songs });+ await atomicWrite(STATE_PATH, { rounds: songs });console.log(`🎵 Created song "${song.title}" (${song.id})`);return song;});}-export async function updateSong(id, patch) {+export async function updateRound(id, patch) {return enqueue(async () => {- const songs = await readSongs();+ const songs = await readRounds();const idx = songs.findIndex((s) => s.id === id);if (idx === -1) throw makeErr(`Song ${id} not found`, ERR_NOT_FOUND);// 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', 'scoreParts', 'notes', 'learned', 'progress', 'sections', 'layers', 'recordings', 'references', 'partnerSongIds']) {+ for (const key of ['title', 'artist', 'key', 'tempo', 'rhythmShapeId', 'notation', 'score', 'scoreParts', 'notes', 'learned', 'progress', 'sections', 'layers', 'recordings', 'references', 'partnerRoundIds']) {if (key in patch) merged[key] = patch[key];}merged.id = id;merged.createdAt = songs[idx].createdAt;merged.updatedAt = new Date().toISOString();- const song = sanitizeSong(merged);+ const song = sanitizeRound(merged);songs[idx] = song;- await atomicWrite(STATE_PATH, { songs });+ await atomicWrite(STATE_PATH, { rounds: songs });console.log(`🎵 Updated song "${song.title}" (${id})`);return song;});@@ -867,9 +867,9 @@ export async function updateSong(id, patch) {// an older version of the song and want the newer shipped one. User-owned state// is preserved: their recorded takes, their `learned` progress, and the// original createdAt. Throws ERR_NOT_BUILTIN for a non-default song.-export async function refreshSongFromTemplate(id) {+export async function refreshRoundFromTemplate(id) {return enqueue(async () => {- const songs = await readSongs();+ const songs = await readRounds();const idx = songs.findIndex((s) => s.id === id);if (idx === -1) throw makeErr(`Song ${id} not found`, ERR_NOT_FOUND);const template = seedTemplate(id);@@ -882,7 +882,7 @@ export async function refreshSongFromTemplate(id) {const recordings = (existing.recordings || []).map((r) => (r.layerId && !templateLayerIds.has(r.layerId) ? { ...r, layerId: '' } : r));- const song = sanitizeSong({+ const song = sanitizeRound({...template,id,learned: existing.learned,@@ -894,19 +894,19 @@ export async function refreshSongFromTemplate(id) {updatedAt: new Date().toISOString(),});songs[idx] = song;- await atomicWrite(STATE_PATH, { songs });+ await atomicWrite(STATE_PATH, { rounds: songs });console.log(`🔄 Refreshed built-in song "${song.title}" (${id}) from template`);return song;});}-export async function deleteSong(id) {+export async function deleteRound(id) {return enqueue(async () => {- const songs = await readSongs();+ const songs = await readRounds();const idx = songs.findIndex((s) => s.id === id);if (idx === -1) throw makeErr(`Song ${id} not found`, ERR_NOT_FOUND);const [removed] = songs.splice(idx, 1);- await atomicWrite(STATE_PATH, { songs });+ await atomicWrite(STATE_PATH, { rounds: songs });console.log(`🗑️ Deleted song "${removed.title}" (${id})`);return { id };});diff --git a/server/services/songs.test.js b/server/services/rounds.test.jssimilarity index 72%rename from server/services/songs.test.jsrename to server/services/rounds.test.jsindex 2407610a94..f2e14ae0ca 100644--- a/server/services/songs.test.js+++ b/server/services/rounds.test.js@@ -8,7 +8,7 @@ const scratch = vi.hoisted(() => {const { mkdtempSync, mkdirSync } = require('fs');const { tmpdir } = require('os');const { join: j } = require('path');- const dir = mkdtempSync(j(tmpdir(), 'songs-svc-'));+ const dir = mkdtempSync(j(tmpdir(), 'rounds-svc-'));mkdirSync(j(dir, 'data'), { recursive: true });return { dir };});@@ -20,14 +20,14 @@ vi.mock('../lib/fileUtils.js', async () => {};});-import * as svc from './songs.js';+import * as svc from './rounds.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');+const STATE_FILE = join(scratch.dir, 'data', 'rounds.json');-describe('songs service', () => {+describe('rounds service', () => {beforeEach(() => {if (existsSync(STATE_FILE)) unlinkSync(STATE_FILE);});@@ -37,7 +37,7 @@ describe('songs service', () => {});it('seeds the 500 Miles example on first read and persists it', async () => {- const songs = await svc.listSongs();+ const songs = await svc.listRounds();expect(songs.length).toBeGreaterThan(0);const seed = songs.find((s) => s.id === 'seed-500-miles');expect(seed).not.toBeNull();@@ -46,50 +46,50 @@ describe('songs service', () => {expect(seed.rhythmShapeId).toBe('slow-4-4');// Persisted, so a re-read returns the same seed (no re-seed churn).expect(existsSync(STATE_FILE)).toBe(true);- const again = await svc.listSongs();+ const again = await svc.listRounds();expect(again.find((s) => s.id === 'seed-500-miles')).toBeDefined();});it('creates a song with a generated id, newest-first', async () => {- await svc.listSongs(); // seed- const song = await svc.createSong({ title: 'Wayfaring Stranger', key: 'D minor', tempo: 60 });- expect(song.id).toMatch(/^song-/);+ await svc.listRounds(); // seed+ const song = await svc.createRound({ title: 'Wayfaring Stranger', key: 'D minor', tempo: 60 });+ expect(song.id).toMatch(/^round-/);expect(song.title).toBe('Wayfaring Stranger');expect(song.tempo).toBe(60);- const songs = await svc.listSongs();+ const songs = await svc.listRounds();expect(songs[0].id).toBe(song.id); // unshifted to front});it('nulls a missing tempo on create', async () => {- const noTempo = await svc.createSong({ title: 'No tempo' });+ const noTempo = await svc.createRound({ title: 'No tempo' });expect(noTempo.tempo).toBeNull();});it('does not lose a song when a create races the first-read seed write', async () => {- // Regression guard: on a fresh (unseeded) store, listSongs() previously+ // Regression guard: on a fresh (unseeded) store, listRounds() previously// wrote the seed from the read path OUTSIDE the write queue, so a late// seed write could clobber a just-created song. Fire both without awaiting// the list first; the created song must survive.expect(existsSync(STATE_FILE)).toBe(false);const [, created] = await Promise.all([- svc.listSongs(),- svc.createSong({ title: 'Race winner' }),+ svc.listRounds(),+ svc.createRound({ title: 'Race winner' }),]);- const songs = await svc.listSongs();+ const songs = await svc.listRounds();expect(songs.find((s) => s.id === created.id)).toBeTruthy();expect(songs.find((s) => s.title === '500 Miles')).toBeTruthy(); // seed also present});it('clamps an out-of-band tempo on the sanitize/read path', () => {- // The route 400s an out-of-band tempo before createSong runs, so this+ // The route 400s an out-of-band tempo before createRound runs, so this// clamp only ever fires when reading hand-edited JSON — exercise it there.- expect(svc.sanitizeSong({ id: 'x', tempo: 9000 }).tempo).toBe(svc.TEMPO_MAX);- expect(svc.sanitizeSong({ id: 'x', tempo: 1 }).tempo).toBe(svc.TEMPO_MIN);- expect(svc.sanitizeSong({ id: 'x', tempo: 'fast' }).tempo).toBeNull();+ expect(svc.sanitizeRound({ id: 'x', tempo: 9000 }).tempo).toBe(svc.TEMPO_MAX);+ expect(svc.sanitizeRound({ id: 'x', tempo: 1 }).tempo).toBe(svc.TEMPO_MIN);+ expect(svc.sanitizeRound({ id: 'x', tempo: 'fast' }).tempo).toBeNull();});it('drops empty sections/layers and labels the survivors', async () => {- const song = await svc.createSong({+ const song = await svc.createRound({title: 'Layered',sections: [{ label: '', lyrics: '' }, { label: 'Verse', lyrics: 'la la' }],layers: [{ label: '', part: '', notes: '' }, { part: 'Bass', notes: 'root' }],@@ -104,7 +104,7 @@ describe('songs service', () => {// The editor strips in-session temp ids before save (sends id: '') so the// server mints stable, non-colliding ids — guards against the reload// duplicate-key bug where persisted temp ids could be re-minted.- const song = await svc.createSong({+ const song = await svc.createRound({title: 'Blank ids',sections: [{ id: '', label: 'A', lyrics: '1' }, { id: '', label: 'B', lyrics: '2' }],layers: [{ id: '', label: 'L1', part: 'x' }, { id: '', label: 'L2', part: 'y' }],@@ -117,8 +117,8 @@ describe('songs service', () => {});it('merges patches field-by-field — absent key preserves, present key applies', async () => {- const song = await svc.createSong({ title: 'Original', artist: 'Someone', key: 'C' });- const patched = await svc.updateSong(song.id, { title: 'Renamed', key: '' });+ const song = await svc.createRound({ title: 'Original', artist: 'Someone', key: 'C' });+ const patched = await svc.updateRound(song.id, { title: 'Renamed', key: '' });expect(patched.title).toBe('Renamed');expect(patched.artist).toBe('Someone'); // untouched key preservedexpect(patched.key).toBe(''); // empty string clears@@ -126,26 +126,26 @@ describe('songs service', () => {});it('throws NOT_FOUND when updating or deleting a missing song', async () => {- await expect(svc.updateSong('song-nope', { title: 'x' })).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });- await expect(svc.deleteSong('song-nope')).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });+ await expect(svc.updateRound('song-nope', { title: 'x' })).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });+ await expect(svc.deleteRound('song-nope')).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });});it('deletes a song by id', async () => {- const song = await svc.createSong({ title: 'Delete me' });- const result = await svc.deleteSong(song.id);+ const song = await svc.createRound({ title: 'Delete me' });+ const result = await svc.deleteRound(song.id);expect(result.id).toBe(song.id);- const songs = await svc.listSongs();+ const songs = await svc.listRounds();expect(songs.find((s) => s.id === song.id)).toBeUndefined();});- it('sanitizeSong rejects shapeless records', () => {- expect(svc.sanitizeSong(null)).toBeNull();- expect(svc.sanitizeSong({})).toBeNull(); // no id- expect(svc.sanitizeSong({ id: 'x' }).title).toBe('Untitled song');+ it('sanitizeRound rejects shapeless records', () => {+ expect(svc.sanitizeRound(null)).toBeNull();+ expect(svc.sanitizeRound({})).toBeNull(); // no id+ expect(svc.sanitizeRound({ id: 'x' }).title).toBe('Untitled round');});it('sanitizes recordings — drops fileless takes, clamps peak, mints ids', () => {- const song = svc.sanitizeSong({+ const song = svc.sanitizeRound({id: 'x',recordings: [{ layerId: 'lead', filename: 'a-vocal.wav', durationMs: 1200.7, peak: 0.4 },@@ -162,19 +162,19 @@ describe('songs service', () => {});it('preserves a stable recording id submitted with the take', () => {- const song = svc.sanitizeSong({ id: 'x', recordings: [{ id: 'rec-keep', filename: 'k.wav' }] });+ const song = svc.sanitizeRound({ id: 'x', recordings: [{ id: 'rec-keep', filename: 'k.wav' }] });expect(song.recordings[0].id).toBe('rec-keep');});it('legacy takes load unchanged — no pitchTrack/accuracy keys added', () => {- const song = svc.sanitizeSong({ id: 'x', recordings: [{ filename: 'legacy.wav', durationMs: 500 }] });+ const song = svc.sanitizeRound({ id: 'x', recordings: [{ filename: 'legacy.wav', durationMs: 500 }] });const rec = song.recordings[0];expect(rec).not.toHaveProperty('pitchTrack');expect(rec).not.toHaveProperty('accuracy');});it('persists + bounds a downsampled pitchTrack, dropping shapeless samples', () => {- const song = svc.sanitizeSong({+ const song = svc.sanitizeRound({id: 'x',recordings: [{filename: 'take.wav',@@ -193,12 +193,12 @@ describe('songs service', () => {it('clamps an oversized pitchTrack to PITCH_TRACK_MAX', () => {const samples = Array.from({ length: svc.PITCH_TRACK_MAX + 50 }, (_, i) => ({ tMs: i, hz: 200 }));- const song = svc.sanitizeSong({ id: 'x', recordings: [{ filename: 't.wav', pitchTrack: samples }] });+ const song = svc.sanitizeRound({ id: 'x', recordings: [{ filename: 't.wav', pitchTrack: samples }] });expect(song.recordings[0].pitchTrack).toHaveLength(svc.PITCH_TRACK_MAX);});it('persists an accuracy summary, clamping percent and dropping unknown grades', () => {- const song = svc.sanitizeSong({+ const song = svc.sanitizeRound({id: 'x',recordings: [{filename: 't.wav',@@ -218,7 +218,7 @@ describe('songs service', () => {});it('derives accuracy.graded from perNote when not supplied', () => {- const song = svc.sanitizeSong({+ const song = svc.sanitizeRound({id: 'x',recordings: [{ filename: 't.wav', accuracy: { perNote: ['in-tune', 'off'] } }],});@@ -227,19 +227,19 @@ describe('songs service', () => {});it('omits accuracy when there is nothing to persist', () => {- const song = svc.sanitizeSong({ id: 'x', recordings: [{ filename: 't.wav', accuracy: 'not-an-object' }] });+ const song = svc.sanitizeRound({ id: 'x', recordings: [{ filename: 't.wav', accuracy: 'not-an-object' }] });expect(song.recordings[0]).not.toHaveProperty('accuracy');});// --- Training progress (#1028) -----------------------------------------it('legacy/untrained songs load with no progress key', () => {- expect(svc.sanitizeSong({ id: 'x' })).not.toHaveProperty('progress');+ expect(svc.sanitizeRound({ id: 'x' })).not.toHaveProperty('progress');// An empty history object is nothing to persist → omit.- expect(svc.sanitizeSong({ id: 'x', progress: { history: {} } })).not.toHaveProperty('progress');+ expect(svc.sanitizeRound({ id: 'x', progress: { history: {} } })).not.toHaveProperty('progress');});it('persists a per-scope training history, clamping percent and dropping zero-note attempts', () => {- const song = svc.sanitizeSong({+ const song = svc.sanitizeRound({id: 'x',progress: {history: {@@ -257,7 +257,7 @@ describe('songs service', () => {});it('drops a scope whose attempts all fail sanitization', () => {- const song = svc.sanitizeSong({+ const song = svc.sanitizeRound({id: 'x',progress: { history: { 'sec-1': [{ percentInTune: 90, graded: 0 }], 'sec-2': [{ percentInTune: 70, graded: 3 }] } },});@@ -266,7 +266,7 @@ describe('songs service', () => {});it('drops prototype-pollution-prone scope keys from a hand-edited file', () => {- const song = svc.sanitizeSong({+ const song = svc.sanitizeRound({id: 'x',progress: { history: { '__proto__': [{ percentInTune: 90, graded: 3 }], 'sec-1': [{ percentInTune: 70, graded: 3 }] } },});@@ -277,39 +277,39 @@ describe('songs service', () => {it('clamps an oversized per-scope history to PROGRESS_HISTORY_MAX', () => {const attempts = Array.from({ length: svc.PROGRESS_HISTORY_MAX + 20 }, () => ({ percentInTune: 80, graded: 3 }));- const song = svc.sanitizeSong({ id: 'x', progress: { history: { 'sec-1': attempts } } });+ const song = svc.sanitizeRound({ id: 'x', progress: { history: { 'sec-1': attempts } } });expect(song.progress.history['sec-1']).toHaveLength(svc.PROGRESS_HISTORY_MAX);});- it('updateSong merges progress and preserves it across an unrelated edit', async () => {- await svc.listSongs();- const created = await svc.createSong({ title: 'Practice me' });- const withProgress = await svc.updateSong(created.id, {+ it('updateRound merges progress and preserves it across an unrelated edit', async () => {+ await svc.listRounds();+ const created = await svc.createRound({ title: 'Practice me' });+ const withProgress = await svc.updateRound(created.id, {progress: { history: { '__whole__': [{ percentInTune: 85, graded: 5 }] } },});expect(withProgress.progress.history['__whole__']).toHaveLength(1);// A later edit that doesn't touch progress keeps it (absent key preserves).- const renamed = await svc.updateSong(created.id, { title: 'Renamed' });+ const renamed = await svc.updateRound(created.id, { title: 'Renamed' });expect(renamed.progress.history['__whole__']).toHaveLength(1);});- it('refreshSongFromTemplate preserves the user training progress', async () => {- await svc.listSongs();- const seedId = [...svc.BUILTIN_SONG_IDS][0];- await svc.updateSong(seedId, { progress: { history: { 'sec-1': [{ percentInTune: 90, graded: 4 }] } } });- const refreshed = await svc.refreshSongFromTemplate(seedId);+ it('refreshRoundFromTemplate preserves the user training progress', async () => {+ await svc.listRounds();+ const seedId = [...svc.BUILTIN_ROUND_IDS][0];+ await svc.updateRound(seedId, { progress: { history: { 'sec-1': [{ percentInTune: 90, graded: 4 }] } } });+ const refreshed = await svc.refreshRoundFromTemplate(seedId);expect(refreshed.progress.history['sec-1']).toHaveLength(1);});it('stamps builtIn from the seed-id set, ignoring the raw value', () => {- const seedId = [...svc.BUILTIN_SONG_IDS][0];- expect(svc.sanitizeSong({ id: seedId }).builtIn).toBe(true);+ const seedId = [...svc.BUILTIN_ROUND_IDS][0];+ expect(svc.sanitizeRound({ id: seedId }).builtIn).toBe(true);// A custom song can't spoof builtIn even if the raw record claims it.- expect(svc.sanitizeSong({ id: 'song-custom', builtIn: true }).builtIn).toBe(false);+ expect(svc.sanitizeRound({ id: 'song-custom', builtIn: true }).builtIn).toBe(false);});it('seeds the 500 Miles default as a built-in with reference videos', async () => {- const songs = await svc.listSongs();+ const songs = await svc.listRounds();const seed = songs.find((s) => s.title === '500 Miles');expect(seed.builtIn).toBe(true);expect(seed.references.length).toBeGreaterThan(0);@@ -317,21 +317,21 @@ describe('songs service', () => {});it('ships a sheet-music score on the 500 Miles default', async () => {- const songs = await svc.listSongs();+ const songs = await svc.listRounds();const seed = songs.find((s) => s.title === '500 Miles');expect(seed.score).toContain('clef: treble');expect(seed.score).toContain('(train)');});it('sanitizes the score field — trims and caps to SCORE_MAX_LENGTH', () => {- expect(svc.sanitizeSong({ id: 'x', score: ' | C4q | ' }).score).toBe('| C4q |');- expect(svc.sanitizeSong({ id: 'x', score: 123 }).score).toBe(''); // non-string → ''+ expect(svc.sanitizeRound({ id: 'x', score: ' | C4q | ' }).score).toBe('| C4q |');+ expect(svc.sanitizeRound({ id: 'x', score: 123 }).score).toBe(''); // non-string → ''const long = 'C'.repeat(svc.SCORE_MAX_LENGTH + 50);- expect(svc.sanitizeSong({ id: 'x', score: long }).score.length).toBe(svc.SCORE_MAX_LENGTH);+ expect(svc.sanitizeRound({ 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({+ const song = svc.sanitizeRound({id: 'x',scoreParts: [{ id: 'part-keep', label: 'Bass', role: 'bass', score: '| G2w(x) |' },@@ -348,11 +348,11 @@ describe('songs service', () => {});it('defaults scoreParts to [] when absent (backward compatible)', () => {- expect(svc.sanitizeSong({ id: 'x' }).scoreParts).toEqual([]);+ expect(svc.sanitizeRound({ id: 'x' }).scoreParts).toEqual([]);});it('sanitizes references — drops urlless entries, mints ids', () => {- const song = svc.sanitizeSong({+ const song = svc.sanitizeRound({id: 'x',references: [{ url: 'https://www.tiktok.com/@u/video/123', label: 'A' },@@ -366,10 +366,10 @@ describe('songs service', () => {});it('refreshes a built-in from template, preserving recordings + learned', async () => {- await svc.listSongs(); // seed- const seedId = [...svc.BUILTIN_SONG_IDS][0];+ await svc.listRounds(); // seed+ const seedId = [...svc.BUILTIN_ROUND_IDS][0];// User edits the song and records a take + marks it learned.- const edited = await svc.updateSong(seedId, {+ const edited = await svc.updateRound(seedId, {title: 'My edited title',sections: [{ label: 'Custom', lyrics: 'changed' }],score: '', // user cleared the sheet music@@ -380,7 +380,7 @@ describe('songs service', () => {expect(edited.title).toBe('My edited title');expect(edited.score).toBe('');- const refreshed = await svc.refreshSongFromTemplate(seedId);+ const refreshed = await svc.refreshRoundFromTemplate(seedId);// Shipped content restored…expect(refreshed.title).toBe('500 Miles');expect(refreshed.references.every((r) => r.url.includes('tiktok.com'))).toBe(true);@@ -395,13 +395,13 @@ describe('songs service', () => {});it('unassigns a recording whose layer the template lacks when refreshing', async () => {- await svc.listSongs();- const seedId = [...svc.BUILTIN_SONG_IDS][0];- await svc.updateSong(seedId, {+ await svc.listRounds();+ const seedId = [...svc.BUILTIN_ROUND_IDS][0];+ await svc.updateRound(seedId, {layers: [{ id: 'custom-counter', label: 'Counter', part: 'Tenor' }],recordings: [{ filename: 'take.wav', layerId: 'custom-counter' }],});- const refreshed = await svc.refreshSongFromTemplate(seedId);+ const refreshed = await svc.refreshRoundFromTemplate(seedId);// Layers reset to the template set, so the custom layer is gone…expect(refreshed.layers.some((l) => l.id === 'custom-counter')).toBe(false);// …and the take that referenced it is unassigned rather than orphaned.@@ -410,7 +410,7 @@ describe('songs service', () => {});it('drops a non-http(s) reference url (defense-in-depth)', () => {- const song = svc.sanitizeSong({+ const song = svc.sanitizeRound({id: 'x',references: [{ url: 'javascript:alert(1)' }, // dangerous scheme → dropped@@ -422,13 +422,13 @@ describe('songs service', () => {});it('refresh throws NOT_BUILTIN for a custom song and NOT_FOUND for a missing one', async () => {- const custom = await svc.createSong({ title: 'Mine' });- 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 });+ const custom = await svc.createRound({ title: 'Mine' });+ await expect(svc.refreshRoundFromTemplate(custom.id)).rejects.toMatchObject({ code: svc.ERR_NOT_BUILTIN });+ await expect(svc.refreshRoundFromTemplate('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();+ const songs = await svc.listRounds();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();@@ -438,7 +438,7 @@ describe('songs service', () => {});it('ships parseable sheet-music scores on every seeded song', async () => {- const songs = await svc.listSongs();+ const songs = await svc.listRounds();const withScore = songs.filter((s) => s.score);expect(withScore.length).toBeGreaterThan(0);for (const s of withScore) {@@ -454,37 +454,37 @@ describe('songs service', () => {});it('links the three classic quodlibet rounds to each other as partners', async () => {- const songs = await svc.listSongs();+ const songs = await svc.listRounds();const heyHo = songs.find((s) => s.id === 'seed-hey-ho-nobody-home');- expect(heyHo.partnerSongIds).toEqual(+ expect(heyHo.partnerRoundIds).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) {+ for (const id of heyHo.partnerRoundIds) {const partner = songs.find((s) => s.id === id);- expect(partner.partnerSongIds).toContain('seed-hey-ho-nobody-home');+ expect(partner.partnerRoundIds).toContain('seed-hey-ho-nobody-home');}});- it('sanitizes partnerSongIds — drops blanks, dedupes, and drops self-references', () => {- const song = svc.sanitizeSong({+ it('sanitizes partnerRoundIds — drops blanks, dedupes, and drops self-references', () => {+ const song = svc.sanitizeRound({id: 'seed-rose-rose-rose-red',- partnerSongIds: ['seed-ah-poor-bird', '', ' ', 'seed-ah-poor-bird', 'seed-rose-rose-rose-red', 42],+ partnerRoundIds: ['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']);+ expect(song.partnerRoundIds).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+ it('defaults partnerRoundIds to [] and round-trips a patch', async () => {+ const song = await svc.createRound({ title: 'Solo' });+ expect(song.partnerRoundIds).toEqual([]);+ const patched = await svc.updateRound(song.id, { partnerRoundIds: [song.id, 'song-other'] });+ expect(patched.partnerRoundIds).toEqual(['song-other']); // self dropped});- it('getSong returns null for a non-existent id', async () => {- await svc.listSongs(); // ensure seeded- const missing = await svc.getSong('song-does-not-exist-xyz');+ it('getRound returns null for a non-existent id', async () => {+ await svc.listRounds(); // ensure seeded+ const missing = await svc.getRound('song-does-not-exist-xyz');expect(missing).toBeNull();});});diff --git a/server/services/songsAI.js b/server/services/roundsAI.jssimilarity index 94%rename from server/services/songsAI.jsrename to server/services/roundsAI.jsindex f3c08f9aca..61cf2b5bd7 100644--- a/server/services/songsAI.js+++ b/server/services/roundsAI.js@@ -1,21 +1,21 @@/**- * Songs AI — generate & evaluate a cappella arrangements.+ * Rounds AI — generate & evaluate a cappella arrangements.** Two single-shot LLM calls (the synchronous universe-builder pattern, NOT- * streaming): `generateSong` drafts a full arrangement from a title/brief, and- * `evaluateSong` critiques an existing one. Both build the prompt inline (no+ * streaming): `generateRound` drafts a full arrangement from a title/brief, and+ * `evaluateRound` critiques an existing one. Both build the prompt inline (no* shipped stage-prompt file — these are one-shot JSON contracts, so the inline* pattern from recordMergeAI.js/agentContentGenerator.js fits) and parse the* response with the shared jsonExtract helper.*- * Output is projected onto the canonical song shape via sanitizeSong (generate)+ * Output is projected onto the canonical song shape via sanitizeRound (generate)* or a small verdict shape (evaluate) so a hallucinated/extra field can't leak* into storage. The rhythm-shape and voice-layer vocabularies are injected into* the prompt from songCraftRef.js so the model returns ids the editor's pickers* already understand — but unknown ids are accepted downstream (free-text* fallback), so a drifted model can't 400.*- * Kept separate from services/songs.js (pure CRUD) so the AI dependency+ * Kept separate from services/rounds.js (pure CRUD) so the AI dependency* (promptRunner → providers → runner) doesn't load on every plain song read.*/@@ -27,9 +27,9 @@ import {HARMONY_PARTS, DERIVABLE_HARMONY_PARTS,} from '../lib/songCraftRef.js';import {- sanitizeSong, FIELD_MAX_LENGTH, SECTIONS_MAX, LAYERS_MAX,+ sanitizeRound, FIELD_MAX_LENGTH, SECTIONS_MAX, LAYERS_MAX,SCORE_MAX_LENGTH, SCORE_PARTS_MAX,-} from './songs.js';+} from './rounds.js';// Strip dangerous control chars that would corrupt the prompt or invite// structure-injection (a lyric containing a fake "# Output contract" header),@@ -110,14 +110,14 @@ Keep lyrics original (do not reproduce copyrighted lyrics verbatim). Each string/*** Generate a full song arrangement from a brief. Returns the sanitized song* fields (NOT persisted — the route/caller merges into a stored record) plus an- * `llm` attribution block. `existingSong` (optional) is folded into the prompt+ * `llm` attribution block. `existingRound` (optional) is folded into the prompt* so "generate" doubles as "expand this draft".*/-export async function generateSong({ title, artist, brief, mood, existingSong, providerId, model } = {}) {+export async function generateRound({ title, artist, brief, mood, existingRound, providerId, model } = {}) {const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });assertProvider(provider, { message: 'No AI provider available for song generation', code: 'NO_PROVIDER' });- const existing = existingSong ? summarizeSongForPrompt(existingSong) : '';+ const existing = existingRound ? summarizeSongForPrompt(existingRound) : '';const prompt = buildGeneratePrompt({title: clean(title), artist: clean(artist), brief: clean(brief), mood: clean(mood), existing,});@@ -127,9 +127,9 @@ export async function generateSong({ title, artist, brief, mood, existingSong, p});const parsed = parseOrThrow(raw, isGeneratedShape, 'generation');- // Project onto the canonical shape; sanitizeSong requires an id, so stamp a+ // Project onto the canonical shape; sanitizeRound requires an id, so stamp a// placeholder the caller replaces — we only want the normalized fields back.- const song = sanitizeSong({ ...parsed, id: 'draft' });+ const song = sanitizeRound({ ...parsed, id: 'draft' });if (!song) {throw new ServerError('The AI produced an unusable song. Try rerunning.', { status: 502, code: 'LLM_EMPTY' });}@@ -193,7 +193,7 @@ Return ONLY a JSON object (no prose, no markdown fence):* strengths[], weaknesses[], suggestions[] } plus an `llm` block. Pure* read-side AI — does not mutate the song.*/-export async function evaluateSong({ song, providerId, model } = {}) {+export async function evaluateRound({ song, providerId, model } = {}) {if (!song || typeof song !== 'object') {throw new ServerError('A song is required to evaluate', { status: 400, code: 'VALIDATION_ERROR' });}@@ -325,7 +325,7 @@ const normalizeDerivedParts = (rawParts) =>* 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 } = {}) {+export async function deriveRoundParts({ song, partIds, providerId, model } = {}) {if (!song || typeof song !== 'object') {throw new ServerError('A song is required to derive parts', { status: 400, code: 'VALIDATION_ERROR' });}diff --git a/server/services/songsAI.test.js b/server/services/roundsAI.test.jssimilarity index 85%rename from server/services/songsAI.test.jsrename to server/services/roundsAI.test.jsindex a21a5a8de9..07fea23713 100644Binary files a/server/services/songsAI.test.js and b/server/services/roundsAI.test.js differ