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
feat(songs): AI generate/expand/evaluate + vocal recording & layered playback
Adam Eivy4233452f6c7c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 592b73c5ed..37a28839dc 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -3,6 +3,8 @@## 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.+- **Songs: AI generate, expand & evaluate** — like the manuscript and universe/series creators, the Songs workbench now drafts and critiques arrangements with AI. From the Songs list, **Generate** drafts a full arrangement (lyrics, voice layers, key/tempo/rhythm shape, notation, and learning notes) from the title/artist as a brief; inside the editor, **Generate draft** and **Expand current** rewrite or build on the open draft, and **Evaluate** scores the arrangement 0–100 for performance-readiness with concrete strengths, weaknesses, and suggestions. The model returns rhythm-shape and voice-layer ids the editor's pickers already understand. Generated drafts land in the editor for review and are never auto-saved.+- **Songs: record & layer your own vocals** — record each part straight from the mic in the song editor (saved as a vocal take), assign takes to voice layers, then **Play layered** to start every unmuted take together — sample-aligned on one audio clock — so you can stack a lead, bass, and harmony and rehearse a cappella against yourself. Mute/solo individual takes, scrub each one with its own player, and the takes persist with the song.- **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/components/songs/SongAiPanel.jsx b/client/src/components/songs/SongAiPanel.jsxnew file mode 100644index 0000000000..9fe9112681--- /dev/null+++ b/client/src/components/songs/SongAiPanel.jsx@@ -0,0 +1,132 @@+/**+ * SongAiPanel — AI generate/expand + evaluate for the Song editor.+ *+ * Two single-shot actions (the synchronous universe-builder pattern, not+ * streaming):+ * - Generate / Expand → POST /api/songs/: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 /+ * weaknesses / suggestions verdict inline (read-only, no mutation).+ *+ * Provider/model default to the active provider server-side; no picker here+ * (matches the manuscript/universe one-button generate UX the user asked for).+ */++import { useState } from 'react';+import { Sparkles, Wand2, ClipboardCheck, Loader2 } from 'lucide-react';+import toast from '../ui/Toast';+import { generateSongFor, evaluateSong } from '../../services/api';++const scoreColor = (n) => {+ if (n == null) return 'text-gray-400';+ if (n >= 80) return 'text-port-success';+ if (n >= 55) return 'text-port-warning';+ return 'text-port-error';+};++export default function SongAiPanel({ songId, onApplyGenerated }) {+ const [brief, setBrief] = useState('');+ const [mood, setMood] = useState('');+ const [busy, setBusy] = useState(null); // 'generate' | 'expand' | 'evaluate' | null+ const [verdict, setVerdict] = useState(null);++ const runGenerate = async (expandExisting) => {+ setBusy(expandExisting ? 'expand' : 'generate');+ const data = await generateSongFor(+ songId,+ { brief: brief.trim(), mood: mood.trim(), expandExisting },+ { silent: true },+ ).catch((err) => { toast.error(err?.message || 'Generation failed'); return null; });+ setBusy(null);+ if (!data?.song) return;+ // The server already folded the prior draft in when expandExisting was set,+ // so the parent just applies the returned fields either way.+ onApplyGenerated(data.song);+ toast.success(expandExisting ? 'Draft expanded — review and Save' : 'Draft generated — review and Save');+ };++ const runEvaluate = async () => {+ setBusy('evaluate');+ const data = await evaluateSong(songId, {}, { silent: true })+ .catch((err) => { toast.error(err?.message || 'Evaluation failed'); return null; });+ setBusy(null);+ if (data?.evaluation) setVerdict(data.evaluation);+ };++ const anyBusy = busy !== null;+ 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 (+ <section className="bg-port-card border border-port-border rounded-lg p-4 space-y-4">+ <h2 className="flex items-center gap-2 text-sm font-semibold text-white">+ <Sparkles size={15} className="text-port-accent" /> AI assist+ </h2>++ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <div>+ <label htmlFor="ai-brief" className={labelCls}>Brief (optional)</label>+ <input id="ai-brief" type="text" value={brief} onChange={(e) => setBrief(e.target.value)} placeholder="e.g. a travelling lament about leaving home" className={inputCls} />+ </div>+ <div>+ <label htmlFor="ai-mood" className={labelCls}>Mood / feel (optional)</label>+ <input id="ai-mood" type="text" value={mood} onChange={(e) => setMood(e.target.value)} placeholder="e.g. mournful, spacious, hymn-like" className={inputCls} />+ </div>+ </div>++ <div className="flex flex-wrap gap-2">+ <button type="button" onClick={() => runGenerate(false)} disabled={anyBusy} 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">+ {busy === 'generate' ? <Loader2 size={14} className="animate-spin" /> : <Wand2 size={14} />}+ Generate draft+ </button>+ <button type="button" onClick={() => runGenerate(true)} disabled={anyBusy} className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50 disabled:opacity-50">+ {busy === 'expand' ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}+ Expand current+ </button>+ <button type="button" onClick={runEvaluate} disabled={anyBusy} className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50 disabled:opacity-50">+ {busy === 'evaluate' ? <Loader2 size={14} className="animate-spin" /> : <ClipboardCheck size={14} />}+ Evaluate+ </button>+ </div>+ <p className="text-xs text-gray-500">+ Generate writes a full draft into the editor; Expand builds on what you have. Both replace the+ draft below — review and <strong>Save</strong> to keep. Evaluation is read-only.+ </p>++ {verdict && (+ <div className="border-t border-port-border pt-3 space-y-3">+ <div className="flex items-baseline gap-2">+ <span className={`text-2xl font-bold ${scoreColor(verdict.score)}`}>{verdict.score ?? '—'}</span>+ <span className="text-xs text-gray-500">/ 100 performance-ready</span>+ </div>+ {verdict.summary && <p className="text-sm text-gray-300">{verdict.summary}</p>}+ {verdict.strengths?.length > 0 && (+ <div>+ <h3 className="text-xs font-semibold text-port-success mb-1">Strengths</h3>+ <ul className="list-disc list-inside text-xs text-gray-300 space-y-0.5">+ {verdict.strengths.map((s, i) => <li key={i}>{s}</li>)}+ </ul>+ </div>+ )}+ {verdict.weaknesses?.length > 0 && (+ <div>+ <h3 className="text-xs font-semibold text-port-warning mb-1">Weaknesses</h3>+ <ul className="list-disc list-inside text-xs text-gray-300 space-y-0.5">+ {verdict.weaknesses.map((s, i) => <li key={i}>{s}</li>)}+ </ul>+ </div>+ )}+ {verdict.suggestions?.length > 0 && (+ <div>+ <h3 className="text-xs font-semibold text-port-accent mb-1">Suggestions</h3>+ <ul className="list-disc list-inside text-xs text-gray-300 space-y-0.5">+ {verdict.suggestions.map((s, i) => <li key={i}>{s}</li>)}+ </ul>+ </div>+ )}+ </div>+ )}+ </section>+ );+}diff --git a/client/src/components/songs/SongRecordings.jsx b/client/src/components/songs/SongRecordings.jsxnew file mode 100644index 0000000000..100c4fcb5a--- /dev/null+++ b/client/src/components/songs/SongRecordings.jsx@@ -0,0 +1,237 @@+/**+ * SongRecordings — record, save, and layer-play vocal takes for one song.+ *+ * Records mic audio via the shared audioRecorder (→ 16 kHz mono WAV base64),+ * uploads it through /api/uploads, and stores the returned filename on the song+ * as a `recordings[]` entry (persisted by the parent's Save). Multiple takes+ * play back simultaneously through createLayeredPlayer so the user can stack a+ * lead + bass + harmony and rehearse against themselves.+ *+ * Stateless about persistence: it calls up to the parent via `onChange` with the+ * next recordings array (optimistic), and the parent owns the PUT. A freshly+ * recorded take is uploaded immediately (so the file exists) but only saved to+ * the song on the parent's Save — matching the editor's explicit-save model.+ */++import { useEffect, useRef, useState, useCallback, useMemo } from 'react';+import { Mic, Square, Play, Trash2, Volume2, VolumeX, Loader2 } from 'lucide-react';+import toast from '../ui/Toast';+import { startMemoRecording } from '../../lib/audioRecorder';+import { createLayeredPlayer } from '../../lib/songPlayback';+import { uploadFile, getUploadUrl } from '../../services/api';+import { formatDurationMs } from '../../utils/formatters';++// Lower bound peak amplitude — below this the take is effectively silence+// (dead mic / muted input), worth warning about before it joins the stack.+const SILENCE_PEAK = 0.01;++// In-session temp id for a take not yet persisted. MUST end in `-new-<n>` so the+// editor's stripTempId (/-new-\d+$/) blanks it on save and the server assigns a+// stable `rec-<uuid>` — otherwise a reload could re-mint the same temp id and+// collide. Counter-based; uniqueness only needs to hold within the session.+let tempSeq = 0;+const tempRecordingId = () => `rec-new-${tempSeq++}`;++export default function SongRecordings({ recordings = [], layers = [], onChange }) {+ const [recording, setRecording] = useState(false);+ const [saving, setSaving] = useState(false);+ const [playing, setPlaying] = useState(false);+ const [targetLayerId, setTargetLayerId] = useState('');+ const handleRef = useRef(null); // active MediaRecorder handle+ const playerRef = useRef(null); // active layered player++ // Tear down any live player/recorder on unmount so a navigation-away can't+ // leave the mic open or audio playing into the void.+ useEffect(() => () => {+ if (playerRef.current) playerRef.current.stop();+ if (handleRef.current) handleRef.current.cancel();+ }, []);++ const layerLabel = useCallback((layerId) => {+ if (!layerId) return '';+ return layers.find((l) => l.id === layerId)?.label || layerId;+ }, [layers]);++ const startRecording = useCallback(async () => {+ if (playerRef.current) { playerRef.current.stop(); setPlaying(false); }+ const handle = await startMemoRecording().catch((err) => {+ toast.error(err?.message || 'Microphone access denied');+ return null;+ });+ if (!handle) return;+ handleRef.current = handle;+ setRecording(true);+ }, []);++ const stopRecording = useCallback(async () => {+ const handle = handleRef.current;+ if (!handle) return;+ handleRef.current = null;+ setRecording(false);+ setSaving(true);+ const take = await handle.stop().catch((err) => {+ toast.error(err?.message || 'Recording failed');+ return null;+ });+ if (!take) { setSaving(false); return; }+ if (take.peak < SILENCE_PEAK) {+ toast.error('That take was silent — check your microphone and try again.');+ setSaving(false);+ return;+ }+ // Upload the WAV; the returned filename is what we persist + play from.+ const ts = new Date().toISOString().replace(/[:.]/g, '-');+ const result = await uploadFile(take.audioBase64, `vocal-${ts}.wav`).catch((err) => {+ toast.error(err?.message || 'Failed to save recording');+ return null;+ });+ setSaving(false);+ if (!result?.filename) return;++ const next = [+ ...recordings,+ {+ id: tempRecordingId(),+ layerId: targetLayerId,+ label: targetLayerId ? layerLabel(targetLayerId) : 'Take',+ filename: result.filename,+ durationMs: take.durationMs || 0,+ peak: take.peak || 0,+ muted: false,+ },+ ];+ onChange(next);+ toast.success('Take recorded — Save the song to keep it');+ }, [recordings, targetLayerId, layerLabel, onChange]);++ const removeRecording = useCallback((id) => {+ onChange(recordings.filter((r) => r.id !== id));+ }, [recordings, onChange]);++ const toggleMute = useCallback((id) => {+ onChange(recordings.map((r) => (r.id === id ? { ...r, muted: !r.muted } : r)));+ }, [recordings, onChange]);++ const assignLayer = useCallback((id, layerId) => {+ onChange(recordings.map((r) => (r.id === id+ ? { ...r, layerId, label: layerId ? layerLabel(layerId) : (r.label || 'Take') }+ : r)));+ }, [recordings, layerLabel, onChange]);++ const playAll = useCallback(async () => {+ if (playerRef.current) playerRef.current.stop();+ const takes = recordings.map((r) => ({ id: r.id, url: getUploadUrl(r.filename), muted: r.muted }));+ if (takes.every((t) => t.muted)) { toast.error('All takes are muted'); return; }+ const player = createLayeredPlayer(takes);+ player.onEnded(() => setPlaying(false));+ playerRef.current = player;+ setPlaying(true);+ await player.play().catch((err) => {+ toast.error(err?.message || 'Playback failed');+ setPlaying(false);+ });+ }, [recordings]);++ const stopPlay = useCallback(() => {+ if (playerRef.current) playerRef.current.stop();+ setPlaying(false);+ }, []);++ const audibleCount = useMemo(() => recordings.filter((r) => !r.muted).length, [recordings]);++ return (+ <section>+ <div className="flex items-center justify-between mb-2 gap-2 flex-wrap">+ <h2 className="flex items-center gap-2 text-sm font-semibold text-white">+ <Mic size={15} className="text-port-accent" /> Vocal takes+ </h2>+ <div className="flex items-center gap-2">+ {recordings.length > 0 && (+ playing ? (+ <button type="button" onClick={stopPlay} 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">+ <Square size={14} /> Stop+ </button>+ ) : (+ <button type="button" onClick={playAll} 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" title="Play all unmuted takes together">+ <Play size={14} /> Play layered ({audibleCount})+ </button>+ )+ )}+ {recording ? (+ <button type="button" onClick={stopRecording} className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg bg-port-error text-white hover:bg-port-error/90 animate-pulse">+ <Square size={14} /> Stop & save+ </button>+ ) : (+ <button type="button" onClick={startRecording} 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">+ {saving ? <Loader2 size={14} className="animate-spin" /> : <Mic size={14} />}+ {saving ? 'Saving…' : 'Record take'}+ </button>+ )}+ </div>+ </div>++ <p className="text-xs text-gray-500 mb-2">+ Record each part, then “Play layered” to stack them — sing along to build harmony against yourself.+ {recording && <span className="text-port-error"> ● Recording… sing now.</span>}+ </p>++ {/* Layer the next take targets (optional) */}+ {layers.length > 0 && !recording && (+ <div className="mb-3">+ <label htmlFor="rec-target-layer" className="block text-xs text-gray-400 mb-1">Next take is for layer</label>+ <select+ id="rec-target-layer"+ value={targetLayerId}+ onChange={(e) => setTargetLayerId(e.target.value)}+ className="w-full sm:w-64 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"+ >+ <option value="">— Unassigned —</option>+ {layers.map((l) => <option key={l.id} value={l.id}>{l.label}</option>)}+ </select>+ </div>+ )}++ {recordings.length === 0 ? (+ <p className="text-xs text-gray-500">No takes yet. Record the lead first, then layer in harmonies.</p>+ ) : (+ <ul className="space-y-2">+ {recordings.map((r) => (+ <li key={r.id} className={`bg-port-card border rounded-lg flex items-center gap-2 px-3 py-2 ${r.muted ? 'border-port-border opacity-60' : 'border-port-border'}`}>+ <button+ type="button"+ onClick={() => toggleMute(r.id)}+ className={`p-1 shrink-0 ${r.muted ? 'text-gray-600 hover:text-gray-400' : 'text-port-accent hover:text-port-accent/80'}`}+ aria-label={r.muted ? 'Unmute take' : 'Mute take'}+ title={r.muted ? 'Muted — excluded from layered play' : 'Audible in layered play'}+ >+ {r.muted ? <VolumeX size={16} /> : <Volume2 size={16} />}+ </button>+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2 min-w-0">+ <span className="text-sm text-white truncate">{r.label || 'Take'}</span>+ {r.durationMs > 0 && <span className="text-xs text-gray-500 shrink-0">{formatDurationMs(r.durationMs)}</span>}+ </div>+ {layers.length > 0 && (+ <select+ value={r.layerId || ''}+ onChange={(e) => assignLayer(r.id, e.target.value)}+ aria-label="Assign take to layer"+ className="mt-1 bg-port-bg border border-port-border rounded px-2 py-0.5 text-xs text-gray-300 focus:border-port-accent focus:outline-none"+ >+ <option value="">— Unassigned —</option>+ {layers.map((l) => <option key={l.id} value={l.id}>{l.label}</option>)}+ </select>+ )}+ </div>+ {/* Solo listen to one take */}+ <audio controls preload="none" src={getUploadUrl(r.filename)} className="h-8 max-w-[160px] hidden sm:block" />+ <button type="button" onClick={() => removeRecording(r.id)} className="p-1.5 text-gray-500 hover:text-port-error shrink-0" aria-label="Remove take">+ <Trash2 size={15} />+ </button>+ </li>+ ))}+ </ul>+ )}+ </section>+ );+}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex b26305d6b4..2850415cc6 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -86,5 +86,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. |+| `songPlayback.js` | `createLayeredPlayer(takes)` — decode N recorded vocal takes and start them together on one shared `AudioContext` so they stack into a layered a cappella performance (sample-aligned, per-layer mute). Used by the Song editor's recording mixer. || `wrSceneCursor.js` | Resolve which script scene the editor caret sits in (`sceneAtCursor`, `sceneAnchorIndex`) — inverse of WorkEditor's jump-to-scene text search; drives the live render preview's "scene at cursor" target. || `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.jsindex af716ca609..e54fe617c2 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -53,6 +53,7 @@ export * from './voiceLabel.js';// === Page-scoped pure helpers ===export * from './cityPlaybackFrame.js';export * from './songCraft.js';+export * from './songPlayback.js';export * from './universeBuilderExpand.js';export * from './wrSceneCursor.js';export * from './writingGuide.js';diff --git a/client/src/lib/songPlayback.js b/client/src/lib/songPlayback.jsnew file mode 100644index 0000000000..09b4ee1f2c--- /dev/null+++ b/client/src/lib/songPlayback.js@@ -0,0 +1,138 @@+// Layered a cappella playback — decode N recorded vocal takes and start them+// together on one AudioContext so they stack into a multi-part performance.+//+// Web Audio (not N <audio> elements) because only a shared AudioContext clock+// lets us start every buffer on the same `when` timestamp — <audio> elements+// drift by tens of ms, which is audible on a tight harmony. Each take gets its+// own GainNode so a layer can be muted live without restarting the mix.+//+// Pure-ish: no React. The Song editor wraps this in a small hook for UI state.+// decodeAudioData is the only async dependency; callers handle rejection.++// Lazily create + reuse one AudioContext. Browsers cap the number of contexts,+// and reusing one keeps every layer on the same clock. Resumed on demand+// because autoplay policies start it suspended until a user gesture.+let sharedCtx = null;+function ctx() {+ if (!sharedCtx) {+ const Ctor = window.AudioContext || window.webkitAudioContext;+ sharedCtx = new Ctor();+ }+ return sharedCtx;+}++// Decode one recording URL into an AudioBuffer. Cached per-URL on the returned+// mixer (not globally) so a re-open re-fetches at most once per session.+async function fetchBuffer(url) {+ const res = await fetch(url);+ if (!res.ok) throw new Error(`Failed to load recording (${res.status})`);+ const bytes = await res.arrayBuffer();+ // decodeAudioData detaches the ArrayBuffer; pass it directly (we don't reuse).+ return ctx().decodeAudioData(bytes);+}++/**+ * Build a layered-playback mixer over a list of takes.+ *+ * @param {Array<{ id, url, muted? }>} takes — each take's audio URL + initial mute.+ * @returns a mixer: { play(), stop(), setMuted(id, bool), isPlaying(),+ * onEnded(cb), duration() }. `play()` decodes (once) then starts every+ * unmuted take in lockstep; resolves when playback has STARTED (not ended).+ */+export function createLayeredPlayer(takes = []) {+ const layers = new Map(); // id -> { url, buffer, gain, source, muted }+ for (const t of takes) {+ if (t && t.id && t.url) layers.set(t.id, { url: t.url, buffer: null, gain: null, source: null, muted: t.muted === true });+ }++ let playing = false;+ let endedCb = null;+ let liveCount = 0; // sources still playing; fire onEnded when it hits 0++ const stopSources = () => {+ for (const l of layers.values()) {+ if (l.source) {+ l.source.onended = null;+ try { l.source.stop(); } catch { /* already stopped */ }+ l.source = null;+ }+ }+ liveCount = 0;+ };++ const stop = () => {+ if (!playing) return;+ playing = false;+ stopSources();+ };++ const play = async () => {+ stop();+ const c = ctx();+ if (c.state === 'suspended') await c.resume();++ // Decode any not-yet-decoded buffers (parallel). Muted layers are skipped —+ // no point paying decode cost for something we won't hear this round.+ const active = [...layers.values()].filter((l) => !l.muted);+ await Promise.all(active.map(async (l) => {+ if (!l.buffer) l.buffer = await fetchBuffer(l.url);+ }));++ // Start every active layer at the same future timestamp so they're sample-+ // aligned. A small lead time absorbs decode/scheduling jitter.+ const startAt = c.currentTime + 0.06;+ playing = true;+ liveCount = 0;+ for (const l of active) {+ if (!l.buffer) continue;+ const gain = c.createGain();+ gain.gain.value = 1;+ const source = c.createBufferSource();+ source.buffer = l.buffer;+ source.connect(gain).connect(c.destination);+ source.onended = () => {+ if (l.source === source) l.source = null;+ liveCount = Math.max(0, liveCount - 1);+ if (liveCount === 0 && playing) {+ playing = false;+ if (endedCb) endedCb();+ }+ };+ source.start(startAt);+ l.gain = gain;+ l.source = source;+ liveCount += 1;+ }+ // Nothing to play (all muted / no buffers) — report ended immediately.+ if (liveCount === 0) {+ playing = false;+ if (endedCb) endedCb();+ }+ };++ // Toggle a layer's mute. Takes effect on the NEXT play() (we don't hot-swap a+ // running source — restarting keeps the stack sample-aligned, which matters+ // more for a harmony than gapless mute).+ const setMuted = (id, muted) => {+ const l = layers.get(id);+ if (l) l.muted = muted === true;+ };++ // Longest take's duration in seconds (0 until at least one buffer decoded).+ const duration = () => {+ let max = 0;+ for (const l of layers.values()) {+ if (l.buffer && l.buffer.duration > max) max = l.buffer.duration;+ }+ return max;+ };++ return {+ play,+ stop,+ setMuted,+ isPlaying: () => playing,+ onEnded: (cb) => { endedCb = cb; },+ duration,+ };+}diff --git a/client/src/pages/SongEditor.jsx b/client/src/pages/SongEditor.jsxindex 30a2b4cc29..ed0a3c549c 100644--- a/client/src/pages/SongEditor.jsx+++ b/client/src/pages/SongEditor.jsx@@ -23,6 +23,8 @@ 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';+import SongAiPanel from '../components/songs/SongAiPanel';+import SongRecordings from '../components/songs/SongRecordings';// In-session-only id for a freshly-added section/layer, used purely as a React// key until the row is saved. Counter-based (not Math.random, which is@@ -87,6 +89,7 @@ export default function SongEditor() {// them from being persisted and later colliding after a reload.sections: (song.sections || []).map(stripTempId),layers: (song.layers || []).map(stripTempId),+ recordings: (song.recordings || []).map(stripTempId),};const data = await updateSong(id, patch, { silent: true });if (data?.song) setSong(data.song);@@ -94,6 +97,28 @@ export default function SongEditor() {return data?.song;}, { errorMessage: 'Failed to save song' });+ // Merge an AI-generated draft into the editor. The server returns canonical+ // fields with server-assigned ids; we replace the editable content (metadata,+ // sections, layers, notation, notes) but PRESERVE the user's recordings and+ // `learned` flag — those aren't the model's to overwrite. Nothing persists+ // until the user hits Save (matches the universe-builder review-then-commit+ // flow). The server already folded any prior draft in when expanding, so we+ // simply apply the returned fields.+ const applyGenerated = useCallback((generated) => {+ setSong((prev) => ({+ ...prev,+ title: generated.title || prev.title,+ artist: generated.artist ?? prev.artist,+ key: generated.key ?? prev.key,+ tempo: generated.tempo ?? prev.tempo,+ rhythmShapeId: generated.rhythmShapeId ?? prev.rhythmShapeId,+ notation: generated.notation ?? prev.notation,+ notes: generated.notes ?? prev.notes,+ sections: Array.isArray(generated.sections) ? generated.sections : prev.sections,+ layers: Array.isArray(generated.layers) ? generated.layers : prev.layers,+ }));+ }, []);+// --- Section helpers ----------------------------------------------------const addSection = () => setSong((prev) => ({...prev,@@ -232,6 +257,9 @@ export default function SongEditor() {</label></section>+ {/* AI assist — generate / expand / evaluate */}+ <SongAiPanel songId={id} onApplyGenerated={applyGenerated} />+{/* Lyric sections */}<section><div className="flex items-center justify-between mb-2">@@ -343,6 +371,13 @@ export default function SongEditor() {)}</section>+ {/* Vocal takes — record & layered playback */}+ <SongRecordings+ recordings={song.recordings || []}+ layers={song.layers || []}+ onChange={(recordings) => setField('recordings', recordings)}+ />+{/* Notation + notes */}<section className="grid grid-cols-1 gap-4"><div>diff --git a/client/src/pages/Songs.jsx b/client/src/pages/Songs.jsxindex 7934785c21..7dba414261 100644--- a/client/src/pages/Songs.jsx+++ b/client/src/pages/Songs.jsx@@ -10,11 +10,11 @@import { useEffect, useState, useCallback } from 'react';import { useNavigate, Link } from 'react-router-dom';-import { Music, Plus, Trash2, BookOpen, CheckCircle2, Circle } from 'lucide-react';+import { Music, Plus, Trash2, BookOpen, CheckCircle2, Circle, Wand2 } 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 { listSongs, createSong, deleteSong, generateSong } from '../services/api';import { RHYTHM_SHAPES } from '../lib/songCraft';const shapeLabel = (id) => RHYTHM_SHAPES.find((s) => s.id === id)?.label || null;@@ -44,6 +44,24 @@ export default function Songs() {return song;}, { errorMessage: 'Failed to create song' });+ // 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+ // the AI service stateless about storage; the editor's own Generate/Expand+ // buttons drive subsequent rounds.+ const [generate, generating] = useAsyncAction(async () => {+ const name = title.trim();+ const data = await generateSong(+ { 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;+ if (song) navigate(`/songs/${song.id}`);+ return song;+ }, { errorMessage: 'Failed to generate song' });+const onDelete = useCallback(async (song) => {if (armed !== song.id) { setArmed(song.id); return; }setArmed(null);@@ -99,14 +117,26 @@ export default function Songs() {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>+ <div className="flex gap-2">+ <button+ type="submit"+ disabled={creating || generating}+ 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>+ <button+ type="button"+ onClick={() => generate()}+ disabled={creating || generating}+ title="Draft a full arrangement with AI from the title/artist above"+ className="flex items-center justify-center gap-2 px-4 py-2 text-sm rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50 disabled:opacity-50"+ >+ <Wand2 size={16} />+ {generating ? 'Generating…' : 'Generate'}+ </button>+ </div></form>{/* List */}diff --git a/client/src/services/apiSongs.js b/client/src/services/apiSongs.jsindex f416da6658..695fff00bc 100644--- a/client/src/services/apiSongs.js+++ b/client/src/services/apiSongs.js@@ -19,3 +19,17 @@ export const updateSong = (id, patch, options) =>export const deleteSong = (id, options) =>request(`/songs/${enc(id)}`, { method: 'DELETE', ...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 });diff --git a/server/lib/README.md b/server/lib/README.mdindex 26d1a3624c..f9fafc2a73 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -161,6 +161,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|| `curatedGenomeMarkers.js` | Curated SNP database with classification logic. |+| `songCraftRef.js` | Server-side mirror of the a cappella rhythm-shape + voice-layer vocabulary (`RHYTHM_SHAPES`, `VOICE_LAYERS`, `DIRGE_RHYTHM_SHAPES`) injected into the song generate/evaluate prompts so the model returns ids the editor pickers understand. Mirrors `client/src/lib/songCraft.js`. |## Domain utilitiesdiff --git a/server/lib/index.js b/server/lib/index.jsindex bfcc78ac21..83d1f9541d 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -137,6 +137,7 @@ export * from './taskParser.js';// === Curated static data ===export * from './curatedGenomeMarkers.js';+export * from './songCraftRef.js';// === Domain utilities ===export * from './appResolver.js';diff --git a/server/lib/songCraftRef.js b/server/lib/songCraftRef.jsnew file mode 100644index 0000000000..9e21e4de8c--- /dev/null+++ b/server/lib/songCraftRef.js@@ -0,0 +1,43 @@+/**+ * Server-side mirror of the a cappella song-craft vocabulary.+ *+ * The full reference data (BPM bands, counts, learning steps, notation help,+ * solfège) lives client-side in `client/src/lib/songCraft.js` and is rendered+ * by the Songs Guide. The server only needs the *vocabulary* — the rhythm-shape+ * 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+ * 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 it+ * in `client/src/lib/songCraft.js` (and vice versa) so generated ids resolve in+ * the UI. Unknown ids are tolerated downstream (free-text fallback), so a brief+ * drift can't 400 — but it costs picker resolution until reconciled.+ */++// Rhythm shapes: { id, label, dirge, feel }. `dirge` marks the slow/lament+// family the workbench is built around. Mirrors RHYTHM_SHAPES in songCraft.js.+export const RHYTHM_SHAPES = [+ { id: 'slow-4-4', label: 'Slow 4/4 ballad', dirge: true, feel: 'Four even beats per bar, weight on 1 and 3.' },+ { id: 'dirge-6-8', label: 'Compound 6/8 dirge', dirge: true, feel: 'Two slow pulses per bar, each split into three — a swaying funeral-march lilt.' },+ { id: 'rubato-free', label: 'Rubato / free-time lament', dirge: true, feel: 'Pulse stretches and contracts with the phrase; the lead breathes, the layers follow.' },+ { id: 'cut-time-march', label: 'Cut-time processional', dirge: true, feel: 'Two broad pulses per bar — a walking, processional tread.' },+ { id: 'driving-4-4', label: 'Driving 4/4 (uptempo)', dirge: false, feel: 'Steady, energetic four — backbeat emphasis on 2 and 4.' },+ { id: 'waltz-3-4', label: 'Waltz 3/4', dirge: false, feel: 'Three beats per bar, strong downbeat then two lighter beats.' },+];++// Voice layers in foundation-first build order: { id, label, voices, role }.+// Mirrors VOICE_LAYERS in songCraft.js.+export const VOICE_LAYERS = [+ { id: 'lead', label: 'Lead melody', voices: 'Any — the tune everyone knows', role: 'The song itself. Everyone learns this first so the harmony has a home to orbit.' },+ { id: 'bass', label: 'Bass / root', voices: 'Bass', role: 'The harmonic floor — usually the root of each chord, moving slowly.' },+ { id: 'harmony-3rd', label: 'Harmony (third)', voices: 'Alto / Tenor', role: 'A line a third above or below the melody — the first taste of chord color.' },+ { id: 'harmony-5th', label: 'Harmony (fifth)', voices: 'Tenor / Soprano', role: 'The fifth fills out the triad and opens the sound up.' },+ { id: 'drone', label: 'Drone / pedal', voices: 'Bass / Alto', role: 'A sustained held note (often the tonic or fifth) under everything.' },+ { id: 'counter', label: 'Counter-melody', voices: 'Soprano / Tenor', role: 'An independent melodic line that answers the lead in its gaps.' },+ { id: 'vocal-perc', label: 'Vocal percussion / texture', voices: 'Any', role: 'Breath, hums, clicks, "doo"/"ah" pads, or beatbox — rhythmic and textural glue.' },+];++// The dirge-family shapes (the lament the workbench centers on), in order.+export const DIRGE_RHYTHM_SHAPES = RHYTHM_SHAPES.filter((s) => s.dirge);diff --git a/server/routes/songs.js b/server/routes/songs.jsindex 6d48aa78e5..f74e20edf7 100644--- a/server/routes/songs.js+++ b/server/routes/songs.js@@ -18,6 +18,7 @@ import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import * as svc from '../services/songs.js';+import { generateSong, evaluateSong } from '../services/songsAI.js';const router = Router();@@ -37,6 +38,20 @@ const layerSchema = z.object({notes: str(svc.FIELD_MAX_LENGTH).optional().default(''),});+// 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+// filename). Numbers are accepted for the mixer; the service clamps them.+const recordingSchema = z.object({+ id: str(svc.ID_MAX_LENGTH).optional(),+ layerId: str(svc.ID_MAX_LENGTH).optional().default(''),+ label: str(svc.LABEL_MAX_LENGTH).optional().default(''),+ filename: str(svc.URL_MAX_LENGTH),+ durationMs: z.number().nonnegative().optional(),+ peak: z.number().min(0).max(1).optional(),+ muted: z.boolean().optional(),+ createdAt: z.string().optional(),+});+// 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@@ -54,6 +69,27 @@ const songInputSchema = z.object({learned: z.boolean().optional(),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(),+});++// AI generate/evaluate inputs. providerId/model are optional overrides; the+// service falls back to the active provider. Empty-string providerId (a UI+// "use default" sentinel) is coerced to undefined so it doesn't pin a bogus id.+const optProvider = z.preprocess((v) => (v === '' ? undefined : v), z.string().optional());+const generateSchema = z.object({+ title: str(svc.TITLE_MAX_LENGTH).optional(),+ 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+ // "generate" expands the existing draft instead of starting blank.+ expandExisting: z.boolean().optional(),+ providerId: optProvider,+ model: optProvider,+});+const evaluateSchema = z.object({+ providerId: optProvider,+ model: optProvider,});// Map a service error (carries a `code`) to the right HTTP status. Without@@ -92,4 +128,43 @@ router.delete('/:id', asyncHandler(async (req, res) => {res.json(result);}));+// --- 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.+// (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);+ 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 };+// 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({+ title: body.title ?? existing.title,+ artist: body.artist ?? existing.artist,+ brief: body.brief,+ mood: body.mood,+ existingSong: 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.+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 });+ res.json(result);+}));+export default router;diff --git a/server/routes/songs.test.js b/server/routes/songs.test.jsindex 293df82f8e..a90b82248a 100644--- a/server/routes/songs.test.js+++ b/server/routes/songs.test.js@@ -18,6 +18,14 @@ vi.mock('../services/songs.js', async () => {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(),+}));+vi.mock('../services/songsAI.js', () => aiMocks);+import songsRoutes from './songs.js';const makeApp = () => {@@ -31,6 +39,7 @@ const makeApp = () => {describe('songs 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 () => {@@ -99,4 +108,69 @@ describe('songs route', () => {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({+ recordings: [{ layerId: 'lead', filename: 'abc-vocal.wav', durationMs: 1200, peak: 0.4 }],+ });+ expect(res.status).toBe(200);+ const [, patch] = mocks.updateSong.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({+ recordings: [{ filename: 'x.wav', peak: 5 }],+ });+ expect(res.status).toBe(400);+ expect(mocks.updateSong).not.toHaveBeenCalled();+ });++ 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' });+ expect(res.status).toBe(200);+ expect(res.body.song.title).toBe('New');+ expect(aiMocks.generateSong).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];+ 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({});+ expect(res.status).toBe(404);+ expect(aiMocks.generateSong).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 });+ expect(res.status).toBe(200);+ const [arg] = aiMocks.generateSong.mock.calls[0];+ expect(arg.existingSong).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({});+ 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({});+ expect(res.status).toBe(404);+ expect(aiMocks.evaluateSong).not.toHaveBeenCalled();+ });});diff --git a/server/services/songs.js b/server/services/songs.jsindex 66e2cdc33b..f43638fc4d 100644--- a/server/services/songs.js+++ b/server/services/songs.js@@ -41,6 +41,8 @@ export const TEMPO_MIN = 20;export const TEMPO_MAX = 320;export const SECTIONS_MAX = 60;export const LAYERS_MAX = 24;+export const RECORDINGS_MAX = 64; // saved vocal takes for layered playback+export const URL_MAX_LENGTH = 512; // uploaded-file path/url// Trim a string field, returning '' for non-strings. Mirrors the// absent-vs-empty rule in CLAUDE.md: callers decide whether '' clears.@@ -83,6 +85,32 @@ const sanitizeLayer = (l) => {};};+// One saved vocal take ({ id, layerId, filename, label, durationMs, peak,+// mutedByDefault }). `filename` is the /api/uploads file name the audio is+// served from; a recording without one is meaningless, so it's dropped.+// `layerId` ties a take to a voice layer for the layered-playback mixer (free+// text — empty means "unassigned"). Numbers are coerced/clamped; bad values+// fall to sensible defaults rather than throwing.+const sanitizeRecording = (r) => {+ if (!r || typeof r !== 'object') return null;+ const filename = trimField(r.filename, URL_MAX_LENGTH);+ if (!filename) return null;+ const durationMs = typeof r.durationMs === 'number' && Number.isFinite(r.durationMs)+ ? Math.max(0, Math.round(r.durationMs)) : 0;+ const peak = typeof r.peak === 'number' && Number.isFinite(r.peak)+ ? Math.max(0, Math.min(1, r.peak)) : 0;+ return {+ id: trimField(r.id, ID_MAX_LENGTH) || `rec-${randomUUID().slice(0, 8)}`,+ layerId: trimField(r.layerId, ID_MAX_LENGTH),+ label: trimField(r.label, LABEL_MAX_LENGTH),+ filename,+ durationMs,+ peak,+ muted: r.muted === true,+ createdAt: typeof r.createdAt === 'string' ? r.createdAt : new Date().toISOString(),+ };+};+const sanitizeList = (arr, fn, max) =>(Array.isArray(arr) ? arr : []).map(fn)@@ -107,6 +135,7 @@ export const sanitizeSong = (raw) => {learned: raw.learned === true,sections: sanitizeList(raw.sections, sanitizeSection, SECTIONS_MAX),layers: sanitizeList(raw.layers, sanitizeLayer, LAYERS_MAX),+ recordings: sanitizeList(raw.recordings, sanitizeRecording, RECORDINGS_MAX),createdAt: typeof raw.createdAt === 'string' ? raw.createdAt : new Date().toISOString(),updatedAt: typeof raw.updatedAt === 'string' ? raw.updatedAt : new Date().toISOString(),};@@ -206,7 +235,7 @@ export async function updateSong(id, patch) {// Merge field-by-field so an absent key preserves the stored value while a// present key (including empty string / empty array) applies the change.const merged = { ...songs[idx] };- for (const key of ['title', 'artist', 'key', 'tempo', 'rhythmShapeId', 'notation', 'notes', 'learned', 'sections', 'layers']) {+ for (const key of ['title', 'artist', 'key', 'tempo', 'rhythmShapeId', 'notation', 'notes', 'learned', 'sections', 'layers', 'recordings']) {if (key in patch) merged[key] = patch[key];}merged.id = id;diff --git a/server/services/songs.test.js b/server/services/songs.test.jsindex a0540c9ca2..034233b5e0 100644--- a/server/services/songs.test.js+++ b/server/services/songs.test.js@@ -135,4 +135,26 @@ describe('songs service', () => {expect(svc.sanitizeSong({})).toBeNull(); // no idexpect(svc.sanitizeSong({ id: 'x' }).title).toBe('Untitled song');});++ it('sanitizes recordings — drops fileless takes, clamps peak, mints ids', () => {+ const song = svc.sanitizeSong({+ id: 'x',+ recordings: [+ { layerId: 'lead', filename: 'a-vocal.wav', durationMs: 1200.7, peak: 0.4 },+ { layerId: 'bass', label: 'no file' }, // no filename → dropped+ { filename: 'b.wav', peak: 5, durationMs: -3 }, // peak clamped, duration floored+ ],+ });+ expect(song.recordings).toHaveLength(2);+ expect(song.recordings[0].filename).toBe('a-vocal.wav');+ expect(song.recordings[0].durationMs).toBe(1201);+ expect(song.recordings[0].id).toMatch(/^rec-/);+ expect(song.recordings[1].peak).toBe(1); // clamped to max+ expect(song.recordings[1].durationMs).toBe(0); // negative floored+ });++ it('preserves a stable recording id submitted with the take', () => {+ const song = svc.sanitizeSong({ id: 'x', recordings: [{ id: 'rec-keep', filename: 'k.wav' }] });+ expect(song.recordings[0].id).toBe('rec-keep');+ });});diff --git a/server/services/songsAI.js b/server/services/songsAI.jsnew file mode 100644index 0000000000..a40de1eef8--- /dev/null+++ b/server/services/songsAI.js@@ -0,0 +1,231 @@+/**+ * Songs 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+ * 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)+ * 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+ * (promptRunner → providers → runner) doesn't load on every plain song read.+ */++import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from '../lib/promptRunner.js';+import { extractJson } from '../lib/jsonExtract.js';+import { ServerError } from '../lib/errorHandler.js';+import {+ RHYTHM_SHAPES, VOICE_LAYERS, DIRGE_RHYTHM_SHAPES,+} from '../lib/songCraftRef.js';+import {+ sanitizeSong, FIELD_MAX_LENGTH, SECTIONS_MAX, LAYERS_MAX,+} from './songs.js';++// Strip dangerous control chars that would corrupt the prompt or invite+// structure-injection (a lyric containing a fake "# Output contract" header),+// and cap length so a giant pasted lyric can't blow the context budget.+// Newlines and tabs are PRESERVED — lyric line breaks carry meaning here.+const PROMPT_FIELD_MAX = 4000;+// eslint-disable-next-line no-control-regex+const CONTROL_CHARS = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g;+const clean = (v) =>+ (typeof v === 'string' ? v.replace(CONTROL_CHARS, '').slice(0, PROMPT_FIELD_MAX) : '');++// Compact vocabulary blocks the model can choose ids from. Listing them inline+// keeps the editor pickers and the generated ids in sync without a round-trip.+const rhythmVocab = () =>+ RHYTHM_SHAPES.map((s) => `- ${s.id}: ${s.label}${s.dirge ? ' (dirge/lament)' : ''} — ${s.feel}`).join('\n');+const layerVocab = () =>+ VOICE_LAYERS.map((l) => `- ${l.id}: ${l.label} (${l.voices}) — ${l.role}`).join('\n');++// --- Shape predicates (jsonExtract) ----------------------------------------+const isGeneratedShape = (o) =>+ o && typeof o === 'object' &&+ (Array.isArray(o.sections) || Array.isArray(o.layers) || typeof o.notation === 'string' || typeof o.notes === 'string');++const isVerdictShape = (o) =>+ o && typeof o === 'object' &&+ (typeof o.score === 'number' || Array.isArray(o.strengths) || Array.isArray(o.suggestions));++// Pull JSON out of the LLM body or throw a typed 502 the route maps verbatim.+const parseOrThrow = (raw, shapePredicate, what) => {+ const { value, lastPreview } = extractJson(raw, { shapePredicate });+ if (value !== undefined) return value;+ throw new ServerError(+ `The AI returned invalid JSON for song ${what}. Try a different model or rerun.`,+ { status: 502, code: 'LLM_INVALID_JSON', context: { details: { preview: lastPreview } } },+ );+};++// --- Generate --------------------------------------------------------------+const buildGeneratePrompt = ({ title, artist, brief, mood, existing }) => {+ const want = [+ title && `Title: ${title}`,+ artist && `Artist / in the style of: ${artist}`,+ brief && `Brief: ${brief}`,+ mood && `Mood / feel: ${mood}`,+ ].filter(Boolean).join('\n');++ const existingBlock = existing+ ? `\n\nThe user already has this draft — extend and improve it, keep what works, fill the gaps:\n${existing}`+ : '';++ return `You are an a cappella arranger and songwriter. Write a singable, original a cappella arrangement (lyrics + voice-layer plan) the user can learn and perform unaccompanied. Lean toward folk/ballad/dirge sensibilities (e.g. "500 Miles" by Peter, Paul and Mary) unless the brief says otherwise.++${want || 'Write a short, mournful a cappella ballad.'}${existingBlock}++# Rhythm shapes you may pick from (return the id in rhythmShapeId)+${rhythmVocab()}+Dirge/lament shapes: ${DIRGE_RHYTHM_SHAPES.map((s) => s.id).join(', ')}.++# Voice layers — return these foundation-first (lead, then bass, then thirds/fifths, then drone/counter). Use the id when it matches.+${layerVocab()}++# Output contract+Return ONLY a JSON object (no prose, no markdown fence) with this shape:+{+ "title": "string",+ "artist": "string (optional — performer or 'in the style of')",+ "key": "string e.g. 'C major'",+ "tempo": 68, // integer BPM, 20–320, or null+ "rhythmShapeId": "one of the ids above",+ "notation": "string — chord progression / lead-sheet notes / solfège, e.g. 'C — Am — F — G'",+ "notes": "string — how it should feel, dynamics, where to breathe, what to drill",+ "sections": [ { "label": "Verse 1", "lyrics": "..." } ], // max ${SECTIONS_MAX}+ "layers": [ { "id": "lead", "label": "Lead melody", "part": "Soprano/Tenor", "notes": "learning notes — intervals, entrances, breaths" } ] // max ${LAYERS_MAX}+}+Keep lyrics original (do not reproduce copyrighted lyrics verbatim). Each string field under ${FIELD_MAX_LENGTH} characters.`;+};++/**+ * 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+ * so "generate" doubles as "expand this draft".+ */+export async function generateSong({ title, artist, brief, mood, existingSong, 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 prompt = buildGeneratePrompt({+ title: clean(title), artist: clean(artist), brief: clean(brief), mood: clean(mood), existing,+ });++ const { text: raw, model: ranModel } = await runPromptThroughProvider({+ provider, model: selectedModel, prompt, source: 'song-generate',+ });++ const parsed = parseOrThrow(raw, isGeneratedShape, 'generation');+ // Project onto the canonical shape; sanitizeSong requires an id, so stamp a+ // placeholder the caller replaces — we only want the normalized fields back.+ const song = sanitizeSong({ ...parsed, id: 'draft' });+ if (!song) {+ throw new ServerError('The AI produced an unusable song. Try rerunning.', { status: 502, code: 'LLM_EMPTY' });+ }+ const { id: _drop, createdAt: _c, updatedAt: _u, ...fields } = song;+ console.log(`🎵 Generated song "${fields.title}" via ${provider.id}/${ranModel || 'default'}`);+ return { song: fields, llm: { provider: provider.id, model: ranModel || null } };+}++// --- Evaluate --------------------------------------------------------------+// Render a stored song into a compact prompt block — used by evaluate and by+// generate's "expand existing" path.+export function summarizeSongForPrompt(song) {+ if (!song || typeof song !== 'object') return '';+ const shape = RHYTHM_SHAPES.find((s) => s.id === song.rhythmShapeId);+ const lines = [+ song.title && `Title: ${clean(song.title)}`,+ song.artist && `Artist: ${clean(song.artist)}`,+ song.key && `Key: ${clean(song.key)}`,+ song.tempo && `Tempo: ${song.tempo} BPM`,+ shape && `Rhythm shape: ${shape.label}${shape.dirge ? ' (dirge)' : ''}`,+ song.notation && `Notation: ${clean(song.notation)}`,+ song.notes && `Arrangement notes: ${clean(song.notes)}`,+ ].filter(Boolean);++ const sections = (song.sections || []).slice(0, SECTIONS_MAX)+ .map((s) => `[${clean(s.label) || 'Section'}]\n${clean(s.lyrics)}`).join('\n\n');+ const layers = (song.layers || []).slice(0, LAYERS_MAX)+ .map((l) => `- ${clean(l.label)}${l.part ? ` (${clean(l.part)})` : ''}: ${clean(l.notes)}`).join('\n');++ return [+ lines.join('\n'),+ sections && `\nLyrics & structure:\n${sections}`,+ layers && `\nVoice layers:\n${layers}`,+ ].filter(Boolean).join('\n');+}++const buildEvaluatePrompt = (songBlock) =>+ `You are an a cappella coach evaluating an arrangement for singability, harmonic soundness, and emotional impact. Be specific and constructive — name the section/layer you mean.++# The arrangement+${songBlock}++# What to assess+- Singability: are the parts in comfortable ranges, do entrances/breaths work unaccompanied?+- Harmony: do the layers build foundation-first (lead, bass, thirds, fifths) and stay in tune as a stack?+- Structure & lyrics: does the form serve the mood; do lyrics scan and breathe across the bar?+- Layer balance: is anything missing (a drone, a counter-melody) or overcrowded?++# Output contract+Return ONLY a JSON object (no prose, no markdown fence):+{+ "score": 0, // integer 0–100, overall performance-readiness+ "summary": "one or two sentence overall take",+ "strengths": ["..."], // up to 6+ "weaknesses": ["..."], // up to 6+ "suggestions": ["concrete, actionable next steps"] // up to 6+}`;++/**+ * Evaluate a stored song arrangement. Returns a verdict { score, summary,+ * strengths[], weaknesses[], suggestions[] } plus an `llm` block. Pure+ * read-side AI — does not mutate the song.+ */+export async function evaluateSong({ song, providerId, model } = {}) {+ if (!song || typeof song !== 'object') {+ throw new ServerError('A song is required to evaluate', { status: 400, code: 'VALIDATION_ERROR' });+ }+ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });+ assertProvider(provider, { message: 'No AI provider available for song evaluation', code: 'NO_PROVIDER' });++ const prompt = buildEvaluatePrompt(summarizeSongForPrompt(song));+ const { text: raw, model: ranModel } = await runPromptThroughProvider({+ provider, model: selectedModel, prompt, source: 'song-evaluate',+ });++ const parsed = parseOrThrow(raw, isVerdictShape, 'evaluation');+ const verdict = normalizeVerdict(parsed);+ console.log(`🎼 Evaluated song "${clean(song.title) || song.id}" → ${verdict.score}/100 via ${provider.id}/${ranModel || 'default'}`);+ return { evaluation: verdict, llm: { provider: provider.id, model: ranModel || null } };+}++// Coerce the model's verdict into a known shape: clamp the score, cap each+// list, and drop non-string entries so a malformed list can't reach the UI.+const LIST_MAX = 6;+const strList = (v) =>+ (Array.isArray(v) ? v : [])+ .map((x) => (typeof x === 'string' ? x.trim() : ''))+ .filter(Boolean)+ .slice(0, LIST_MAX);++export function normalizeVerdict(raw) {+ const scoreNum = Number(raw?.score);+ const score = Number.isFinite(scoreNum) ? Math.max(0, Math.min(100, Math.round(scoreNum))) : null;+ return {+ score,+ summary: typeof raw?.summary === 'string' ? raw.summary.trim().slice(0, FIELD_MAX_LENGTH) : '',+ strengths: strList(raw?.strengths),+ weaknesses: strList(raw?.weaknesses),+ suggestions: strList(raw?.suggestions),+ };+}diff --git a/server/services/songsAI.test.js b/server/services/songsAI.test.jsnew file mode 100644index 0000000000..8daa3d69eaBinary files /dev/null and b/server/services/songsAI.test.js differ