Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Add Songs: a cappella song writing & learning workbench

Adam Eivyfabe98592af5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f1baf8d0a9..592b73c5ed 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,7 @@
## Added
+- **Songs — an a cappella song workbench (Create → Songs)** — write, arrange, and learn songs like "500 Miles" by Peter, Paul and Mary. Each song tracks its key, tempo, and rhythm shape (slow 4/4 ballad, compound 6/8 dirge, free-time lament, and more), lyric sections, and the voice layers you're stacking — with per-layer learning notes. An "Add from ladder" picker seeds layers in the recommended foundation-first order (lead → bass → thirds → fifths → drone → counter-melody). A deep-linkable **Learning Guide** (Create → Songs → Learning Guide, or `/songs/guide`) covers dirge rhythm shapes with tempo bands, the layer-building ladder, a step-by-step practice sequence for learning a new song, and a plain-language musical-notation primer (staves, time signatures, note values, dynamics, reading a lead sheet). A worked "500 Miles" example is seeded on first visit. Reachable from `⌘K` and voice nav.
- **Daily budgets for the Chief of Staff's domains** — each domain (Brain auto-classify, Memory auto-extract, CoS auto-run, Messages auto-send) can now carry a daily cap on how many automatic actions it takes and how many minutes of work it does. When a domain reaches its cap it pauses that automatic work for the rest of the day and resumes after the counters reset at midnight; the Chief of Staff config panel shows each domain's usage so far today. Caps are off by default (blank means unlimited), so nothing changes until you set one. This rounds out the per-domain guardrails alongside the off / dry-run / execute controls.
- **Scheduled "Claim Issue" task** — a new built-in CoS schedule (CoS → Schedule → Claim Issue) that runs the `/claim --issues` flow on a cadence: it picks the next open GitHub issue, creates its own `claim/issue-<num>` worktree, implements the fix, opens a PR that closes the issue, runs the configured reviewers, merges, and cleans up. Configurable per app via an **Issue Author Filter** — claim only issues filed by the repository owner (default) or any open issue regardless of author. Off by default; enable and pick a provider/model per app like the other improvement tasks.
- **Scheduled "Refresh local-LLM catalog" task** — a new built-in CoS schedule that periodically researches the current best local models per category and opens a PR refreshing PortOS's bundled suggested-models catalog (`server/lib/localLlmCatalog.js`) and the editorial model ranking, so the in-app install picker and recommendations don't go stale. It no-ops on any repo lacking the catalog file, so it only does work when enabled on the PortOS app itself. Off by default; weekly when enabled, and it only opens a PR when the catalog is actually out of date.
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 35c0591192..b87596cf3d 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -45,6 +45,9 @@ const Loras = lazyWithReload(() => import('./pages/Loras'));
const UniverseBuilder = lazyWithReload(() => import('./pages/UniverseBuilder'));
const Universes = lazyWithReload(() => import('./pages/Universes'));
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 CatalogIngest = lazyWithReload(() => import('./pages/CatalogIngest'));
const CatalogIngredient = lazyWithReload(() => import('./pages/CatalogIngredient'));
const VideoTimeline = lazyWithReload(() => import('./pages/VideoTimeline'));
@@ -274,6 +277,9 @@ export default function App() {
at `/universes/:universeId`; `new` is the create-mode sentinel
(UniverseBuilder treats it as no-id → blank draft). Universe ids are
UUIDs, 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="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.jsx
index ee07e84a86..e316bbce5e 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -83,6 +83,7 @@ import {
Pin,
PinOff,
Navigation,
+ Music,
Workflow as WorkflowIcon
} from 'lucide-react';
/* global __APP_VERSION__ */
@@ -199,6 +200,7 @@ const navItems = [
{ to: '/media', label: 'Media Gen', icon: Layers },
{ 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 },
@@ -1183,6 +1185,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
+ // (list + create form) takes the normal padded+scrolling main.
+ location.pathname.startsWith('/songs/') ||
location.pathname.startsWith('/wiki') ||
// Only the universe EDITOR (/universes/:id, /universes/new) is
// full-width — it manages its own scroll. The /universes index
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 4db7079a90..b26305d6b4 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -85,5 +85,6 @@ grep -i "what you want to do" client/src/lib/README.md
|---|---|
| `cityPlaybackFrame.js` | Map a recorded CyberCity snapshot frame onto the prop shape CityScene/CityHud consume for the timeline scrubber (`mergeFrameIntoCityProps`, `buildPlaybackApps`, `buildPlaybackAgentMap`, `isPlayableFrame`). Honors `schemaVersion` and the capture-side null sentinels; returns only snapshot-backed props so unfed landmarks stay live. |
| `universeBuilderExpand.js` | `mergeExpandIntoDraft(draft, result)` — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with `kind` precedence, canon dedupe by name/slugline/alias). Also exports `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` for callers that need the building blocks (per-category Generate, save-time refetch+merge). |
+| `songCraft.js` | Canonical a cappella song-craft reference data rendered by the Songs Guide (`/songs/guide`) and reused by the Song editor: `RHYTHM_SHAPES` / `DIRGE_RHYTHM_SHAPES` (dirge & ballad pulse feels with BPM bands), `VOICE_LAYERS` (foundation-first harmony build ladder), `LEARNING_STEPS` (practice sequence), `NOTATION_HELP` (lead-sheet/notation primers), `SOLFEGE_DEGREES` + `solfegeForDegree(n)`. Pure data; pickers and docs read the same source so they can't drift. |
| `wrSceneCursor.js` | Resolve which script scene the editor caret sits in (`sceneAtCursor`, `sceneAnchorIndex`) — inverse of WorkEditor's jump-to-scene text search; drives the live render preview's "scene at cursor" target. |
| `writingGuide.js` | Canonical Writers Room reference data + craft principles rendered by the Guide page (`/writers-room/guide`): `WRITING_LENGTH_TARGETS` (microfiction→novel word/char bands), `BOOK_LENGTH_ESTIMATES` (page-based), `WRITING_PRINCIPLES`, `PLANNED_ANALYSES` (e.g. the emotional-roadmap evaluator), and `classifyByWordCount(n)` for labelling a draft's length. Future word-count gauges / length checks read from here so targets don't drift from the docs. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 495c648696..af716ca609 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -52,6 +52,7 @@ export * from './voiceLabel.js';
// === Page-scoped pure helpers ===
export * from './cityPlaybackFrame.js';
+export * from './songCraft.js';
export * from './universeBuilderExpand.js';
export * from './wrSceneCursor.js';
export * from './writingGuide.js';
diff --git a/client/src/lib/songCraft.js b/client/src/lib/songCraft.js
new file mode 100644
index 0000000000..a6c36e8c1d
--- /dev/null
+++ b/client/src/lib/songCraft.js
@@ -0,0 +1,261 @@
+// Canonical a cappella song-craft reference data: dirge rhythm shapes, the
+// layer-building ladder, a learning sequence, musical-notation help, and the
+// solfège scale used by the editor's harmony helpers. The Songs Guide page
+// renders directly from these arrays; the Song editor reuses RHYTHM_SHAPES,
+// VOICE_LAYERS, and SOLFEGE_DEGREES so the picker options and the docs never
+// drift. Keep this module pure (no React, no imports) — it is mirrored into
+// the client lib barrel and unit-tested for shape.
+
+// --- Rhythm shapes ---------------------------------------------------------
+// A "rhythm shape" is the felt pulse + note-length feel a song leans on. A
+// dirge is a slow, solemn lament (funeral march, ballad of loss) — "500 Miles"
+// by Peter, Paul and Mary sits in the slow-ballad / dirge family. `bpm` carries
+// the typical tempo band, `feel` the conductor's count, and `count` a spoken
+// counting pattern the singer can tap. `dirge` marks the shapes that suit a
+// lament so the guide can highlight the slow family the user asked about.
+export const RHYTHM_SHAPES = [
+ {
+ id: 'slow-4-4',
+ label: 'Slow 4/4 ballad',
+ dirge: true,
+ bpm: { min: 56, max: 76, label: '56–76 BPM' },
+ feel: 'Four even beats per bar, weight on 1 and 3.',
+ count: '1 — 2 — 3 — 4',
+ note: 'The default lament pulse. "500 Miles" lives here: long sustained vowels on the downbeats, lyrics breathing across the bar rather than chopping it up.',
+ },
+ {
+ id: 'dirge-6-8',
+ label: 'Compound 6/8 dirge',
+ dirge: true,
+ bpm: { min: 40, max: 60, label: '40–60 BPM (dotted-quarter pulse)' },
+ feel: 'Two slow pulses per bar, each split into three — a swaying funeral-march lilt.',
+ count: 'ONE-and-a Two-and-a',
+ note: 'The rocking 6/8 underpins many spirituals and laments. Conduct in 2, sing in 6 — the triple subdivision gives the grief a heave-and-settle.',
+ },
+ {
+ id: 'rubato-free',
+ label: 'Rubato / free-time lament',
+ dirge: true,
+ bpm: { min: null, max: null, label: 'No fixed tempo — follow the lead' },
+ feel: 'Pulse stretches and contracts with the phrase; the lead breathes, the layers follow.',
+ count: 'Follow the words, not a click',
+ note: 'Used for the most exposed laments. Drop the metronome: cadence on the lyric, let the harmony swell and release with the lead singer.',
+ },
+ {
+ id: 'cut-time-march',
+ label: 'Cut-time processional',
+ dirge: true,
+ bpm: { min: 60, max: 84, label: '60–84 BPM (half-note pulse)' },
+ feel: 'Two broad pulses per bar — a walking, processional tread.',
+ count: 'ONE . . . TWO . . .',
+ note: 'A dirge that moves. The half-note pulse keeps it solemn but gives a forward, funeral-procession walk under the melody.',
+ },
+ {
+ id: 'driving-4-4',
+ label: 'Driving 4/4 (uptempo)',
+ dirge: false,
+ bpm: { min: 96, max: 132, label: '96–132 BPM' },
+ feel: 'Steady, energetic four — backbeat emphasis on 2 and 4.',
+ count: '1 2 3 4 with a clap on 2 & 4',
+ note: 'Not a dirge — the contrast point. Useful when a set needs to lift out of the laments; clap or stomp the backbeat to drive it.',
+ },
+ {
+ id: 'waltz-3-4',
+ label: 'Waltz 3/4',
+ dirge: false,
+ bpm: { min: 84, max: 144, label: '84–144 BPM' },
+ feel: 'Three beats per bar, strong downbeat then two lighter beats.',
+ count: 'ONE two three',
+ note: 'A lilting triple meter. Slowed right down it can read as a tender lament; kept moving it sways.',
+ },
+];
+
+// --- Voice layers ----------------------------------------------------------
+// The order singers stack parts when arranging a cappella, foundation-first.
+// `order` is the recommended build sequence; `voices` names the typical
+// SATB-ish home for the part. The editor offers these as part labels.
+export const VOICE_LAYERS = [
+ {
+ id: 'lead',
+ label: 'Lead melody',
+ order: 1,
+ voices: 'Any — the tune everyone knows',
+ role: 'The song itself. Everyone learns this first so the harmony has a home to orbit.',
+ advice: 'Lock the lead before adding anything. If the melody is shaky, every layer above it wobbles.',
+ },
+ {
+ id: 'bass',
+ label: 'Bass / root',
+ order: 2,
+ voices: 'Bass',
+ role: 'The harmonic floor — usually the root of each chord, moving slowly.',
+ advice: 'Add the bass second. It defines the chord under the melody and gives the upper voices their tuning reference.',
+ },
+ {
+ id: 'harmony-3rd',
+ label: 'Harmony (third)',
+ order: 3,
+ voices: 'Alto / Tenor',
+ role: 'A line a third above or below the melody — the first taste of chord color.',
+ advice: 'Thirds are the sweet spot: close enough to feel like the tune, far enough to bloom into harmony. Build this before stacking wider intervals.',
+ },
+ {
+ id: 'harmony-5th',
+ label: 'Harmony (fifth)',
+ order: 4,
+ voices: 'Tenor / Soprano',
+ role: 'The fifth fills out the triad and opens the sound up.',
+ advice: 'With root, third and fifth you have a full chord. Add this once the third is solid so the stack stays in tune.',
+ },
+ {
+ id: 'drone',
+ label: 'Drone / pedal',
+ order: 5,
+ voices: 'Bass / Alto',
+ role: 'A sustained held note (often the tonic or fifth) under everything.',
+ advice: 'A drone is the cheapest way to make a lament feel ancient and grounded. One held vowel under the whole verse does enormous work.',
+ },
+ {
+ id: 'counter',
+ label: 'Counter-melody',
+ order: 6,
+ voices: 'Soprano / Tenor',
+ role: 'An independent melodic line that answers the lead in its gaps.',
+ advice: 'Save this for last. It fills the lead\'s breathing spaces — write it into the rests, not on top of the words.',
+ },
+ {
+ id: 'vocal-perc',
+ label: 'Vocal percussion / texture',
+ order: 7,
+ voices: 'Any',
+ role: 'Breath, hums, clicks, "doo"/"ah" pads, or beatbox — rhythmic and textural glue.',
+ advice: 'Optional and genre-dependent. For a dirge, a soft hummed pad beats a beatbox; keep texture serving the mood.',
+ },
+];
+
+// --- Learning steps --------------------------------------------------------
+// The practice sequence for learning a new a cappella song, in order.
+export const LEARNING_STEPS = [
+ {
+ id: 'listen',
+ label: 'Listen first, sing nothing',
+ detail: 'Play a reference recording several times before opening your mouth. Internalize the melody, the feel, and where the phrases breathe.',
+ },
+ {
+ id: 'lyrics',
+ label: 'Learn the lyrics cold',
+ detail: 'Speak the words in rhythm until they are automatic. You can\'t hold a harmony while still hunting for the next line.',
+ },
+ {
+ id: 'melody',
+ label: 'Own the melody',
+ detail: 'Sing the lead until it is effortless and in tune — even if you\'ll ultimately sing harmony. The melody is your map.',
+ },
+ {
+ id: 'find-part',
+ label: 'Find your part',
+ detail: 'Pick the layer that fits your range (see the layer ladder). Learn it against the melody, one phrase at a time.',
+ },
+ {
+ id: 'intervals',
+ label: 'Drill the intervals',
+ detail: 'Where your part leaps or sits against the lead, practice that interval in isolation until you can find it without the melody playing.',
+ },
+ {
+ id: 'layer',
+ label: 'Layer in slowly',
+ detail: 'Add voices one at a time, foundation-first: lead, then bass, then thirds, then fifths. Stop and re-tune whenever a chord sounds muddy.',
+ },
+ {
+ id: 'tempo',
+ label: 'Slow, then up to tempo',
+ detail: 'Rehearse below performance speed until the tuning is locked, then walk the tempo up. For a free-time dirge, rehearse the breaths instead of a click.',
+ },
+ {
+ id: 'memorize',
+ label: 'Memorize and perform',
+ detail: 'Drop the sheet. A cappella lives or dies on listening to each other — you can\'t blend with your eyes buried in a page.',
+ },
+];
+
+// --- Notation help ---------------------------------------------------------
+// Plain-language primers for reading lead sheets and basic notation. Each
+// `group` carries a title, a one-line summary, and a list of point strings.
+export const NOTATION_HELP = [
+ {
+ id: 'staff',
+ title: 'The staff & note names',
+ summary: 'Five lines, four spaces. Pitch rises as you go up.',
+ points: [
+ 'Treble-clef lines bottom→top: E G B D F ("Every Good Boy Does Fine"); spaces spell F A C E.',
+ 'Bass-clef lines bottom→top: G B D F A ("Good Boys Do Fine Always"); spaces: A C E G.',
+ 'The seven letters A–G repeat each octave; a sharp (♯) raises a semitone, a flat (♭) lowers one.',
+ ],
+ },
+ {
+ id: 'time-signature',
+ title: 'Time signatures',
+ summary: 'Top number = beats per bar; bottom = which note gets the beat.',
+ points: [
+ '4/4 ("common time"): four quarter-note beats per bar — the default for ballads like "500 Miles".',
+ '3/4: a waltz — three beats per bar.',
+ '6/8: six eighth-notes grouped as two pulses of three — the swaying dirge feel.',
+ ],
+ },
+ {
+ id: 'note-values',
+ title: 'Note durations',
+ summary: 'How long to hold each note, relative to the beat.',
+ points: [
+ 'Whole note = 4 beats, half = 2, quarter = 1, eighth = ½, sixteenth = ¼.',
+ 'A dot after a note adds half its value again (dotted half = 3 beats).',
+ 'Rests mirror these durations — silence is part of the rhythm, especially in a lament.',
+ ],
+ },
+ {
+ id: 'dynamics',
+ title: 'Dynamics & expression',
+ summary: 'Markings that shape volume and feel — where a dirge lives.',
+ points: [
+ 'p (piano) = soft, f (forte) = loud; pp / ff are the extremes, mp / mf the middles.',
+ 'Crescendo (<) swells louder; decrescendo (>) fades — laments breathe on these.',
+ 'Fermata (𝄐) = hold the note longer than written, at the singer\'s discretion.',
+ ],
+ },
+ {
+ id: 'lead-sheet',
+ title: 'Reading a lead sheet',
+ summary: 'Most a cappella folk songs are shared as melody + chord symbols + lyrics.',
+ points: [
+ 'Chord symbols (C, Am, G7) sit above the staff at the beat they change — the bass and harmony build their notes from these.',
+ 'Lyrics align under the notes they\'re sung on; a slur or hyphen shows a syllable held across notes.',
+ 'No staff? A Nashville-number or solfège chart still tells you the chord motion — learn the shape, transpose to your key.',
+ ],
+ },
+];
+
+// --- Solfège -------------------------------------------------------------
+// The movable-do major scale degrees. Used by the editor's harmony helper to
+// label a part's home degree and by the guide. Index 0 = tonic (Do).
+export const SOLFEGE_DEGREES = [
+ { degree: 1, solfege: 'Do', semitone: 0 },
+ { degree: 2, solfege: 'Re', semitone: 2 },
+ { degree: 3, solfege: 'Mi', semitone: 4 },
+ { degree: 4, solfege: 'Fa', semitone: 5 },
+ { degree: 5, solfege: 'Sol', semitone: 7 },
+ { degree: 6, solfege: 'La', semitone: 9 },
+ { degree: 7, solfege: 'Ti', semitone: 11 },
+];
+
+// Map a 1–7 scale degree to its solfège syllable. Degrees outside 1–7 wrap
+// into the octave (so 8 → Do, 9 → Re) so callers can pass raw step counts.
+// Returns null for non-numeric input rather than throwing.
+export function solfegeForDegree(degree) {
+ if (typeof degree !== 'number' || !Number.isFinite(degree)) return null;
+ const idx = ((Math.round(degree) - 1) % 7 + 7) % 7;
+ return SOLFEGE_DEGREES[idx].solfege;
+}
+
+// Only the dirge-family rhythm shapes, in declaration order. The Songs Guide
+// leads with these because the lament is what the workbench is built around.
+export const DIRGE_RHYTHM_SHAPES = RHYTHM_SHAPES.filter((s) => s.dirge);
diff --git a/client/src/lib/songCraft.test.js b/client/src/lib/songCraft.test.js
new file mode 100644
index 0000000000..791bbc503d
--- /dev/null
+++ b/client/src/lib/songCraft.test.js
@@ -0,0 +1,76 @@
+import { describe, it, expect } from 'vitest';
+import {
+ RHYTHM_SHAPES,
+ DIRGE_RHYTHM_SHAPES,
+ VOICE_LAYERS,
+ LEARNING_STEPS,
+ NOTATION_HELP,
+ SOLFEGE_DEGREES,
+ solfegeForDegree,
+} from './songCraft.js';
+
+describe('songCraft reference data', () => {
+ it('every rhythm shape carries id, label, bpm band, feel, count and a boolean dirge flag', () => {
+ const ids = new Set();
+ for (const s of RHYTHM_SHAPES) {
+ expect(typeof s.id).toBe('string');
+ expect(s.id.length).toBeGreaterThan(0);
+ expect(ids.has(s.id)).toBe(false);
+ ids.add(s.id);
+ expect(typeof s.label).toBe('string');
+ expect(typeof s.feel).toBe('string');
+ expect(typeof s.count).toBe('string');
+ expect(typeof s.bpm.label).toBe('string');
+ expect(typeof s.dirge).toBe('boolean');
+ }
+ });
+
+ it('exposes the dirge family as a subset of all rhythm shapes', () => {
+ expect(DIRGE_RHYTHM_SHAPES.length).toBeGreaterThan(0);
+ expect(DIRGE_RHYTHM_SHAPES.length).toBeLessThan(RHYTHM_SHAPES.length);
+ for (const s of DIRGE_RHYTHM_SHAPES) {
+ expect(s.dirge).toBe(true);
+ }
+ // The slow 4/4 ballad ("500 Miles") must be a dirge-family shape.
+ expect(DIRGE_RHYTHM_SHAPES.some((s) => s.id === 'slow-4-4')).toBe(true);
+ });
+
+ it('orders voice layers foundation-first with unique sequential order numbers', () => {
+ const orders = VOICE_LAYERS.map((l) => l.order);
+ expect(orders).toEqual([...orders].sort((a, b) => a - b));
+ expect(new Set(orders).size).toBe(orders.length);
+ // Lead melody is always the first layer learned.
+ expect(VOICE_LAYERS[0].id).toBe('lead');
+ for (const l of VOICE_LAYERS) {
+ expect(typeof l.label).toBe('string');
+ expect(typeof l.role).toBe('string');
+ expect(typeof l.advice).toBe('string');
+ }
+ });
+
+ it('every learning step and notation group has the documented shape', () => {
+ for (const step of LEARNING_STEPS) {
+ expect(typeof step.id).toBe('string');
+ expect(typeof step.label).toBe('string');
+ expect(typeof step.detail).toBe('string');
+ }
+ for (const g of NOTATION_HELP) {
+ expect(typeof g.title).toBe('string');
+ expect(typeof g.summary).toBe('string');
+ expect(Array.isArray(g.points)).toBe(true);
+ expect(g.points.length).toBeGreaterThan(0);
+ }
+ });
+
+ it('maps scale degrees to solfège syllables, wrapping octaves', () => {
+ expect(SOLFEGE_DEGREES).toHaveLength(7);
+ expect(solfegeForDegree(1)).toBe('Do');
+ expect(solfegeForDegree(3)).toBe('Mi');
+ expect(solfegeForDegree(5)).toBe('Sol');
+ // Octave wrap: 8 → Do, 9 → Re.
+ expect(solfegeForDegree(8)).toBe('Do');
+ expect(solfegeForDegree(9)).toBe('Re');
+ expect(solfegeForDegree(null)).toBeNull();
+ expect(solfegeForDegree('x')).toBeNull();
+ });
+});
diff --git a/client/src/pages/SongEditor.jsx b/client/src/pages/SongEditor.jsx
new file mode 100644
index 0000000000..6af312d8b8
--- /dev/null
+++ b/client/src/pages/SongEditor.jsx
@@ -0,0 +1,337 @@
+/**
+ * Song editor — /songs/:id.
+ *
+ * Edit one a cappella song: metadata (title/artist/key/tempo/rhythm shape),
+ * lyric sections, the voice layers being stacked, and free-text notation +
+ * arrangement notes. Full-width route (Layout.jsx isFullWidth matches
+ * `/songs/`) so this page owns its own vertical scroll, mirroring
+ * WritersRoomGuide's column layout.
+ *
+ * Saves are explicit (a Save button) rather than per-keystroke — the workbench
+ * is a focused editing surface, and a single PUT keeps the merge simple. The
+ * "Add layer from ladder" picker seeds a layer pre-filled from songCraft's
+ * foundation-first VOICE_LAYERS so the user can build harmony in the
+ * recommended order.
+ */
+
+import { useState, useEffect, useCallback, useMemo } from 'react';
+import { useParams, useNavigate, Link } from 'react-router-dom';
+import {
+ Music, ArrowLeft, Plus, Trash2, Save, BookOpen, CheckCircle2, Circle, Layers,
+} from 'lucide-react';
+import toast from '../components/ui/Toast';
+import { useAsyncAction } from '../hooks/useAsyncAction';
+import { getSong, updateSong } from '../services/api';
+import { RHYTHM_SHAPES, VOICE_LAYERS } from '../lib/songCraft';
+
+// Stable client-side id for a freshly-added section/layer before the server
+// assigns one. Counter-based (not Math.random, which is unavailable in some
+// harnesses and unnecessary here) — uniqueness only needs to hold within the
+// editing session for React keys; the server re-ids on save.
+let localSeq = 0;
+const localId = (prefix) => `${prefix}-new-${localSeq++}`;
+
+export default function SongEditor() {
+ const { id } = useParams();
+ const navigate = useNavigate();
+ const [song, setSong] = useState(null);
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ let cancelled = false;
+ getSong(id, { silent: true })
+ .then((data) => { if (!cancelled) setSong(data?.song || null); })
+ .catch((err) => { if (!cancelled) toast.error(err?.message || 'Failed to load song'); })
+ .finally(() => { if (!cancelled) setLoading(false); });
+ return () => { cancelled = true; };
+ }, [id]);
+
+ // Field setters merge into the in-memory draft; nothing persists until Save.
+ const setField = useCallback((key, value) => {
+ setSong((prev) => (prev ? { ...prev, [key]: value } : prev));
+ }, []);
+
+ const [save, saving] = useAsyncAction(async () => {
+ const patch = {
+ title: song.title, artist: song.artist, key: song.key,
+ tempo: song.tempo ?? null, rhythmShapeId: song.rhythmShapeId,
+ notation: song.notation, notes: song.notes, learned: song.learned,
+ sections: song.sections, layers: song.layers,
+ };
+ const data = await updateSong(id, patch, { silent: true });
+ if (data?.song) setSong(data.song);
+ toast.success('Song saved');
+ return data?.song;
+ }, { errorMessage: 'Failed to save song' });
+
+ // --- Section helpers ----------------------------------------------------
+ const addSection = () => setSong((prev) => ({
+ ...prev,
+ sections: [...(prev.sections || []), { id: localId('sec'), label: 'Section', lyrics: '' }],
+ }));
+ const updateSection = (sid, key, value) => setSong((prev) => ({
+ ...prev,
+ sections: prev.sections.map((s) => (s.id === sid ? { ...s, [key]: value } : s)),
+ }));
+ const removeSection = (sid) => setSong((prev) => ({
+ ...prev, sections: prev.sections.filter((s) => s.id !== sid),
+ }));
+
+ // --- Layer helpers ------------------------------------------------------
+ const addLayer = (preset) => setSong((prev) => ({
+ ...prev,
+ layers: [...(prev.layers || []), preset
+ ? { id: localId(preset.id), label: preset.label, part: preset.voices, notes: preset.advice }
+ : { id: localId('layer'), label: 'Layer', part: '', notes: '' }],
+ }));
+ const updateLayer = (lid, key, value) => setSong((prev) => ({
+ ...prev,
+ layers: prev.layers.map((l) => (l.id === lid ? { ...l, [key]: value } : l)),
+ }));
+ const removeLayer = (lid) => setSong((prev) => ({
+ ...prev, layers: prev.layers.filter((l) => l.id !== lid),
+ }));
+
+ // Layer presets the user hasn't added yet, in foundation-first order.
+ const remainingPresets = useMemo(() => {
+ const have = new Set((song?.layers || []).map((l) => l.label));
+ return VOICE_LAYERS.filter((p) => !have.has(p.label));
+ }, [song?.layers]);
+
+ if (loading) {
+ return <div className="p-6 text-sm text-gray-500">Loading song…</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>
+ </div>
+ );
+ }
+
+ const labelCls = 'block text-xs text-gray-400 mb-1';
+ const inputCls = 'w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:border-port-accent focus:outline-none';
+
+ return (
+ <div className="flex flex-col h-full">
+ {/* Header bar */}
+ <div className="flex items-center gap-3 px-4 py-3 border-b border-port-border bg-port-card shrink-0">
+ <button
+ type="button"
+ onClick={() => navigate('/songs')}
+ className="p-1 text-gray-400 hover:text-white transition-colors"
+ title="Back to Songs"
+ aria-label="Back to Songs"
+ >
+ <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>
+ <Link
+ to="/songs/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} />
+ Guide
+ </Link>
+ <button
+ type="button"
+ onClick={() => save()}
+ disabled={saving}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg bg-port-accent text-white hover:bg-port-accent/90 disabled:opacity-50"
+ >
+ <Save size={14} />
+ {saving ? 'Saving…' : 'Save'}
+ </button>
+ </div>
+
+ {/* Scrollable body */}
+ <div className="flex-1 overflow-y-auto p-4 md:p-6">
+ <div className="max-w-3xl mx-auto space-y-6">
+ {/* Metadata */}
+ <section className="bg-port-card border border-port-border rounded-lg p-4 space-y-4">
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
+ <div>
+ <label htmlFor="title" className={labelCls}>Title</label>
+ <input id="title" type="text" value={song.title} onChange={(e) => setField('title', e.target.value)} className={inputCls} />
+ </div>
+ <div>
+ <label htmlFor="artist" className={labelCls}>Artist</label>
+ <input id="artist" type="text" value={song.artist} onChange={(e) => setField('artist', e.target.value)} className={inputCls} />
+ </div>
+ <div>
+ <label htmlFor="key" className={labelCls}>Key</label>
+ <input id="key" type="text" value={song.key} onChange={(e) => setField('key', e.target.value)} placeholder="e.g. C major" className={inputCls} />
+ </div>
+ <div>
+ <label htmlFor="tempo" className={labelCls}>Tempo (BPM)</label>
+ <input
+ id="tempo"
+ type="number"
+ min="20"
+ max="320"
+ value={song.tempo ?? ''}
+ onChange={(e) => setField('tempo', e.target.value === '' ? null : Number(e.target.value))}
+ placeholder="e.g. 68"
+ className={inputCls}
+ />
+ </div>
+ <div className="sm:col-span-2">
+ <label htmlFor="rhythm" className={labelCls}>Rhythm shape</label>
+ <select id="rhythm" value={song.rhythmShapeId} onChange={(e) => setField('rhythmShapeId', e.target.value)} className={inputCls}>
+ <option value="">— Choose a feel —</option>
+ {RHYTHM_SHAPES.map((s) => (
+ <option key={s.id} value={s.id}>{s.label}{s.dirge ? ' · dirge' : ''} ({s.bpm.label})</option>
+ ))}
+ </select>
+ </div>
+ </div>
+ <label className="flex items-center gap-2 text-sm text-gray-300 cursor-pointer w-fit">
+ <input type="checkbox" checked={song.learned} onChange={(e) => setField('learned', e.target.checked)} className="accent-port-accent" />
+ {song.learned ? <CheckCircle2 size={16} className="text-port-success" /> : <Circle size={16} className="text-gray-600" />}
+ Learned (performance-ready)
+ </label>
+ </section>
+
+ {/* Lyric sections */}
+ <section>
+ <div className="flex items-center justify-between mb-2">
+ <h2 className="text-sm font-semibold text-white">Lyrics & structure</h2>
+ <button type="button" onClick={addSection} 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">
+ <Plus size={14} /> Add section
+ </button>
+ </div>
+ {(song.sections || []).length === 0 ? (
+ <p className="text-xs text-gray-500">No sections yet. Add a verse, chorus, or bridge.</p>
+ ) : (
+ <div className="space-y-3">
+ {song.sections.map((s) => (
+ <div key={s.id} className="bg-port-card border border-port-border rounded-lg p-3">
+ <div className="flex items-center gap-2 mb-2">
+ <input
+ type="text"
+ value={s.label}
+ onChange={(e) => updateSection(s.id, 'label', e.target.value)}
+ placeholder="Section label (Verse 1, Chorus…)"
+ aria-label="Section label"
+ className="flex-1 bg-port-bg border border-port-border rounded-lg px-3 py-1.5 text-sm text-white focus:border-port-accent focus:outline-none"
+ />
+ <button type="button" onClick={() => removeSection(s.id)} className="p-1.5 text-gray-500 hover:text-port-error" aria-label="Remove section">
+ <Trash2 size={15} />
+ </button>
+ </div>
+ <textarea
+ value={s.lyrics}
+ onChange={(e) => updateSection(s.id, 'lyrics', e.target.value)}
+ placeholder="Lyrics…"
+ aria-label="Section lyrics"
+ rows={3}
+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:border-port-accent focus:outline-none font-mono leading-relaxed"
+ />
+ </div>
+ ))}
+ </div>
+ )}
+ </section>
+
+ {/* Voice layers */}
+ <section>
+ <div className="flex items-center justify-between mb-2">
+ <h2 className="flex items-center gap-2 text-sm font-semibold text-white">
+ <Layers size={15} className="text-port-accent" /> Voice layers
+ </h2>
+ <button type="button" onClick={() => addLayer(null)} 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">
+ <Plus size={14} /> Blank layer
+ </button>
+ </div>
+ <p className="text-xs text-gray-500 mb-2">
+ Build foundation-first: lead, then bass, then thirds and fifths. See the{' '}
+ <Link to="/songs/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">
+ {remainingPresets.map((p) => (
+ <button
+ key={p.id}
+ type="button"
+ onClick={() => addLayer(p)}
+ title={p.advice}
+ 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.label}
+ </button>
+ ))}
+ </div>
+ )}
+ {(song.layers || []).length === 0 ? (
+ <p className="text-xs text-gray-500">No layers yet. Add the lead melody first.</p>
+ ) : (
+ <div className="space-y-3">
+ {song.layers.map((l) => (
+ <div key={l.id} className="bg-port-card border border-port-border rounded-lg p-3">
+ <div className="flex items-center gap-2 mb-2">
+ <input
+ type="text"
+ value={l.label}
+ onChange={(e) => updateLayer(l.id, 'label', e.target.value)}
+ placeholder="Layer (Lead, Bass, Harmony…)"
+ aria-label="Layer label"
+ className="flex-1 bg-port-bg border border-port-border rounded-lg px-3 py-1.5 text-sm text-white focus:border-port-accent focus:outline-none"
+ />
+ <input
+ type="text"
+ value={l.part}
+ onChange={(e) => updateLayer(l.id, 'part', e.target.value)}
+ placeholder="Voice (Alto…)"
+ aria-label="Layer voice"
+ className="w-32 bg-port-bg border border-port-border rounded-lg px-3 py-1.5 text-sm text-white focus:border-port-accent focus:outline-none"
+ />
+ <button type="button" onClick={() => removeLayer(l.id)} className="p-1.5 text-gray-500 hover:text-port-error" aria-label="Remove layer">
+ <Trash2 size={15} />
+ </button>
+ </div>
+ <textarea
+ value={l.notes}
+ onChange={(e) => updateLayer(l.id, 'notes', e.target.value)}
+ placeholder="Notes for learning this part — intervals, entrances, breaths…"
+ aria-label="Layer notes"
+ rows={2}
+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:border-port-accent focus:outline-none leading-relaxed"
+ />
+ </div>
+ ))}
+ </div>
+ )}
+ </section>
+
+ {/* Notation + notes */}
+ <section className="grid grid-cols-1 gap-4">
+ <div>
+ <label htmlFor="notation" className={labelCls}>Notation / chords</label>
+ <textarea
+ id="notation"
+ value={song.notation}
+ onChange={(e) => setField('notation', e.target.value)}
+ placeholder="Chord progression, lead-sheet notes, solfège — e.g. C — Am — F — G"
+ rows={3}
+ className={`${inputCls} font-mono leading-relaxed`}
+ />
+ </div>
+ <div>
+ <label htmlFor="notes" className={labelCls}>Arrangement & learning notes</label>
+ <textarea
+ id="notes"
+ value={song.notes}
+ onChange={(e) => setField('notes', e.target.value)}
+ placeholder="How it should feel, dynamics, where to breathe, what to drill…"
+ rows={4}
+ className={`${inputCls} leading-relaxed`}
+ />
+ </div>
+ </section>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/pages/Songs.jsx b/client/src/pages/Songs.jsx
new file mode 100644
index 0000000000..7934785c21
--- /dev/null
+++ b/client/src/pages/Songs.jsx
@@ -0,0 +1,160 @@
+/**
+ * Songs page — a cappella song 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
+ * 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.
+ */
+
+import { useEffect, useState, useCallback } from 'react';
+import { useNavigate, Link } from 'react-router-dom';
+import { Music, Plus, Trash2, BookOpen, CheckCircle2, Circle } from 'lucide-react';
+import toast from '../components/ui/Toast';
+import { timeAgo } from '../utils/formatters';
+import { useAsyncAction } from '../hooks/useAsyncAction';
+import { listSongs, createSong, deleteSong } 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() {
+ const navigate = useNavigate();
+ const [songs, setSongs] = 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.
+ 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'))
+ .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;
+ if (song) navigate(`/songs/${song.id}`);
+ return song;
+ }, { errorMessage: 'Failed to create song' });
+
+ const onDelete = useCallback(async (song) => {
+ if (armed !== song.id) { setArmed(song.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'));
+ }, [armed]);
+
+ return (
+ <div className="max-w-4xl mx-auto">
+ <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>
+ </div>
+ <Link
+ to="/songs/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} />
+ Learning Guide
+ </Link>
+ </div>
+ <p className="text-sm text-gray-400 mb-6">
+ Write and learn a cappella songs — dirges, ballads, and harmonies. Track lyrics,
+ rhythm shapes, and the voice layers you're stacking.
+ </p>
+
+ {/* Create form */}
+ <form
+ onSubmit={(e) => { e.preventDefault(); create(); }}
+ 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>
+ <input
+ id="song-title"
+ type="text"
+ value={title}
+ onChange={(e) => setTitle(e.target.value)}
+ placeholder="e.g. 500 Miles"
+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:border-port-accent focus:outline-none"
+ />
+ </div>
+ <div className="flex-1">
+ <label htmlFor="song-artist" className="block text-xs text-gray-400 mb-1">Artist (optional)</label>
+ <input
+ id="song-artist"
+ type="text"
+ value={artist}
+ onChange={(e) => setArtist(e.target.value)}
+ placeholder="e.g. Peter, Paul and Mary"
+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:border-port-accent focus:outline-none"
+ />
+ </div>
+ <button
+ type="submit"
+ disabled={creating}
+ 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
+ </button>
+ </form>
+
+ {/* 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>
+ ) : (
+ <ul className="space-y-2">
+ {songs.map((song) => {
+ const shape = shapeLabel(song.rhythmShapeId);
+ const layerCount = song.layers?.length || 0;
+ return (
+ <li
+ key={song.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">
+ <div className="flex items-center gap-2 min-w-0">
+ {song.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="text-white font-medium truncate">{song.title}</span>
+ {song.artist && <span className="text-gray-500 text-sm truncate">· {song.artist}</span>}
+ </div>
+ <div className="flex flex-wrap gap-x-3 gap-y-0.5 text-xs text-gray-500 mt-1 pl-6">
+ {song.key && <span>Key: {song.key}</span>}
+ {song.tempo && <span>{song.tempo} BPM</span>}
+ {shape && <span>{shape}</span>}
+ {layerCount > 0 && <span>{layerCount} layer{layerCount === 1 ? '' : 's'}</span>}
+ {song.updatedAt && <span>Edited {timeAgo(song.updatedAt)}</span>}
+ </div>
+ </Link>
+ <button
+ type="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'}
+ >
+ <Trash2 size={16} />
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/pages/SongsGuide.jsx b/client/src/pages/SongsGuide.jsx
new file mode 100644
index 0000000000..9f2de8fc8d
--- /dev/null
+++ b/client/src/pages/SongsGuide.jsx
@@ -0,0 +1,165 @@
+/**
+ * Songs Guide — deep-linkable learning reference at /songs/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
+ * its own vertical scroll — mirrors WritersRoomGuide.
+ */
+
+import { Link } from 'react-router-dom';
+import { Music, ArrowLeft, Drum, Layers, GraduationCap, FileMusic } from 'lucide-react';
+import Pill from '../components/ui/Pill';
+import {
+ RHYTHM_SHAPES,
+ VOICE_LAYERS,
+ LEARNING_STEPS,
+ NOTATION_HELP,
+} from '../lib/songCraft';
+
+function RhythmCard({ shape }) {
+ return (
+ <div className="bg-port-card border border-port-border rounded-lg p-4 flex flex-col gap-2">
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-sm font-semibold text-white">{shape.label}</span>
+ {shape.dirge && <Pill tone="accent" size="xs">dirge</Pill>}
+ </div>
+ <div className="flex flex-wrap gap-1.5">
+ <Pill tone="muted">{shape.bpm.label}</Pill>
+ <Pill tone="note">{shape.count}</Pill>
+ </div>
+ <p className="text-xs text-gray-300 leading-relaxed">{shape.feel}</p>
+ <p className="text-xs text-gray-500 leading-relaxed">{shape.note}</p>
+ </div>
+ );
+}
+
+function LayerCard({ layer }) {
+ return (
+ <div className="bg-port-card border border-port-border rounded-lg p-4">
+ <div className="flex items-center gap-2 mb-1">
+ <span className="flex items-center justify-center w-5 h-5 rounded-full bg-port-accent/15 text-port-accent text-[11px] font-bold shrink-0">
+ {layer.order}
+ </span>
+ <span className="text-sm font-semibold text-white">{layer.label}</span>
+ <Pill tone="muted" size="xs">{layer.voices}</Pill>
+ </div>
+ <p className="text-xs text-gray-300 leading-relaxed mb-1">{layer.role}</p>
+ <p className="text-xs text-gray-500 leading-relaxed">{layer.advice}</p>
+ </div>
+ );
+}
+
+function SectionHeading({ icon: Icon, title, subtitle }) {
+ return (
+ <div className="mb-3">
+ <h2 className="flex items-center gap-2 text-lg font-semibold text-white">
+ <Icon size={18} className="text-port-accent" />
+ {title}
+ </h2>
+ {subtitle && <p className="text-xs text-gray-500 mt-0.5">{subtitle}</p>}
+ </div>
+ );
+}
+
+export default function SongsGuide() {
+ 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"
+ className="p-1 text-gray-400 hover:text-white transition-colors"
+ title="Back to Songs"
+ aria-label="Back to Songs"
+ >
+ <ArrowLeft size={18} />
+ </Link>
+ <Music size={18} className="text-port-accent shrink-0" />
+ <span className="text-white font-semibold">Songs · Learning Guide</span>
+ </div>
+
+ <div className="flex-1 overflow-y-auto p-4 md:p-6">
+ <div className="max-w-4xl mx-auto space-y-10">
+ <p className="text-sm text-gray-400 leading-relaxed">
+ How to write and learn a cappella songs — the slow lament family (dirges and
+ ballads like <span className="text-gray-200">"500 Miles"</span>), how to stack
+ harmony layers, the practice sequence, and a plain-language notation primer.
+ </p>
+
+ {/* Rhythm shapes */}
+ <section>
+ <SectionHeading
+ icon={Drum}
+ title="Rhythm shapes"
+ subtitle="The felt pulse a song leans on. Dirges — slow, solemn laments — lead the list, since that's the workbench's home turf."
+ />
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ {RHYTHM_SHAPES.map((s) => <RhythmCard key={s.id} shape={s} />)}
+ </div>
+ </section>
+
+ {/* Layer ladder */}
+ <section>
+ <SectionHeading
+ icon={Layers}
+ title="Building layers (foundation-first)"
+ subtitle="Stack voices in this order. Each layer needs the one below it locked and in tune before it can sit right."
+ />
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ {VOICE_LAYERS.map((l) => <LayerCard key={l.id} layer={l} />)}
+ </div>
+ </section>
+
+ {/* Learning sequence */}
+ <section>
+ <SectionHeading
+ icon={GraduationCap}
+ title="How to learn a new song"
+ subtitle="A practice sequence — listen and own the melody before you ever touch a harmony."
+ />
+ <ol className="space-y-2">
+ {LEARNING_STEPS.map((step, i) => (
+ <li key={step.id} className="bg-port-card border border-port-border rounded-lg p-3 flex gap-3">
+ <span className="flex items-center justify-center w-6 h-6 rounded-full bg-port-accent/15 text-port-accent text-xs font-bold shrink-0">
+ {i + 1}
+ </span>
+ <div>
+ <span className="text-sm font-semibold text-white">{step.label}</span>
+ <p className="text-xs text-gray-400 leading-relaxed mt-0.5">{step.detail}</p>
+ </div>
+ </li>
+ ))}
+ </ol>
+ </section>
+
+ {/* Notation help */}
+ <section>
+ <SectionHeading
+ icon={FileMusic}
+ title="Reading musical notation"
+ subtitle="A plain-language primer for lead sheets, time signatures, note values, and dynamics."
+ />
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ {NOTATION_HELP.map((g) => (
+ <div key={g.id} className="bg-port-card border border-port-border rounded-lg p-4">
+ <h3 className="text-sm font-semibold text-white">{g.title}</h3>
+ <p className="text-xs text-gray-500 mb-2">{g.summary}</p>
+ <ul className="space-y-1.5">
+ {g.points.map((point, i) => (
+ <li key={i} className="flex gap-2 text-xs text-gray-300 leading-relaxed">
+ <span className="text-port-accent shrink-0">›</span>
+ <span>{point}</span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ ))}
+ </div>
+ </section>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/services/README.md b/client/src/services/README.md
index afa86c6aaf..57f4b505b9 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -87,6 +87,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiUniverseBuilder.js` | Universe Builder (generate + edit + commit). |
| `apiWritersRoom.js` | Writers Room (folders + works + drafts, live continuation + render-preview reservation, scene-image attach). |
| `apiSharing.js` | Share buckets + federation sync. |
+| `apiSongs.js` | Songs workbench CRUD (a cappella song writing + arranging voice layers + learning tracking). |
| `apiPeerSync.js` | Per-record peer sync subscriptions (universe + series → other PortOS instances over Tailnet). |
| `apiSyncReview.js` | Sync hygiene: duplicate-record detection + smart merge (universe/series) and the non-blocking edit-conflict journal (list/resolve). Surfaced in Sharing → Duplicates / Conflicts. |
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 79c4efd5ea..b826856fb9 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -46,6 +46,7 @@ export * from './apiWritersRoom.js';
export * from './apiUniverseBuilder.js';
export * from './apiPipeline.js';
export * from './apiSharing.js';
+export * from './apiSongs.js';
export * from './apiPeerSync.js';
export * from './apiSyncReview.js';
export * from './apiCreativeDirector.js';
diff --git a/client/src/services/apiSongs.js b/client/src/services/apiSongs.js
new file mode 100644
index 0000000000..f416da6658
--- /dev/null
+++ b/client/src/services/apiSongs.js
@@ -0,0 +1,21 @@
+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 });
diff --git a/server/index.js b/server/index.js
index 88e3adf3c0..cabb870c9f 100644
--- a/server/index.js
+++ b/server/index.js
@@ -118,6 +118,7 @@ import lorasRoutes from './routes/loras.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 peerSyncRoutes from './routes/peerSync.js';
import { initSharing } from './services/sharing/index.js';
import askRoutes from './routes/ask.js';
@@ -509,6 +510,7 @@ app.use('/api/loras', lorasRoutes);
app.use('/sdapi/v1', sdapiRoutes);
app.use('/api/openclaw', openclawRoutes);
app.use('/api/sharing', sharingRoutes);
+app.use('/api/songs', songsRoutes);
app.use('/api/peer-sync', peerSyncRoutes);
app.use('/api/ask', askRoutes);
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index f21b470c86..438eacc339 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -26,6 +26,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.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.settings', path: '/media/image?settings=1', label: 'Media Gen Settings', section: 'Create', aliases: ['media-settings', 'image-gen-settings', 'sd-settings', 'video-gen-settings'] },
diff --git a/server/routes/songs.js b/server/routes/songs.js
new file mode 100644
index 0000000000..67e79ba579
--- /dev/null
+++ b/server/routes/songs.js
@@ -0,0 +1,90 @@
+/**
+ * Songs 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 }
+ *
+ * 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
+ * here and the service-layer sanitizer agree by construction (the dashboard-
+ * layouts pattern).
+ */
+
+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';
+
+const router = Router();
+
+// Trim then cap, allowing empty (the client clears a field by sending '').
+const str = (max) => z.string().trim().max(max);
+
+const sectionSchema = z.object({
+ id: str(svc.ID_MAX_LENGTH).optional(),
+ label: str(svc.LABEL_MAX_LENGTH).optional().default(''),
+ lyrics: str(svc.FIELD_MAX_LENGTH).optional().default(''),
+});
+
+const layerSchema = z.object({
+ id: str(svc.ID_MAX_LENGTH).optional(),
+ label: str(svc.LABEL_MAX_LENGTH).optional().default(''),
+ part: str(svc.PART_MAX_LENGTH).optional().default(''),
+ notes: str(svc.FIELD_MAX_LENGTH).optional().default(''),
+});
+
+const songInputSchema = z.object({
+ title: str(svc.TITLE_MAX_LENGTH).optional().default(''),
+ artist: str(svc.ARTIST_MAX_LENGTH).optional().default(''),
+ key: str(svc.KEY_MAX_LENGTH).optional().default(''),
+ // null clears the tempo; a number is clamped server-side into the band.
+ tempo: z.number().int().min(svc.TEMPO_MIN).max(svc.TEMPO_MAX).nullable().optional(),
+ rhythmShapeId: str(svc.ID_MAX_LENGTH).optional().default(''),
+ notation: str(svc.FIELD_MAX_LENGTH).optional().default(''),
+ notes: str(svc.FIELD_MAX_LENGTH).optional().default(''),
+ learned: z.boolean().optional(),
+ sections: z.array(sectionSchema).max(svc.SECTIONS_MAX).optional(),
+ layers: z.array(layerSchema).max(svc.LAYERS_MAX).optional(),
+});
+
+// Map a service error (carries a `code`) to the right HTTP status. Without
+// this, asyncHandler defaults everything to 500.
+const mapSongError = (err) => {
+ if (err?.code === svc.ERR_NOT_FOUND) return new ServerError(err.message, { status: 404, code: err.code });
+ return err;
+};
+const rethrowSongError = (err) => { throw mapSongError(err); };
+
+router.get('/', asyncHandler(async (req, res) => {
+ const songs = await svc.listSongs();
+ res.json({ songs });
+}));
+
+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 });
+}));
+
+router.post('/', asyncHandler(async (req, res) => {
+ const input = validateRequest(songInputSchema, req.body || {});
+ const song = await svc.createSong(input).catch(rethrowSongError);
+ res.json({ song });
+}));
+
+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 });
+}));
+
+router.delete('/:id', asyncHandler(async (req, res) => {
+ const result = await svc.deleteSong(req.params.id).catch(rethrowSongError);
+ res.json(result);
+}));
+
+export default router;
diff --git a/server/services/songs.js b/server/services/songs.js
new file mode 100644
index 0000000000..e1ff3108a9
--- /dev/null
+++ b/server/services/songs.js
@@ -0,0 +1,211 @@
+/**
+ * Songs 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
+ * the voice layers (lead / bass / harmony / drone / counter-melody) the user is
+ * stacking — plus per-layer learning notes. Persisted to data/songs.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
+ * 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)
+ * so a client on a newer/older songCraft revision can't 400.
+ */
+
+import { join } from 'path';
+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');
+
+// Service errors carry a `code` field so routes map to HTTP status without
+// string-matching on err.message (which breaks on rename).
+export const ERR_NOT_FOUND = 'NOT_FOUND';
+const makeErr = (message, code) => Object.assign(new Error(message), { code });
+
+// --- Shape bounds (shared with routes/songs.js#songInputSchema) -------------
+export const TITLE_MAX_LENGTH = 200;
+export const ARTIST_MAX_LENGTH = 200;
+export const KEY_MAX_LENGTH = 24;
+export const FIELD_MAX_LENGTH = 4000; // lyrics body / general notes
+export const LABEL_MAX_LENGTH = 120; // section + layer labels
+export const PART_MAX_LENGTH = 60; // layer voice (e.g. "Bass")
+export const ID_MAX_LENGTH = 60; // rhythm-shape / layer ids
+export const TEMPO_MIN = 20;
+export const TEMPO_MAX = 320;
+export const SECTIONS_MAX = 60;
+export const LAYERS_MAX = 24;
+
+// Trim a string field, returning '' for non-strings. Mirrors the
+// absent-vs-empty rule in CLAUDE.md: callers decide whether '' clears.
+const trimField = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
+
+// Clamp an integer tempo into the supported band; null when unparseable so a
+// song without a tempo stays distinct from one pinned to a bound.
+const sanitizeTempo = (v) => {
+ if (typeof v !== 'number' || !Number.isFinite(v)) return null;
+ return Math.max(TEMPO_MIN, Math.min(TEMPO_MAX, Math.round(v)));
+};
+
+// One lyric/structure section ({ id, label, lyrics }). Label defaults from the
+// id when blank so a section card is never headerless. Drops shapeless entries.
+const sanitizeSection = (s) => {
+ if (!s || typeof s !== 'object') return null;
+ const label = trimField(s.label, LABEL_MAX_LENGTH);
+ const lyrics = trimField(s.lyrics, FIELD_MAX_LENGTH);
+ if (!label && !lyrics) return null;
+ return {
+ id: trimField(s.id, ID_MAX_LENGTH) || `sec-${randomUUID().slice(0, 8)}`,
+ label: label || 'Section',
+ lyrics,
+ };
+};
+
+// One voice layer the user is arranging ({ id, label, part, notes }). `id`
+// references a songCraft VOICE_LAYERS entry when known but is free-text-safe.
+const sanitizeLayer = (l) => {
+ if (!l || typeof l !== 'object') return null;
+ const label = trimField(l.label, LABEL_MAX_LENGTH);
+ const part = trimField(l.part, PART_MAX_LENGTH);
+ const notes = trimField(l.notes, FIELD_MAX_LENGTH);
+ if (!label && !part && !notes) return null;
+ return {
+ id: trimField(l.id, ID_MAX_LENGTH) || `layer-${randomUUID().slice(0, 8)}`,
+ label: label || 'Layer',
+ part,
+ notes,
+ };
+};
+
+const sanitizeList = (arr, fn, max) =>
+ (Array.isArray(arr) ? arr : [])
+ .map(fn)
+ .filter(Boolean)
+ .slice(0, max);
+
+// Project a stored or inbound record onto the canonical song shape. Used on
+// read (defends hand-edited JSON) and on write (normalizes the input).
+export const sanitizeSong = (raw) => {
+ if (!raw || typeof raw !== 'object') return null;
+ const id = trimField(raw.id, ID_MAX_LENGTH);
+ if (!id) return null;
+ return {
+ id,
+ title: trimField(raw.title, TITLE_MAX_LENGTH) || 'Untitled song',
+ artist: trimField(raw.artist, ARTIST_MAX_LENGTH),
+ key: trimField(raw.key, KEY_MAX_LENGTH),
+ tempo: sanitizeTempo(raw.tempo),
+ rhythmShapeId: trimField(raw.rhythmShapeId, ID_MAX_LENGTH),
+ notation: trimField(raw.notation, FIELD_MAX_LENGTH),
+ notes: trimField(raw.notes, FIELD_MAX_LENGTH),
+ learned: raw.learned === true,
+ sections: sanitizeList(raw.sections, sanitizeSection, SECTIONS_MAX),
+ layers: sanitizeList(raw.layers, sanitizeLayer, LAYERS_MAX),
+ createdAt: typeof raw.createdAt === 'string' ? raw.createdAt : new Date().toISOString(),
+ updatedAt: typeof raw.updatedAt === 'string' ? raw.updatedAt : new Date().toISOString(),
+ };
+};
+
+// 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 = [
+ {
+ id: 'seed-500-miles',
+ title: '500 Miles',
+ artist: 'Peter, Paul and Mary',
+ key: 'C major',
+ tempo: 68,
+ rhythmShapeId: 'slow-4-4',
+ notation: 'Verse chords (key of C): C — Am — F — G, four slow bars per line. A gentle 4/4 ballad; let each line breathe across the bar rather than chopping it.',
+ notes: 'A travelling lament — keep it spacious and mournful. Sustain the vowels on the downbeats. Works beautifully with a soft hummed drone under the verses.',
+ learned: false,
+ sections: [
+ { id: 'sec-verse-1', label: 'Verse 1', lyrics: 'If you miss the train I\'m on, you will know that I am gone\nYou can hear the whistle blow a hundred miles' },
+ { id: 'sec-chorus', label: 'Chorus', lyrics: 'A hundred miles, a hundred miles, a hundred miles, a hundred miles\nYou can hear the whistle blow a hundred miles' },
+ ],
+ layers: [
+ { id: 'lead', label: 'Lead melody', part: 'Soprano / Tenor', notes: 'The tune everyone knows. Lock this first, in tune, before stacking anything.' },
+ { id: 'bass', label: 'Bass / root', part: 'Bass', notes: 'Root of each chord — C, A, F, G. Move slowly; you are the floor.' },
+ { id: 'harmony-3rd', label: 'Harmony (third)', part: 'Alto', notes: 'A third under the melody. The first colour — keep it close and warm.' },
+ { id: 'drone', label: 'Drone / pedal', part: 'Bass / Alto', notes: 'Optional held tonic (C) under the verse to make the lament feel ancient.' },
+ ],
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ },
+];
+
+// 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
+// persisted state instead of racing on a stale snapshot. Single-user, so this
+// is re-entrancy hygiene, not a multi-actor lock (see CLAUDE.md Security Model).
+const enqueue = createFileWriteQueue();
+
+// Read + sanitize every song. Seeds on first read (file absent) and persists
+// the seed so subsequent reads are stable and the user can edit the example.
+export async function listSongs() {
+ const state = await readJSONFile(STATE_PATH, null, { allowArray: false });
+ if (!state || !Array.isArray(state.songs)) {
+ const seeded = SEED_SONGS.map(sanitizeSong).filter(Boolean);
+ await atomicWrite(STATE_PATH, { songs: seeded });
+ return seeded;
+ }
+ return state.songs.map(sanitizeSong).filter(Boolean);
+}
+
+export async function getSong(id) {
+ const songs = await listSongs();
+ return songs.find((s) => s.id === id) || null;
+}
+
+export async function createSong(input) {
+ return enqueue(async () => {
+ const songs = await listSongs();
+ const now = new Date().toISOString();
+ const song = sanitizeSong({ ...input, id: `song-${randomUUID()}`, createdAt: now, updatedAt: now });
+ songs.unshift(song);
+ await atomicWrite(STATE_PATH, { songs });
+ console.log(`🎵 Created song "${song.title}" (${song.id})`);
+ return song;
+ });
+}
+
+export async function updateSong(id, patch) {
+ return enqueue(async () => {
+ const songs = await listSongs();
+ 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', 'notes', 'learned', 'sections', 'layers']) {
+ 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);
+ songs[idx] = song;
+ await atomicWrite(STATE_PATH, { songs });
+ console.log(`🎵 Updated song "${song.title}" (${id})`);
+ return song;
+ });
+}
+
+export async function deleteSong(id) {
+ return enqueue(async () => {
+ const songs = await listSongs();
+ 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 });
+ console.log(`🗑️ Deleted song "${removed.title}" (${id})`);
+ return { id };
+ });
+}
diff --git a/server/services/songs.test.js b/server/services/songs.test.js
new file mode 100644
index 0000000000..d37dcf44e5
--- /dev/null
+++ b/server/services/songs.test.js
@@ -0,0 +1,101 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { existsSync, unlinkSync } from 'fs';
+import { join } from 'path';
+
+// The service captures STATE_PATH at module-load time, so the scratch dir must
+// exist before the import resolves. vi.hoisted runs before imports.
+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-'));
+ mkdirSync(j(dir, 'data'), { recursive: true });
+ return { dir };
+});
+vi.mock('../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../lib/fileUtils.js');
+ return {
+ ...actual,
+ PATHS: { ...actual.PATHS, data: join(scratch.dir, 'data') },
+ };
+});
+
+import * as svc from './songs.js';
+
+const STATE_FILE = join(scratch.dir, 'data', 'songs.json');
+
+describe('songs service', () => {
+ beforeEach(() => {
+ if (existsSync(STATE_FILE)) unlinkSync(STATE_FILE);
+ });
+
+ it('seeds the 500 Miles example on first read and persists it', async () => {
+ const songs = await svc.listSongs();
+ expect(songs.length).toBeGreaterThan(0);
+ const seed = songs.find((s) => s.title === '500 Miles');
+ expect(seed).toBeTruthy();
+ expect(seed.artist).toBe('Peter, Paul and Mary');
+ 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();
+ expect(again.find((s) => s.title === '500 Miles')).toBeTruthy();
+ });
+
+ 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-/);
+ expect(song.title).toBe('Wayfaring Stranger');
+ expect(song.tempo).toBe(60);
+ const songs = await svc.listSongs();
+ expect(songs[0].id).toBe(song.id); // unshifted to front
+ });
+
+ it('clamps tempo into the supported band and nulls unparseable values', async () => {
+ const fast = await svc.createSong({ title: 'Too fast', tempo: 9000 });
+ expect(fast.tempo).toBe(svc.TEMPO_MAX);
+ const noTempo = await svc.createSong({ title: 'No tempo' });
+ expect(noTempo.tempo).toBeNull();
+ });
+
+ it('drops empty sections/layers and labels the survivors', async () => {
+ const song = await svc.createSong({
+ title: 'Layered',
+ sections: [{ label: '', lyrics: '' }, { label: 'Verse', lyrics: 'la la' }],
+ layers: [{ label: '', part: '', notes: '' }, { part: 'Bass', notes: 'root' }],
+ });
+ expect(song.sections).toHaveLength(1);
+ expect(song.sections[0].label).toBe('Verse');
+ expect(song.layers).toHaveLength(1);
+ expect(song.layers[0].label).toBe('Layer'); // defaulted when blank but kept (has part/notes)
+ });
+
+ 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: '' });
+ expect(patched.title).toBe('Renamed');
+ expect(patched.artist).toBe('Someone'); // untouched key preserved
+ expect(patched.key).toBe(''); // empty string clears
+ expect(patched.createdAt).toBe(song.createdAt); // createdAt is immutable across updates
+ });
+
+ 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 });
+ });
+
+ it('deletes a song by id', async () => {
+ const song = await svc.createSong({ title: 'Delete me' });
+ const result = await svc.deleteSong(song.id);
+ expect(result.id).toBe(song.id);
+ const songs = await svc.listSongs();
+ 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');
+ });
+});