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

feat([issue-1028]): song training mode — section looping, scoring, learned-progress tracking

Adam Eivy96541de2577d
diff --git a/client/src/components/songs/ScoreSheet.jsx b/client/src/components/songs/ScoreSheet.jsx
index c1e25adace..77de906fae 100644
--- a/client/src/components/songs/ScoreSheet.jsx
+++ b/client/src/components/songs/ScoreSheet.jsx
@@ -145,7 +145,7 @@ const rowLyricOffset = (row, bottomLineStep) => {
return Math.max(LYRIC_MIN_BELOW_STAFF, belowStaffPx + LYRIC_BELOW_NOTE);
};
-export default function ScoreSheet({ text, className = '', controls = true, activeNoteIndex = null, noteColors = null }) {
+export default function ScoreSheet({ text, className = '', controls = true, activeNoteIndex = null, noteColors = null, hideLyrics = false }) {
const score = useMemo(() => parseScore(text), [text]);
// --- Reference-tone playback (synthesize the written melody) ---------------
@@ -311,7 +311,7 @@ export default function ScoreSheet({ text, className = '', controls = true, acti
if (note.chord) {
els.push(<text key={`${key}-ch`} x={cx} y={chordY} fontSize={12} fontWeight="600" style={fillStyle(CHORD)} textAnchor="middle" fontFamily="ui-sans-serif, system-ui, sans-serif">{note.chord}</text>);
}
- if (note.lyric) {
+ if (note.lyric && !hideLyrics) {
els.push(<text key={`${key}-ly`} x={cx} y={lyricY} fontSize={11} style={fillStyle(LYRIC)} textAnchor="middle" fontFamily="ui-sans-serif, system-ui, sans-serif">{note.lyric}</text>);
}
});
diff --git a/client/src/components/songs/SongTraining.jsx b/client/src/components/songs/SongTraining.jsx
new file mode 100644
index 0000000000..d571fc2a1f
--- /dev/null
+++ b/client/src/components/songs/SongTraining.jsx
@@ -0,0 +1,313 @@
+/**
+ * SongTraining — the practice loop that ties the song system together into a
+ * memorize / learn / track tool (#1028, the capstone of the #1021 umbrella).
+ *
+ * Pick a target (the whole song or one section), press Start, get counted in on
+ * the metronome, sing the part, and watch the staff grade you note-by-note
+ * (green / yellow / red) with an accuracy score — then repeat. Loop a single
+ * section to drill it, or loop the whole song. As your rolling average on a
+ * scope climbs, the lyrics fade and finally hide so you're singing from memory.
+ * A progress panel shows which sections are learned, your best/average per
+ * scope, and nudges you toward the weakest sections (spaced repetition).
+ *
+ * It is a thin shell over `useSongTraining` (which reuses the color-match timing
+ * + grading loop) and the pure `songProgress` core (sections, history, stats).
+ * It owns its OWN mic — training is a deliberate practice action separate from
+ * "record a take", and nothing is saved as a recording — and reports progress up
+ * to the parent via `onProgress` (persisted on the song's Save, like takes).
+ *
+ * Colors/copy use `--port-*` tokens only; the layout is mobile-responsive.
+ */
+
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { GraduationCap, Play, Square, Repeat, CheckCircle2, Circle, Target } from 'lucide-react';
+import toast from '../ui/Toast';
+import { scoreHasMusic } from '../../lib/scoreNotation.js';
+import {
+ WHOLE_SONG_SCOPE,
+ deriveTrainingSections,
+ scopeStats,
+ wholeSongStats,
+ weakestSections,
+ memorizationPercent,
+ hideLevelFor,
+} from '../../lib/songProgress.js';
+import useSongTraining from '../../hooks/useSongTraining.js';
+import useMounted from '../../hooks/useMounted.js';
+import ScoreSheet from './ScoreSheet.jsx';
+
+// Accuracy % → readout tone. Mirrors the color-match summary coloring.
+const percentTone = (pct) => (pct >= 80 ? 'text-port-success' : pct >= 50 ? 'text-port-warning' : 'text-port-error');
+
+export default function SongTraining({
+ score = '',
+ lyricSections = [],
+ tempo = null,
+ progress = null,
+ onProgress,
+}) {
+ const hasMusic = useMemo(() => scoreHasMusic(score), [score]);
+ const sections = useMemo(() => deriveTrainingSections(score, lyricSections), [score, lyricSections]);
+
+ // Which scope is selected for the next run: WHOLE_SONG_SCOPE or a section id.
+ const [scopeId, setScopeId] = useState(WHOLE_SONG_SCOPE);
+ const [loop, setLoop] = useState(false);
+
+ // Keep the selected scope valid as the score changes (a section can vanish on
+ // an edit) — fall back to the whole song.
+ useEffect(() => {
+ if (scopeId !== WHOLE_SONG_SCOPE && !sections.some((s) => s.id === scopeId)) {
+ setScopeId(WHOLE_SONG_SCOPE);
+ }
+ }, [sections, scopeId]);
+
+ const activeScope = useMemo(
+ () => (scopeId === WHOLE_SONG_SCOPE
+ ? { id: WHOLE_SONG_SCOPE, label: 'Whole song', score }
+ : sections.find((s) => s.id === scopeId) || { id: WHOLE_SONG_SCOPE, label: 'Whole song', score }),
+ [scopeId, sections, score],
+ );
+
+ // The training mic — opened on Start, closed on Stop / unmount. Training is a
+ // deliberate practice action, so it owns its own getUserMedia (separate from
+ // the take recorder), and nothing it captures is persisted as audio.
+ const [stream, setStream] = useState(null);
+ const streamRef = useRef(null);
+ const mountedRef = useMounted();
+
+ const {
+ running, countingIn, noteColors, activeIndex, lastSummary, start, stop,
+ } = useSongTraining({
+ scopeId: activeScope.id,
+ scopeScore: activeScope.score,
+ stream,
+ tempo,
+ loop,
+ progress,
+ onProgress,
+ });
+
+ const closeMic = useCallback(() => {
+ if (streamRef.current) {
+ streamRef.current.getTracks().forEach((t) => t.stop());
+ streamRef.current = null;
+ }
+ setStream(null);
+ }, []);
+
+ // Stop a session: end the training loop, then close the mic.
+ const handleStop = useCallback(() => {
+ stop();
+ closeMic();
+ }, [stop, closeMic]);
+
+ const handleStart = useCallback(async () => {
+ if (running || stream) return;
+ const src = await navigator.mediaDevices.getUserMedia({ audio: true }).catch((err) => {
+ toast.error(err?.message || 'Microphone access denied');
+ return null;
+ });
+ if (!src) return;
+ if (!mountedRef.current) { src.getTracks().forEach((t) => t.stop()); return; }
+ streamRef.current = src;
+ setStream(src);
+ }, [running, stream, mountedRef]);
+
+ // Once the mic stream lands (after Start), arm the training run for the scope.
+ useEffect(() => {
+ if (stream && !running && hasMusic && activeScope.score) start();
+ // start is stable from the hook; only react to the stream arriving.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [stream]);
+
+ // Tear the mic down on unmount.
+ useEffect(() => () => {
+ if (streamRef.current) streamRef.current.getTracks().forEach((t) => t.stop());
+ }, []);
+
+ // Derived progress views — recomputed from the (immutable) progress aggregate.
+ const wholeStats = useMemo(() => wholeSongStats(progress), [progress]);
+ const overall = useMemo(() => memorizationPercent(progress, sections), [progress, sections]);
+ const weak = useMemo(() => weakestSections(progress, sections).slice(0, 3), [progress, sections]);
+
+ // Progressive hiding for the staff lyrics, driven by the active scope's
+ // rolling average so a single good take doesn't yank the crutch mid-drill.
+ const scopeAvg = useMemo(
+ () => scopeStats(progress, activeScope.id).average,
+ [progress, activeScope.id],
+ );
+ const hideLevel = hideLevelFor(scopeAvg);
+ const showLyrics = hideLevel === 'show' || hideLevel === 'dim';
+ const showNotes = hideLevel !== 'blind';
+ const dimLyrics = hideLevel === 'dim';
+
+ if (!hasMusic) {
+ return (
+ <section className="bg-port-card border border-port-border rounded-lg p-4">
+ <h2 className="flex items-center gap-2 text-sm font-semibold text-white mb-2">
+ <GraduationCap size={15} className="text-port-accent" /> Training
+ </h2>
+ <p className="text-xs text-gray-500">
+ Add a notated melody in the Sheet music tab to practice against it — training grades you note by note and tracks what you&apos;ve learned.
+ </p>
+ </section>
+ );
+ }
+
+ return (
+ <section className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">
+ <div className="flex items-center justify-between gap-2 flex-wrap">
+ <h2 className="flex items-center gap-2 text-sm font-semibold text-white">
+ <GraduationCap size={15} className="text-port-accent" /> Training
+ {countingIn && <span className="text-xs font-normal text-port-warning">● counting in…</span>}
+ {running && !countingIn && <span className="text-xs font-normal text-port-error">● singing</span>}
+ </h2>
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => setLoop((v) => !v)}
+ aria-pressed={loop}
+ title={loop ? 'Looping — restarts after each run' : 'Loop this scope'}
+ className={`flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg border transition-colors ${loop ? 'bg-port-accent/15 border-port-accent/60 text-white' : 'border-port-border text-gray-300 hover:text-white hover:bg-port-border/50'}`}
+ >
+ <Repeat size={14} /> Loop
+ </button>
+ {running || stream ? (
+ <button
+ type="button"
+ onClick={handleStop}
+ 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"
+ >
+ <Square size={14} /> Stop
+ </button>
+ ) : (
+ <button
+ type="button"
+ onClick={handleStart}
+ 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"
+ title="Count in, then sing the selected part — you're graded note by note"
+ >
+ <Play size={14} /> Start
+ </button>
+ )}
+ </div>
+ </div>
+
+ {/* Scope picker — whole song or a single section to drill. */}
+ <div>
+ <label htmlFor="training-scope" className="block text-xs text-gray-400 mb-1">Practice</label>
+ <select
+ id="training-scope"
+ value={scopeId}
+ onChange={(e) => setScopeId(e.target.value)}
+ disabled={running || Boolean(stream)}
+ className="w-full sm:w-72 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 disabled:opacity-50"
+ >
+ <option value={WHOLE_SONG_SCOPE}>Whole song</option>
+ {sections.map((s) => (
+ <option key={s.id} value={s.id}>{s.label}{s.measures ? ` (${s.measures} bars)` : ''}</option>
+ ))}
+ </select>
+ </div>
+
+ {/* Latest take readout. */}
+ {lastSummary && (
+ <p className="text-xs text-gray-300" aria-live="polite">
+ Last take:{' '}
+ <span className={`font-semibold ${percentTone(lastSummary.percentInTune)}`}>{lastSummary.percentInTune}%</span>{' '}
+ in tune
+ <span className="text-gray-500"> · {lastSummary.graded} {lastSummary.graded === 1 ? 'note' : 'notes'}</span>
+ </p>
+ )}
+
+ {/* The staff with live grading. Lyrics/notes hide progressively as the
+ scope's rolling average climbs (sing from memory). */}
+ {showNotes ? (
+ <div className={dimLyrics ? 'opacity-90' : ''}>
+ <ScoreSheet
+ text={activeScope.score}
+ controls={false}
+ noteColors={noteColors}
+ activeNoteIndex={activeIndex}
+ hideLyrics={!showLyrics}
+ />
+ {!showLyrics && (
+ <p className="text-xs text-port-success mt-1">Lyrics hidden — you&apos;re singing this from memory. Nice.</p>
+ )}
+ </div>
+ ) : (
+ <p className="text-xs text-port-success py-6 text-center">
+ 🎉 Memorized — singing this with no chart. Press Start and sing it blind.
+ </p>
+ )}
+
+ {/* Progress panel — overall completion, whole-song stats, weak sections. */}
+ <div className="border-t border-port-border pt-3 space-y-3">
+ <div>
+ <div className="flex items-center justify-between text-xs text-gray-400 mb-1">
+ <span>Memorization</span>
+ <span className="text-gray-300">{overall}%</span>
+ </div>
+ <div className="h-2 rounded-full bg-port-bg overflow-hidden">
+ <div className="h-full bg-port-success transition-all" style={{ width: `${overall}%` }} />
+ </div>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-gray-300">
+ <span className="flex items-center gap-1.5">
+ {wholeStats.learned
+ ? <CheckCircle2 size={14} className="text-port-success" />
+ : <Circle size={14} className="text-gray-600" />}
+ Whole song
+ </span>
+ {wholeStats.attempts > 0 && (
+ <>
+ <span>best <span className={`font-semibold ${percentTone(wholeStats.best)}`}>{wholeStats.best}%</span></span>
+ <span className="text-gray-500">avg {wholeStats.average}% · {wholeStats.attempts} {wholeStats.attempts === 1 ? 'take' : 'takes'}</span>
+ </>
+ )}
+ </div>
+
+ {sections.length > 0 && (
+ <ul className="grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-1 text-xs">
+ {sections.map((s) => {
+ const st = scopeStats(progress, s.id);
+ return (
+ <li key={s.id} className="flex items-center justify-between gap-2 text-gray-300">
+ <span className="flex items-center gap-1.5 min-w-0">
+ {st.learned
+ ? <CheckCircle2 size={13} className="text-port-success shrink-0" />
+ : <Circle size={13} className="text-gray-600 shrink-0" />}
+ <span className="truncate">{s.label}</span>
+ </span>
+ {st.attempts > 0
+ ? <span className={`shrink-0 ${percentTone(st.average)}`}>{st.average}%</span>
+ : <span className="text-gray-600 shrink-0">—</span>}
+ </li>
+ );
+ })}
+ </ul>
+ )}
+
+ {weak.length > 0 && (
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="flex items-center gap-1.5 text-xs text-gray-500">
+ <Target size={13} className="text-port-warning" /> Drill next:
+ </span>
+ {weak.map((s) => (
+ <button
+ key={s.id}
+ type="button"
+ onClick={() => setScopeId(s.id)}
+ disabled={running || Boolean(stream)}
+ className="px-2.5 py-1 text-xs rounded-full border border-port-warning/40 text-gray-300 hover:text-white hover:border-port-warning disabled:opacity-40"
+ >
+ {s.label}{s.stats.attempts > 0 ? ` · ${s.stats.average}%` : ' · new'}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ </section>
+ );
+}
diff --git a/client/src/components/songs/SongTraining.test.jsx b/client/src/components/songs/SongTraining.test.jsx
new file mode 100644
index 0000000000..492298f305
--- /dev/null
+++ b/client/src/components/songs/SongTraining.test.jsx
@@ -0,0 +1,74 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent } from '@testing-library/react';
+
+// Drive the component off a mocked training hook so we don't need a real mic /
+// AudioContext (neither exists in jsdom). The hook + the pure progress math are
+// tested on their own (useColorMatch + songProgress.test.js).
+const start = vi.fn();
+const stop = vi.fn();
+let hookState = { running: false, countingIn: false, noteColors: {}, activeIndex: null, lastSummary: null };
+
+vi.mock('../../hooks/useSongTraining.js', () => ({
+ __esModule: true,
+ default: () => ({ ...hookState, start, stop }),
+}));
+
+import SongTraining from './SongTraining.jsx';
+import { recordAttempt, WHOLE_SONG_SCOPE } from '../../lib/songProgress.js';
+
+const SCORE = [
+ 'clef: treble', 'key: G', 'time: 4/4', 'tempo: 68', '',
+ '| [G] D4q(If) D4q(you) | [G] B4h(miss) |',
+ '',
+ '| [Em] B4h(on) | [C] C5q(know) G4q(am) |',
+].join('\n');
+
+describe('SongTraining', () => {
+ beforeEach(() => {
+ start.mockClear();
+ stop.mockClear();
+ hookState = { running: false, countingIn: false, noteColors: {}, activeIndex: null, lastSummary: null };
+ });
+
+ it('prompts to add a melody when the song has no notated music', () => {
+ render(<SongTraining score="" />);
+ expect(screen.getByText(/add a notated melody/i)).toBeTruthy();
+ });
+
+ it('renders the scope picker with the whole song and each section', () => {
+ render(<SongTraining score={SCORE} lyricSections={[{ label: 'Verse 1' }, { label: 'Chorus' }]} />);
+ const select = screen.getByLabelText(/practice/i);
+ const options = Array.from(select.querySelectorAll('option')).map((o) => o.textContent);
+ expect(options[0]).toMatch(/whole song/i);
+ expect(options.some((o) => /Verse 1/.test(o))).toBe(true);
+ expect(options.some((o) => /Chorus/.test(o))).toBe(true);
+ });
+
+ it('shows a Start button that triggers a run after the mic opens', () => {
+ // getUserMedia isn't in jsdom — provide a stub the component awaits.
+ const getUserMedia = vi.fn().mockResolvedValue({ getTracks: () => [] });
+ Object.defineProperty(global.navigator, 'mediaDevices', {
+ value: { getUserMedia }, configurable: true,
+ });
+ render(<SongTraining score={SCORE} />);
+ fireEvent.click(screen.getByRole('button', { name: /start/i }));
+ expect(getUserMedia).toHaveBeenCalled();
+ });
+
+ it('renders progress for trained scopes', () => {
+ // Whole song trained to 90% once.
+ const progress = recordAttempt(null, WHOLE_SONG_SCOPE, { percentInTune: 90, graded: 6 });
+ render(<SongTraining score={SCORE} progress={progress} />);
+ // The whole-song best/avg (both 90% after one take) are surfaced.
+ expect(screen.getAllByText(/90%/).length).toBeGreaterThan(0);
+ // The memorization bar label is present.
+ expect(screen.getByText(/memorization/i)).toBeTruthy();
+ });
+
+ it('surfaces the last-take readout from the hook', () => {
+ hookState = { ...hookState, lastSummary: { percentInTune: 75, graded: 4 } };
+ render(<SongTraining score={SCORE} />);
+ expect(screen.getByText(/last take/i)).toBeTruthy();
+ expect(screen.getByText(/75%/)).toBeTruthy();
+ });
+});
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 866ce96848..2a102a3dda 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -125,6 +125,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useLocalModels` | Live installed Ollama/LM Studio model ids per backend + the server's editorial recommendation. | Model pickers that must show currently-installed local models (not just a provider's stale stored `models`). Fold in via `mergeModelLists` + `localBackendForProvider`. |
| `useTheme` | Dark/light theme + paired-theme switching. | Theme picker. |
| `useSingToScore` | Capture a sung melody from the mic and transcribe it into lead-sheet notation. `start()` opens the mic, counts in on the shared metronome, then accumulates a pitch track relative to beat 1; `stop()` runs the `transcribePitchTrack` pipeline (segment → quantize at the song tempo → spell for the key) and returns the lead-sheet body. Exposes `{ phase, beat, result, error, start, stop, reset }`; tears down mic/analyser/tracker/metronome on stop and unmount. | The Song editor's Sing-to-score panel. |
+| `useSongTraining` | Drives a song training run over one scope (whole song or a sliced section) on top of `useColorMatch`: counts in, walks + grades the scope's score, then folds the finished take into the rolling progress history (`songProgress.recordAttempt`) and surfaces the next aggregate via `onProgress`. Supports looping (auto-restart after a run) and keeps a `lastSummary`. Exposes `{ running, countingIn, noteColors, activeIndex, lastSummary, start, stop }`; cancels pending loop relaunches on stop/unmount. | The Song editor's Training panel. |
| `useSyncIntegrity` | Fetches per-kind integrity diff from every eligible online peer; reduces to worst-case `statusById` + `byPeer` breakdown maps. | Federated media sync integrity UI — badges, drawers, peer breakdown. |
| `useUniverse` | Loads the universe record for a `universeId` with mount/cancel guards; returns `[universe, setUniverse, loading, error]` (setter exposed for optimistic post-mutation updates). | Any surface that loads a linked universe (pipeline stages, etc.) — use instead of re-rolling the getUniverse-on-mount effect. |
| `useUniverseAction` | LLM-driven universe mutation scaffolding. | Universe Builder action UIs. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index b490bfe4ad..9c950ddcc7 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -19,6 +19,7 @@ export { default as useImageRenderSettings } from './useImageRenderSettings.js';
export { default as useSingleImageRender } from './useSingleImageRender.js';
export { default as useSingToScore } from './useSingToScore.js';
export * from './useSingToScore.js';
+export { default as useSongTraining } from './useSongTraining.js';
export { default as useMediaPreviewActions } from './useMediaPreviewActions.js';
export { default as useKeyboardControls } from './useKeyboardControls.js';
export { default as useMediaJobProgress } from './useMediaJobProgress.js';
diff --git a/client/src/hooks/useSongTraining.js b/client/src/hooks/useSongTraining.js
new file mode 100644
index 0000000000..bdc6a860e4
--- /dev/null
+++ b/client/src/hooks/useSongTraining.js
@@ -0,0 +1,111 @@
+// useSongTraining — drives a song training run: pick a scope (the whole song or
+// one section), count the singer in, walk that scope's notated score in tempo,
+// grade it against the live mic (reusing useColorMatch), and — when the run
+// finishes — fold the take's accuracy into the rolling progress history.
+//
+// It does NOT re-implement grading or the timing loop: useColorMatch (#1025)
+// already counts in with the metronome (#1024), walks the score, and grades each
+// note against the pitch tracker (#1022). This hook owns only the training
+// concerns layered on top: which scope is being trained (a sliced section score
+// or the whole song), looping a scope (auto-restart after a run completes), and
+// committing the finished summary to the progress aggregate via songProgress.js.
+//
+// The committed progress is surfaced through `onProgress` (the parent merges it
+// into the song draft and persists on Save) so this hook stays free of any HTTP
+// concern — same store-up-to-the-parent shape SongRecordings uses.
+
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { parseScore } from '../lib/scoreNotation.js';
+import { recordAttempt } from '../lib/songProgress.js';
+import useColorMatch from './useColorMatch.js';
+import useMounted from './useMounted.js';
+
+/**
+ * @param {object} args
+ * @param {string} args.scopeId — section id or WHOLE_SONG_SCOPE.
+ * @param {string} args.scopeScore — the lead-sheet text for the scope (a
+ * sliced section, or the full score).
+ * @param {MediaStream|null} args.stream — live mic stream to grade against.
+ * @param {number|null} [args.tempo] — BPM override (else score tempo).
+ * @param {boolean} [args.loop=false] — auto-restart the run when it finishes.
+ * @param {object} [args.progress] — current song progress aggregate.
+ * @param {(next:object)=>void} [args.onProgress] — called with the next progress
+ * aggregate after a graded run completes.
+ * @returns {{ running, countingIn, noteColors, summary, activeIndex, lastSummary,
+ * start, stop }}
+ */
+export default function useSongTraining({
+ scopeId,
+ scopeScore = '',
+ stream = null,
+ tempo = null,
+ loop = false,
+ progress = null,
+ onProgress,
+}) {
+ const parsed = useMemo(() => parseScore(scopeScore || ''), [scopeScore]);
+ const bpm = Number.isFinite(tempo) && tempo > 0 ? tempo : null;
+
+ // The most recently committed take summary — kept after the colorMatch hook
+ // resets between loop iterations, so the readout persists across a loop gap.
+ const [lastSummary, setLastSummary] = useState(null);
+
+ const mountedRef = useMounted();
+ // Latest values the completion handler reads — refs so the stable
+ // useColorMatch summary-effect below doesn't need them in its dep array
+ // (which would re-fire commit on every scope/loop change).
+ const scopeRef = useRef(scopeId);
+ const loopRef = useRef(loop);
+ const progressRef = useRef(progress);
+ const onProgressRef = useRef(onProgress);
+ useEffect(() => { scopeRef.current = scopeId; }, [scopeId]);
+ useEffect(() => { loopRef.current = loop; }, [loop]);
+ useEffect(() => { progressRef.current = progress; }, [progress]);
+ useEffect(() => { onProgressRef.current = onProgress; }, [onProgress]);
+
+ const {
+ running, countingIn, noteColors, summary, activeIndex, start: startMatch, stop,
+ } = useColorMatch({ score: parsed, stream, bpm });
+
+ // When a color-match run finishes it sets a non-null `summary` and clears
+ // `running`. That edge is the commit point: fold the take into the rolling
+ // history (songProgress drops zero-note takes itself), surface the next
+ // aggregate to the parent, and — when looping — re-arm after a short beat so
+ // the singer gets a fresh count-in. Gate on the summary identity so a single
+ // finished run commits exactly once.
+ const committedRef = useRef(null);
+ const relaunchRef = useRef(null);
+ useEffect(() => {
+ if (running || !summary || committedRef.current === summary) return;
+ committedRef.current = summary;
+ setLastSummary(summary);
+ const next = recordAttempt(progressRef.current, scopeRef.current, summary);
+ onProgressRef.current?.(next);
+ if (loopRef.current && stream) {
+ relaunchRef.current = setTimeout(() => {
+ if (mountedRef.current && loopRef.current && stream) startMatch();
+ }, 600);
+ }
+ }, [summary, running, stream, startMatch, mountedRef]);
+
+ // A new run clears the prior commit guard so its summary commits when it ends.
+ const start = useCallback(() => {
+ committedRef.current = null;
+ startMatch();
+ }, [startMatch]);
+
+ // Cancel a pending loop relaunch on stop / unmount / loop-off so a deferred
+ // restart can't fire after the user stopped (the deferred-work staleness +
+ // unmount guard from CLAUDE.md).
+ const clearRelaunch = useCallback(() => {
+ if (relaunchRef.current != null) { clearTimeout(relaunchRef.current); relaunchRef.current = null; }
+ }, []);
+ const stopTraining = useCallback(() => { clearRelaunch(); stop(); }, [clearRelaunch, stop]);
+ useEffect(() => { if (!loop) clearRelaunch(); }, [loop, clearRelaunch]);
+ useEffect(() => () => clearRelaunch(), [clearRelaunch]);
+
+ return {
+ running, countingIn, noteColors, summary, activeIndex, lastSummary,
+ start, stop: stopTraining,
+ };
+}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index f48ddf2453..9a78155b8a 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -96,5 +96,6 @@ grep -i "what you want to do" client/src/lib/README.md
| `singToScore.js` | Sing-to-score transcription for the song system — turns a sung pitch track into lead-sheet notation. `segmentPitchTrack(track, opts)` groups `[{ tMs, hz, clarity }]` frames into note/rest segments (median pitch per stable span, rests where clarity drops, sub-threshold note/rest filtering); `quantizeSegments(segments, { bpm, beatValue })` snaps each duration to the nearest grid value (w/h/q/e/s) at the song tempo; `segmentsToScoreDsl(quantized, { keySig, beatsPerBar, beatValue })` spells notes enharmonically from the key signature and emits measure-grouped `\| … \|` body text; `transcribePitchTrack(track, { bpm, key, beatsPerBar, beatValue })` runs all three. Round-trips cleanly back through `parseScore`. Reuses `frequencyToNote` (pitchDetect) + the duration/key tables (scoreNotation) — no DSP/notation library. |
| `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)`, and `rhythmShapeLabel(id)` (human-readable "Slow 4/4 ballad · dirge (56–76 BPM)" label shared by the editor's picker and read view). 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. |
+| `songProgress.js` | Pure training-progress core for the song system's memorize/learn/track mode. `deriveTrainingSections(score, lyricSections?)` slices a lead-sheet score into blank-line-separated trainable sections (each a self-contained header+block score, positional stable id, lyric-matched label); `recordAttempt(progress, scope, summary)` appends a graded take to a scope's bounded rolling history (drops zero-note takes); `scopeStats(progress, scope)`/`wholeSongStats` derive `{ attempts, best, average, last, streak, learned }` (learned = streak of ≥`LEARNED_PERCENT` takes ≥`LEARNED_STREAK`); `weakestSections(progress, sections)` ranks weak/un-attempted sections for spaced-repetition; `memorizationPercent` is the learned-section share; `hideLevelFor(average)` maps a rolling average to a progressive lyric/note-hiding level (`show`/`dim`/`hide`/`blind`). No React/audio — `useSongTraining` drives it. |
| `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 a95456197c..8217738a3d 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -63,6 +63,7 @@ export * from './scorePlayback.js';
export * from './singToScore.js';
export * from './songCraft.js';
export * from './songPlayback.js';
+export * from './songProgress.js';
export * from './universeBuilderExpand.js';
export * from './wrSceneCursor.js';
export * from './writingGuide.js';
diff --git a/client/src/lib/songProgress.js b/client/src/lib/songProgress.js
new file mode 100644
index 0000000000..9964fd8d67
--- /dev/null
+++ b/client/src/lib/songProgress.js
@@ -0,0 +1,224 @@
+// Song training progress — the pure core for the "memorize / learn / track"
+// training mode (#1028, the capstone of the #1021 song-system umbrella).
+//
+// This module is deliberately PURE (no React, no Web Audio, no notation/DSP
+// library): it slices a lead-sheet score into trainable SECTIONS, appends a
+// graded take to a rolling per-scope accuracy HISTORY, and derives the
+// memorization state (best %, rolling average, "learned" flag, weakest section)
+// the training UI surfaces. Keeping the bookkeeping here is what makes the
+// progress math unit-testable without a microphone.
+//
+// It composes the pieces already on `main` — it does NOT re-implement grading
+// (that's `colorMatch.js` / `useColorMatch`) or parsing (`scoreNotation.js`).
+// A "section" is one blank-line-separated block of the score body, which is how
+// the seeded scores already group verses/choruses; training a section just
+// feeds `useColorMatch` a score sliced to that block (header preserved), so the
+// existing grading loop is reused unchanged.
+//
+// Persistence: the aggregate lives on the song under an optional `progress`
+// field (sanitized + Zod-validated + migration-stamped server-side, same
+// discipline as #1027's per-take fields). Absent on legacy songs; it only
+// appears once the user records a training attempt.
+
+// Scope id for "the whole song" — distinct from a section id so a whole-song
+// run and a per-section run never collide in the history map. Sections key by
+// their derived `id` (sec-1, sec-2, …); the whole song keys by this sentinel.
+export const WHOLE_SONG_SCOPE = '__whole__';
+
+// How many recent attempts to keep per scope. Bounded so a long practice
+// streak can't grow the persisted record without limit; the rolling average
+// and "best" are computed over this window. Mirrors a server-side MAX so the
+// sanitizer and this client agree on the cap.
+export const HISTORY_MAX = 50;
+
+// Accuracy (% in tune) at or above which a scope is considered "learned" when
+// it also has a stable streak. A vocal take wobbles, so the bar is the same
+// 80% the color-match readout already calls "good" (green), not 100%.
+export const LEARNED_PERCENT = 80;
+// Consecutive at-or-above-threshold attempts required before a scope flips to
+// learned — one lucky take shouldn't claim mastery; the singer has to repeat it.
+export const LEARNED_STREAK = 3;
+
+// Below this rolling-average %, a section is "weak" and worth surfacing for
+// spaced-repetition practice. Sections at or above are considered solid.
+export const WEAK_PERCENT = 60;
+
+// Split a lead-sheet score into a header block (clef/key/time/tempo) and the
+// body lines, returning the body grouped into blank-line-separated BLOCKS. Each
+// block is the natural verse/chorus grouping the seeded scores already use.
+// Pure string work — no parser dependency, so a block that fails to parse still
+// slices cleanly (the grading hook tolerates parse errors per-measure).
+const splitScoreBlocks = (score) => {
+ const lines = String(score || '').replace(/\r\n?/g, '\n').split('\n');
+ const header = [];
+ const bodyLines = [];
+ let inBody = false;
+ for (const line of lines) {
+ // Header lines are `key: value` before the first measure line. Once we hit
+ // a music line (starts with `|`) we're in the body for the rest of the file.
+ if (!inBody && /^\s*\|/.test(line)) inBody = true;
+ if (inBody) bodyLines.push(line);
+ else if (/^\s*[A-Za-z]+\s*:/.test(line)) header.push(line.trim());
+ // blank lines in the header region are ignored (header has no blanks).
+ }
+ // Group body lines into blocks separated by one-or-more blank lines.
+ const blocks = [];
+ let current = [];
+ for (const line of bodyLines) {
+ if (line.trim() === '') {
+ if (current.length) { blocks.push(current); current = []; }
+ } else {
+ current.push(line);
+ }
+ }
+ if (current.length) blocks.push(current);
+ return { header: header.join('\n'), blocks };
+};
+
+// Count the measures in a block (number of `|`-delimited cells with content).
+// Used only to label a section so the user can tell them apart; a block with no
+// bars still gets a label.
+const countMeasures = (blockLines) => {
+ let count = 0;
+ for (const line of blockLines) {
+ // Each `| … |` measure adds one; split on `|` and count non-empty cells.
+ const cells = line.split('|').map((c) => c.trim()).filter(Boolean);
+ count += cells.length;
+ }
+ return count;
+};
+
+// Derive the trainable sections of a score: one per blank-line-separated block,
+// each carrying a stable id (by position), a human label, the sliced score text
+// (header + just that block, so it renders/grades on its own), and the running
+// measure offset. Returns [] when the score has no music body. When a song
+// carries lyric `sections[]`, their labels are matched positionally so a
+// training section reads "Verse 1" instead of "Section 1" — best-effort, purely
+// cosmetic (the id stays positional so history keys are stable across renames).
+export const deriveTrainingSections = (score, lyricSections = []) => {
+ const { header, blocks } = splitScoreBlocks(score);
+ if (!blocks.length) return [];
+ let measureOffset = 0;
+ return blocks.map((blockLines, i) => {
+ const measures = countMeasures(blockLines);
+ const lyricLabel = lyricSections[i]?.label;
+ const section = {
+ id: `sec-${i + 1}`,
+ index: i,
+ label: lyricLabel || `Section ${i + 1}`,
+ measures,
+ startMeasure: measureOffset,
+ // Header + this block only — a self-contained score the grading hook can
+ // build a timeline from in isolation.
+ score: header ? `${header}\n\n${blockLines.join('\n')}` : blockLines.join('\n'),
+ };
+ measureOffset += measures;
+ return section;
+ });
+};
+
+// A finite number clamped to [0,100], or 0 — used to coerce a graded percent
+// before it lands in the history.
+const clampPercent = (v) => {
+ if (typeof v !== 'number' || !Number.isFinite(v)) return 0;
+ return Math.max(0, Math.min(100, Math.round(v)));
+};
+
+// One history entry per attempt: the take's percent-in-tune, how many notes
+// were graded, and when. Bounded + minimal so the persisted record stays small.
+const makeAttempt = (summary, at) => ({
+ percentInTune: clampPercent(summary?.percentInTune),
+ graded: typeof summary?.graded === 'number' && summary.graded >= 0 ? Math.round(summary.graded) : 0,
+ at: typeof at === 'string' ? at : new Date().toISOString(),
+});
+
+// Append a graded attempt to a scope's history, returning the NEXT progress
+// object (never mutates the input — reactive-update friendly). `scope` is a
+// section id or WHOLE_SONG_SCOPE. The history is the source of truth; the
+// derived stats (best/avg/learned) are recomputed by `scopeStats` on read so a
+// threshold change can't leave a stale persisted flag. A take that graded zero
+// notes (the singer stopped before any note, or sang into silence) is ignored —
+// it carries no signal and would drag the average down spuriously.
+export const recordAttempt = (progress, scope, summary, at) => {
+ const attempt = makeAttempt(summary, at);
+ const base = progress && typeof progress === 'object' ? progress : {};
+ const history = base.history && typeof base.history === 'object' ? base.history : {};
+ if (attempt.graded <= 0) return { ...base, history };
+ const prior = Array.isArray(history[scope]) ? history[scope] : [];
+ // Newest last; keep only the most recent HISTORY_MAX so the record is bounded.
+ const next = [...prior, attempt].slice(-HISTORY_MAX);
+ return { ...base, history: { ...history, [scope]: next } };
+};
+
+// Derive the stats for one scope from its attempt history: attempt count, best
+// %, rolling average % (over the kept window), the current at-or-above-threshold
+// streak (counted from the most recent attempt backwards), and the learned flag
+// (streak ≥ LEARNED_STREAK). Pure — recomputed on every read so the displayed
+// state always reflects the current thresholds, never a stale stored boolean.
+export const scopeStats = (progress, scope) => {
+ const history = progress?.history?.[scope];
+ const attempts = Array.isArray(history) ? history : [];
+ if (!attempts.length) {
+ return { attempts: 0, best: 0, average: 0, last: 0, streak: 0, learned: false };
+ }
+ const percents = attempts.map((a) => clampPercent(a?.percentInTune));
+ const best = Math.max(...percents);
+ const average = Math.round(percents.reduce((s, p) => s + p, 0) / percents.length);
+ const last = percents[percents.length - 1];
+ let streak = 0;
+ for (let i = percents.length - 1; i >= 0; i -= 1) {
+ if (percents[i] >= LEARNED_PERCENT) streak += 1;
+ else break;
+ }
+ return { attempts: attempts.length, best, average, last, streak, learned: streak >= LEARNED_STREAK };
+};
+
+// Whole-song stats — a thin alias so callers don't pass the sentinel by hand.
+export const wholeSongStats = (progress) => scopeStats(progress, WHOLE_SONG_SCOPE);
+
+// Rank the sections weakest-first for spaced-repetition surfacing: a section is
+// scored by its rolling average (lower = weaker), with never-attempted sections
+// treated as the weakest of all (so the user is nudged to the parts they've
+// skipped). Returns the section descriptors annotated with their stats, sorted
+// ascending by average (un-attempted first, then lowest average). Only sections
+// BELOW WEAK_PERCENT (or never attempted) are returned — solid sections drop
+// off the list so it stays a focused practice queue. `sections` comes from
+// deriveTrainingSections. Pure + side-effect-free.
+export const weakestSections = (progress, sections) => {
+ return (sections || [])
+ .map((s) => ({ ...s, stats: scopeStats(progress, s.id) }))
+ .filter((s) => s.stats.attempts === 0 || s.stats.average < WEAK_PERCENT)
+ .sort((a, b) => {
+ // Never-attempted (attempts 0) sort before attempted; among attempted,
+ // lower average first.
+ if (a.stats.attempts === 0 && b.stats.attempts !== 0) return -1;
+ if (b.stats.attempts === 0 && a.stats.attempts !== 0) return 1;
+ return a.stats.average - b.stats.average;
+ });
+};
+
+// Overall memorization completion 0–100: the share of sections that are
+// `learned`, plus a partial credit for the whole-song scope being learned.
+// Simple and legible — the training view shows it as a single progress bar.
+// Returns 0 when there are no sections to learn.
+export const memorizationPercent = (progress, sections) => {
+ const list = sections || [];
+ if (!list.length) return 0;
+ const learnedCount = list.filter((s) => scopeStats(progress, s.id).learned).length;
+ return Math.round((learnedCount / list.length) * 100);
+};
+
+// Progressive lyric/note hiding: as a scope's rolling average climbs, hide more
+// of the on-screen crutches so the singer is pushed toward memory. Returns a
+// hint level the UI maps to how much to obscure: `show` (everything visible),
+// `dim` (lyrics dimmed, still legible), `hide` (lyrics hidden, notes only),
+// `blind` (notes hidden too — sing from memory). Driven off the rolling average
+// so a single good take doesn't yank the crutch away mid-practice.
+export const HIDE_LEVELS = ['show', 'dim', 'hide', 'blind'];
+export const hideLevelFor = (average) => {
+ const avg = clampPercent(average);
+ if (avg >= 95) return 'blind';
+ if (avg >= LEARNED_PERCENT) return 'hide';
+ if (avg >= WEAK_PERCENT) return 'dim';
+ return 'show';
+};
diff --git a/client/src/lib/songProgress.test.js b/client/src/lib/songProgress.test.js
new file mode 100644
index 0000000000..dbd0dbc5d2
--- /dev/null
+++ b/client/src/lib/songProgress.test.js
@@ -0,0 +1,215 @@
+import { describe, it, expect } from 'vitest';
+import {
+ WHOLE_SONG_SCOPE,
+ HISTORY_MAX,
+ LEARNED_PERCENT,
+ LEARNED_STREAK,
+ WEAK_PERCENT,
+ deriveTrainingSections,
+ recordAttempt,
+ scopeStats,
+ wholeSongStats,
+ weakestSections,
+ memorizationPercent,
+ hideLevelFor,
+} from './songProgress.js';
+
+const HEADER = ['clef: treble', 'key: G', 'time: 4/4', 'tempo: 68'].join('\n');
+const TWO_SECTION_SCORE = [
+ HEADER,
+ '',
+ '| [G] D4q(If) D4q(you) | [G] B4h(miss) |',
+ '| [Em] B4h(on) | [C] C5q(know) G4q(am) |',
+ '',
+ '| [Am7] E4h(gone) | [D7] A4q(hear) |',
+].join('\n');
+
+describe('deriveTrainingSections', () => {
+ it('splits the score body into blank-line-separated sections, header preserved', () => {
+ const sections = deriveTrainingSections(TWO_SECTION_SCORE);
+ expect(sections).toHaveLength(2);
+ // Each section's sliced score carries the header so it renders/grades alone.
+ expect(sections[0].score.startsWith(HEADER)).toBe(true);
+ expect(sections[1].score.startsWith(HEADER)).toBe(true);
+ // Positional, stable ids.
+ expect(sections.map((s) => s.id)).toEqual(['sec-1', 'sec-2']);
+ // First block: two lines of two measures each = 4; second block: 2.
+ expect(sections[0].measures).toBe(4);
+ expect(sections[1].measures).toBe(2);
+ // Running measure offset.
+ expect(sections[0].startMeasure).toBe(0);
+ expect(sections[1].startMeasure).toBe(4);
+ });
+
+ it('labels sections from matching lyric sections when provided', () => {
+ const sections = deriveTrainingSections(TWO_SECTION_SCORE, [
+ { label: 'Verse 1' }, { label: 'Chorus' },
+ ]);
+ expect(sections[0].label).toBe('Verse 1');
+ expect(sections[1].label).toBe('Chorus');
+ });
+
+ it('falls back to positional labels without lyric sections', () => {
+ const sections = deriveTrainingSections(TWO_SECTION_SCORE);
+ expect(sections[0].label).toBe('Section 1');
+ expect(sections[1].label).toBe('Section 2');
+ });
+
+ it('returns [] for a score with no music body', () => {
+ expect(deriveTrainingSections(HEADER)).toEqual([]);
+ expect(deriveTrainingSections('')).toEqual([]);
+ expect(deriveTrainingSections(null)).toEqual([]);
+ });
+
+ it('handles CRLF line endings', () => {
+ const crlf = TWO_SECTION_SCORE.replace(/\n/g, '\r\n');
+ expect(deriveTrainingSections(crlf)).toHaveLength(2);
+ });
+});
+
+describe('recordAttempt', () => {
+ it('appends a graded attempt newest-last under the scope, immutably', () => {
+ const before = { history: {} };
+ const after = recordAttempt(before, 'sec-1', { percentInTune: 90, graded: 4 });
+ expect(after).not.toBe(before);
+ expect(before.history).toEqual({}); // input untouched
+ expect(after.history['sec-1']).toHaveLength(1);
+ expect(after.history['sec-1'][0].percentInTune).toBe(90);
+ expect(after.history['sec-1'][0].graded).toBe(4);
+ expect(typeof after.history['sec-1'][0].at).toBe('string');
+ });
+
+ it('drops a zero-note take (no signal)', () => {
+ const after = recordAttempt(null, 'sec-1', { percentInTune: 0, graded: 0 });
+ expect(after.history['sec-1']).toBeUndefined();
+ });
+
+ it('clamps percent into 0..100', () => {
+ const after = recordAttempt(null, WHOLE_SONG_SCOPE, { percentInTune: 250, graded: 3 });
+ expect(after.history[WHOLE_SONG_SCOPE][0].percentInTune).toBe(100);
+ });
+
+ it('bounds the per-scope history to HISTORY_MAX (keeps the newest)', () => {
+ let p = null;
+ for (let i = 0; i < HISTORY_MAX + 10; i += 1) {
+ p = recordAttempt(p, 'sec-1', { percentInTune: i % 100, graded: 2 });
+ }
+ expect(p.history['sec-1']).toHaveLength(HISTORY_MAX);
+ // Last appended wins the tail.
+ const lastPct = (HISTORY_MAX + 9) % 100;
+ expect(p.history['sec-1'][HISTORY_MAX - 1].percentInTune).toBe(lastPct);
+ });
+});
+
+describe('scopeStats', () => {
+ it('returns a zeroed shape for an un-attempted scope', () => {
+ expect(scopeStats({ history: {} }, 'sec-1')).toEqual({
+ attempts: 0, best: 0, average: 0, last: 0, streak: 0, learned: false,
+ });
+ expect(scopeStats(null, 'sec-1').attempts).toBe(0);
+ });
+
+ it('computes best, average, last from history', () => {
+ let p = null;
+ p = recordAttempt(p, 'sec-1', { percentInTune: 40, graded: 5 });
+ p = recordAttempt(p, 'sec-1', { percentInTune: 90, graded: 5 });
+ p = recordAttempt(p, 'sec-1', { percentInTune: 50, graded: 5 });
+ const st = scopeStats(p, 'sec-1');
+ expect(st.attempts).toBe(3);
+ expect(st.best).toBe(90);
+ expect(st.average).toBe(60); // (40+90+50)/3
+ expect(st.last).toBe(50);
+ });
+
+ it('flips learned after a streak of LEARNED_STREAK takes at/above threshold', () => {
+ let p = null;
+ // One below-threshold then a fresh streak — streak counts from the newest back.
+ p = recordAttempt(p, 'sec-1', { percentInTune: 50, graded: 5 });
+ for (let i = 0; i < LEARNED_STREAK - 1; i += 1) {
+ p = recordAttempt(p, 'sec-1', { percentInTune: LEARNED_PERCENT + 5, graded: 5 });
+ }
+ expect(scopeStats(p, 'sec-1').learned).toBe(false); // one short of the streak
+ p = recordAttempt(p, 'sec-1', { percentInTune: LEARNED_PERCENT, graded: 5 });
+ const st = scopeStats(p, 'sec-1');
+ expect(st.streak).toBe(LEARNED_STREAK);
+ expect(st.learned).toBe(true);
+ });
+
+ it('a below-threshold take breaks the streak (learned drops)', () => {
+ let p = null;
+ for (let i = 0; i < LEARNED_STREAK; i += 1) {
+ p = recordAttempt(p, 'sec-1', { percentInTune: 95, graded: 5 });
+ }
+ expect(scopeStats(p, 'sec-1').learned).toBe(true);
+ p = recordAttempt(p, 'sec-1', { percentInTune: 40, graded: 5 });
+ const st = scopeStats(p, 'sec-1');
+ expect(st.streak).toBe(0);
+ expect(st.learned).toBe(false);
+ });
+
+ it('wholeSongStats reads the whole-song sentinel scope', () => {
+ const p = recordAttempt(null, WHOLE_SONG_SCOPE, { percentInTune: 70, graded: 8 });
+ expect(wholeSongStats(p).attempts).toBe(1);
+ expect(wholeSongStats(p).best).toBe(70);
+ });
+});
+
+describe('weakestSections', () => {
+ const sections = [
+ { id: 'sec-1', label: 'A' },
+ { id: 'sec-2', label: 'B' },
+ { id: 'sec-3', label: 'C' },
+ ];
+
+ it('surfaces un-attempted sections first, then lowest average', () => {
+ let p = null;
+ // sec-1 solid, sec-2 weak, sec-3 never attempted.
+ p = recordAttempt(p, 'sec-1', { percentInTune: 95, graded: 5 });
+ p = recordAttempt(p, 'sec-2', { percentInTune: 30, graded: 5 });
+ const weak = weakestSections(p, sections);
+ // sec-1 is solid (≥ WEAK_PERCENT) so it drops off.
+ expect(weak.map((s) => s.id)).toEqual(['sec-3', 'sec-2']);
+ expect(weak[0].stats.attempts).toBe(0); // never-attempted first
+ });
+
+ it('omits sections at or above WEAK_PERCENT', () => {
+ const p = recordAttempt(
+ recordAttempt(recordAttempt(null, 'sec-1', { percentInTune: WEAK_PERCENT, graded: 5 }),
+ 'sec-2', { percentInTune: WEAK_PERCENT, graded: 5 }),
+ 'sec-3', { percentInTune: WEAK_PERCENT, graded: 5 },
+ );
+ expect(weakestSections(p, sections)).toEqual([]);
+ });
+});
+
+describe('memorizationPercent', () => {
+ const sections = [{ id: 'sec-1' }, { id: 'sec-2' }];
+
+ it('is the share of learned sections', () => {
+ let p = null;
+ expect(memorizationPercent(p, sections)).toBe(0);
+ for (let i = 0; i < LEARNED_STREAK; i += 1) {
+ p = recordAttempt(p, 'sec-1', { percentInTune: 95, graded: 5 });
+ }
+ expect(memorizationPercent(p, sections)).toBe(50); // 1 of 2 learned
+ });
+
+ it('is 0 with no sections', () => {
+ expect(memorizationPercent({ history: {} }, [])).toBe(0);
+ });
+});
+
+describe('hideLevelFor', () => {
+ it('maps the rolling average to a progressive hiding level', () => {
+ expect(hideLevelFor(0)).toBe('show');
+ expect(hideLevelFor(WEAK_PERCENT)).toBe('dim');
+ expect(hideLevelFor(LEARNED_PERCENT)).toBe('hide');
+ expect(hideLevelFor(95)).toBe('blind');
+ expect(hideLevelFor(100)).toBe('blind');
+ });
+
+ it('treats invalid input as the lowest level', () => {
+ expect(hideLevelFor(NaN)).toBe('show');
+ expect(hideLevelFor(null)).toBe('show');
+ });
+});
diff --git a/client/src/pages/SongEditor.jsx b/client/src/pages/SongEditor.jsx
index 4ed52769a0..92858d38e7 100644
--- a/client/src/pages/SongEditor.jsx
+++ b/client/src/pages/SongEditor.jsx
@@ -35,6 +35,7 @@ import { RHYTHM_SHAPES, VOICE_LAYERS, rhythmShapeLabel } from '../lib/songCraft'
import Pill from '../components/ui/Pill';
import SongAiPanel from '../components/songs/SongAiPanel';
import SongRecordings from '../components/songs/SongRecordings';
+import SongTraining from '../components/songs/SongTraining';
import SongScoreEditor from '../components/songs/SongScoreEditor';
import SongScoreParts from '../components/songs/SongScoreParts';
import ScoreSheet from '../components/songs/ScoreSheet';
@@ -195,6 +196,7 @@ export default function SongEditor() {
title: song.title, artist: song.artist, key: song.key,
tempo: song.tempo ?? null, rhythmShapeId: song.rhythmShapeId,
notation: song.notation, score: song.score, notes: song.notes, learned: song.learned,
+ progress: song.progress ?? null,
// Strip in-session temp ids so the server assigns stable uuids — keeps
// them from being persisted and later colliding after a reload.
sections: (song.sections || []).map(stripTempId),
@@ -584,6 +586,15 @@ export default function SongEditor() {
onChange={(recordings) => setField('recordings', recordings)}
/>
+ {/* Training — practice loop, scoring, and learned-progress tracking */}
+ <SongTraining
+ score={song.score}
+ lyricSections={song.sections || []}
+ tempo={song.tempo ?? null}
+ progress={song.progress ?? null}
+ onProgress={(progress) => setField('progress', progress)}
+ />
+
{/* Reference material — links / videos (TikTok embeds in read view) */}
<section>
<div className="flex items-center justify-between mb-2">
@@ -769,6 +780,18 @@ function ReadView({ song, setField, onRefreshTemplate, refreshing, partnerSongs
onChange={(recordings) => setField('recordings', recordings)}
/>
+ {/* Training — practice & memorize against the score, tracking progress.
+ Hidden while the round stack is open (the stack is its own surface). */}
+ {!showingStack && (
+ <SongTraining
+ score={song.score}
+ lyricSections={song.sections || []}
+ tempo={song.tempo ?? null}
+ progress={song.progress ?? null}
+ onProgress={(progress) => setField('progress', progress)}
+ />
+ )}
+
{!showingStack && (
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Lyrics — the main reading surface, given the most width. */}
diff --git a/scripts/migrations/079-song-training-progress.js b/scripts/migrations/079-song-training-progress.js
new file mode 100644
index 0000000000..88f7a71a00
--- /dev/null
+++ b/scripts/migrations/079-song-training-progress.js
@@ -0,0 +1,29 @@
+/**
+ * Registration stub for song training progress (#1028 — the capstone of the
+ * #1021 song-system umbrella).
+ *
+ * The song shape (`server/services/songs.js`) gained one OPTIONAL,
+ * absent-tolerant field — `progress` (`{ history: { <scope>: [attempt…] } }`),
+ * a bounded per-scope rolling accuracy history for the memorize/learn/track
+ * training mode. It's additive: a legacy song simply has no `progress` field,
+ * the sanitizer reads it back unchanged, and the Zod schema treats it as
+ * optional, so an older client's payload (no training data) still validates.
+ *
+ * Because the change is purely additive and the read path is absent-tolerant,
+ * there is no on-disk data to rewrite — existing `data/songs.json` records load
+ * as-is and gain the field only when the user records a training attempt. This
+ * stub ships anyway so the schema bump is RECORDED in
+ * `data/migrations.applied.json`: the distribution model is many installs
+ * upgrading independently (CLAUDE.md → Distribution model), and a recorded
+ * migration is the audit trail showing when the training-progress shape was
+ * introduced.
+ *
+ * No-op + idempotent: nothing to rewrite in the file runner.
+ */
+
+export default {
+ async up() {
+ console.log('🎓 migration 079: song training-progress field is additive/absent-tolerant; nothing to rewrite — recording the schema bump.');
+ return { updated: 0, reason: 'additive-no-op' };
+ },
+};
diff --git a/scripts/migrations/079-song-training-progress.test.js b/scripts/migrations/079-song-training-progress.test.js
new file mode 100644
index 0000000000..7b862869e3
--- /dev/null
+++ b/scripts/migrations/079-song-training-progress.test.js
@@ -0,0 +1,15 @@
+import { describe, it, expect } from 'vitest';
+import migration from './079-song-training-progress.js';
+
+describe('migration 079 — song training-progress registration stub', () => {
+ it('is a no-op that records the additive schema bump', async () => {
+ const result = await migration.up({ rootDir: '/tmp/nonexistent' });
+ expect(result).toEqual({ updated: 0, reason: 'additive-no-op' });
+ });
+
+ it('is idempotent (re-running changes nothing)', async () => {
+ const first = await migration.up({ rootDir: '/tmp/nonexistent' });
+ const second = await migration.up({ rootDir: '/tmp/nonexistent' });
+ expect(second).toEqual(first);
+ });
+});
diff --git a/server/routes/songs.js b/server/routes/songs.js
index b52502f362..ec1ed0ed21 100644
--- a/server/routes/songs.js
+++ b/server/routes/songs.js
@@ -80,6 +80,23 @@ const recordingSchema = z.object({
accuracy: accuracySchema.optional(),
});
+// One training attempt — a graded take of one scope (#1028). The service clamps
+// the percent and drops zero-note attempts; the schema only types the fields.
+const attemptSchema = z.object({
+ percentInTune: z.number().optional(),
+ graded: z.number().optional(),
+ at: z.string().optional(),
+});
+
+// Training progress (#1028): `{ history: { <scope>: [attempt…] } }`. A record
+// of the scope → recent graded attempts; the service bounds both the per-scope
+// history and the number of scopes, and recomputes derived stats client-side.
+// `.passthrough()` is NOT used — only `history` is meaningful, and the service
+// re-sanitizes regardless, but typing it keeps the contract explicit.
+const progressSchema = z.object({
+ history: z.record(z.string(), z.array(attemptSchema).max(svc.PROGRESS_HISTORY_MAX)).optional(),
+}).optional();
+
// A sheet-music part — a harmony variation of the base score, in the same
// lead-sheet DSL. `score` is required (a part without notation is meaningless);
// `role` is a HARMONY_PARTS id when known but free-text-safe.
@@ -120,6 +137,9 @@ const songInputSchema = z.object({
scoreParts: z.array(scorePartSchema).max(svc.SCORE_PARTS_MAX).optional(),
notes: str(svc.FIELD_MAX_LENGTH).optional(),
learned: z.boolean().optional(),
+ // Training progress (#1028) — per-scope rolling accuracy history. Optional and
+ // absent-tolerant: a legacy/untrained song omits it; the service bounds + clamps.
+ progress: progressSchema,
sections: z.array(sectionSchema).max(svc.SECTIONS_MAX).optional(),
layers: z.array(layerSchema).max(svc.LAYERS_MAX).optional(),
recordings: z.array(recordingSchema).max(svc.RECORDINGS_MAX).optional(),
diff --git a/server/services/songs.js b/server/services/songs.js
index 3c9c0e5179..9d43583540 100644
--- a/server/services/songs.js
+++ b/server/services/songs.js
@@ -57,6 +57,13 @@ export const URL_MAX_LENGTH = 512; // uploaded-file path/url
// be arbitrarily long.
export const PITCH_TRACK_MAX = 4000; // downsampled tuner samples per take
export const PER_NOTE_GRADES_MAX = 2000; // per-note color-match grades per take
+// Training progress (#1028). `progress.history` maps a training scope (a
+// section id or the whole-song sentinel) to a bounded array of graded attempts.
+// Mirrors client/src/lib/songProgress.js HISTORY_MAX (kept window per scope) and
+// caps the number of distinct scopes so a hand-edited file can't balloon the
+// record. An attempt is `{ percentInTune, graded, at }`.
+export const PROGRESS_HISTORY_MAX = 50; // attempts kept per scope
+export const PROGRESS_SCOPES_MAX = 80; // distinct training scopes tracked
// Valid color-match grades — mirrors client/src/lib/colorMatch.js GRADE. An
// unrecognized grade is dropped (a newer/older client vocabulary can't 400 or
// poison the persisted array).
@@ -153,6 +160,46 @@ const sanitizeAccuracy = (a) => {
};
};
+// One training attempt ({ percentInTune, graded, at }) — a graded take of one
+// scope (a section or the whole song). Numbers are clamped; an attempt with no
+// graded notes carries no signal and is dropped (mirrors songProgress.js, which
+// never records a zero-note take). Returns null for a shapeless/empty attempt.
+const sanitizeAttempt = (a) => {
+ if (!a || typeof a !== 'object') return null;
+ const graded = finiteOrNull(a.graded);
+ if (graded === null || graded <= 0) return null;
+ const pct = finiteOrNull(a.percentInTune);
+ return {
+ percentInTune: pct === null ? 0 : Math.max(0, Math.min(100, Math.round(pct))),
+ graded: Math.max(0, Math.round(graded)),
+ at: typeof a.at === 'string' ? a.at : new Date().toISOString(),
+ };
+};
+
+// Training progress (#1028): `{ history: { <scope>: [attempt…] } }`. Each scope
+// (a section id or the whole-song sentinel) keys a bounded, newest-last attempt
+// list. Absent on legacy/untrained songs — returns null when there's nothing to
+// persist so the field stays off the record (no wave of empty objects). The
+// number of scopes and the per-scope history are both bounded so a hand-edited
+// file can't grow the record without limit. Derived stats (best/avg/learned)
+// are recomputed client-side from this history on read, never stored.
+const sanitizeProgress = (p) => {
+ if (!p || typeof p !== 'object') return null;
+ const rawHistory = p.history && typeof p.history === 'object' ? p.history : {};
+ const history = {};
+ let scopeCount = 0;
+ for (const [scope, attempts] of Object.entries(rawHistory)) {
+ if (scopeCount >= PROGRESS_SCOPES_MAX) break;
+ const key = trimField(scope, ID_MAX_LENGTH);
+ if (!key) continue;
+ const cleaned = sanitizeList(attempts, sanitizeAttempt, PROGRESS_HISTORY_MAX);
+ if (!cleaned.length) continue;
+ history[key] = cleaned;
+ scopeCount += 1;
+ }
+ return Object.keys(history).length ? { history } : null;
+};
+
// 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.
@@ -259,7 +306,7 @@ export const sanitizeSong = (raw) => {
if (!raw || typeof raw !== 'object') return null;
const id = trimField(raw.id, ID_MAX_LENGTH);
if (!id) return null;
- return {
+ const song = {
id,
title: trimField(raw.title, TITLE_MAX_LENGTH) || 'Untitled song',
artist: trimField(raw.artist, ARTIST_MAX_LENGTH),
@@ -291,6 +338,12 @@ export const sanitizeSong = (raw) => {
createdAt: typeof raw.createdAt === 'string' ? raw.createdAt : new Date().toISOString(),
updatedAt: typeof raw.updatedAt === 'string' ? raw.updatedAt : new Date().toISOString(),
};
+ // Training progress (#1028). Absent ⇒ omit (legacy/untrained song); present ⇒
+ // attach the bounded per-scope attempt history. Keeping the key off the record
+ // when there's no progress avoids an empty husk on every untrained song.
+ const progress = sanitizeProgress(raw.progress);
+ if (progress) song.progress = progress;
+ return song;
};
// Worked-example harmony stack for the built-in "500 Miles" — the chord-tone
@@ -698,7 +751,7 @@ export async function updateSong(id, patch) {
// Merge field-by-field so an absent key preserves the stored value while a
// present key (including empty string / empty array) applies the change.
const merged = { ...songs[idx] };
- for (const key of ['title', 'artist', 'key', 'tempo', 'rhythmShapeId', 'notation', 'score', 'scoreParts', 'notes', 'learned', 'sections', 'layers', 'recordings', 'references', 'partnerSongIds']) {
+ for (const key of ['title', 'artist', 'key', 'tempo', 'rhythmShapeId', 'notation', 'score', 'scoreParts', 'notes', 'learned', 'progress', 'sections', 'layers', 'recordings', 'references', 'partnerSongIds']) {
if (key in patch) merged[key] = patch[key];
}
merged.id = id;
@@ -736,6 +789,9 @@ export async function refreshSongFromTemplate(id) {
...template,
id,
learned: existing.learned,
+ // Preserve the user's training progress — it's their practice record, not
+ // the template's to reset (mirrors keeping `learned` + `recordings`).
+ progress: existing.progress,
recordings,
createdAt: existing.createdAt,
updatedAt: new Date().toISOString(),
diff --git a/server/services/songs.test.js b/server/services/songs.test.js
index 1db318ba0e..8d2caffc68 100644
--- a/server/services/songs.test.js
+++ b/server/services/songs.test.js
@@ -226,6 +226,66 @@ describe('songs service', () => {
expect(song.recordings[0]).not.toHaveProperty('accuracy');
});
+ // --- Training progress (#1028) -----------------------------------------
+ it('legacy/untrained songs load with no progress key', () => {
+ expect(svc.sanitizeSong({ id: 'x' })).not.toHaveProperty('progress');
+ // An empty history object is nothing to persist → omit.
+ expect(svc.sanitizeSong({ id: 'x', progress: { history: {} } })).not.toHaveProperty('progress');
+ });
+
+ it('persists a per-scope training history, clamping percent and dropping zero-note attempts', () => {
+ const song = svc.sanitizeSong({
+ id: 'x',
+ progress: {
+ history: {
+ '__whole__': [
+ { percentInTune: 250, graded: 6, at: '2026-06-08T00:00:00.000Z' }, // clamped to 100
+ { percentInTune: 50, graded: 0 }, // zero-note → dropped
+ ],
+ 'sec-1': [{ percentInTune: 80, graded: 4 }],
+ },
+ },
+ });
+ expect(song.progress.history['__whole__']).toHaveLength(1);
+ expect(song.progress.history['__whole__'][0].percentInTune).toBe(100);
+ expect(song.progress.history['sec-1'][0].graded).toBe(4);
+ });
+
+ it('drops a scope whose attempts all fail sanitization', () => {
+ const song = svc.sanitizeSong({
+ id: 'x',
+ progress: { history: { 'sec-1': [{ percentInTune: 90, graded: 0 }], 'sec-2': [{ percentInTune: 70, graded: 3 }] } },
+ });
+ expect(song.progress.history).not.toHaveProperty('sec-1');
+ expect(song.progress.history['sec-2']).toHaveLength(1);
+ });
+
+ it('clamps an oversized per-scope history to PROGRESS_HISTORY_MAX', () => {
+ const attempts = Array.from({ length: svc.PROGRESS_HISTORY_MAX + 20 }, () => ({ percentInTune: 80, graded: 3 }));
+ const song = svc.sanitizeSong({ id: 'x', progress: { history: { 'sec-1': attempts } } });
+ expect(song.progress.history['sec-1']).toHaveLength(svc.PROGRESS_HISTORY_MAX);
+ });
+
+ it('updateSong merges progress and preserves it across an unrelated edit', async () => {
+ await svc.listSongs();
+ const created = await svc.createSong({ title: 'Practice me' });
+ const withProgress = await svc.updateSong(created.id, {
+ progress: { history: { '__whole__': [{ percentInTune: 85, graded: 5 }] } },
+ });
+ expect(withProgress.progress.history['__whole__']).toHaveLength(1);
+ // A later edit that doesn't touch progress keeps it (absent key preserves).
+ const renamed = await svc.updateSong(created.id, { title: 'Renamed' });
+ expect(renamed.progress.history['__whole__']).toHaveLength(1);
+ });
+
+ it('refreshSongFromTemplate preserves the user training progress', async () => {
+ await svc.listSongs();
+ const seedId = [...svc.BUILTIN_SONG_IDS][0];
+ await svc.updateSong(seedId, { progress: { history: { 'sec-1': [{ percentInTune: 90, graded: 4 }] } } });
+ const refreshed = await svc.refreshSongFromTemplate(seedId);
+ expect(refreshed.progress.history['sec-1']).toHaveLength(1);
+ });
+
it('stamps builtIn from the seed-id set, ignoring the raw value', () => {
const seedId = [...svc.BUILTIN_SONG_IDS][0];
expect(svc.sanitizeSong({ id: seedId }).builtIn).toBe(true);