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: add sing-to-verify score correction (#3239)
[._.]/ Adam Eivy0cdc657304a0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 29100e603f..5d32218f40 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -66,6 +66,8 @@## Rounds+- **[issue-3239] Sing your own version of any round into its existing sheet music.** Choose a starting bar, get a one-bar count-in, then compare the written and sung pitches note by note on the staff. Nothing changes automatically: accept only the sung notes you want, and PortOS preserves every duration, chord, lyric, line break, and space around those pitch corrections when you commit them.+- **[issue-3238] "Hey Ho Nobody Home" now has all four of its lines — and the right words for the last one.** The built-in round printed four lines of lyrics but only ever notated three: the closing line had no notes to sing it on, so the words and the sheet music disagreed. That line was wrong too, repeating the opening ("Hey, ho, nobody home.") instead of the way it is actually sung — **"Hey, hey, ho."** It now has its own two bars, cadencing down onto the note the round is centred on, plus the fourth entering voice the round always described but could not support. That also puts it back in step with Ah Poor Bird and Rose Rose Rose Red: at three phrases it was a quarter shorter than both, so the three-round quodlibet drifted out of alignment every few times round. If you have edited your copy of the round, your version is left exactly as you wrote it.## Quota burndiff --git a/client/src/components/songs/SingToVerify.jsx b/client/src/components/songs/SingToVerify.jsxnew file mode 100644index 0000000000..87a6f58e28--- /dev/null+++ b/client/src/components/songs/SingToVerify.jsx@@ -0,0 +1,207 @@+import { useEffect, useMemo, useState } from 'react';+import { Check, Mic, RotateCcw, Square } from 'lucide-react';+import useSingToVerify, {+ VERIFY_COUNT_IN,+ VERIFY_IDLE,+ VERIFY_RECORDING,+} from '../../hooks/useSingToVerify.js';+import { GRADE } from '../../lib/colorMatch.js';+import { parseScore, replaceNotePitch } from '../../lib/scoreNotation.js';+import ScoreSheet from './ScoreSheet.jsx';++const pitchLabel = (pitch) =>+ pitch ? `${pitch.letter}${pitch.accidental || ''}${pitch.octave}` : '—';++export default function SingToVerify({ value = '', tempo = null, onChange }) {+ const score = useMemo(() => parseScore(value), [value]);+ const [startBar, setStartBar] = useState(1);+ const [activeIndex, setActiveIndex] = useState(null);+ const {+ phase,+ beat,+ rows,+ error,+ start,+ stop,+ reset,+ toggleAccept,+ acceptAll,+ } = useSingToVerify({ score: value, tempo });++ const recording = phase !== VERIFY_IDLE;+ const measureCount = Math.max(1, score.measures.length);+ const noteColors = useMemo(+ () => Object.fromEntries(rows+ .filter((row) => row.grade !== GRADE.PENDING)+ .map((row) => [row.index, row.grade])),+ [rows],+ );+ const acceptedCount = rows.filter((row) => row.accepted && row.sung).length;++ // Parsed source spans belong to the exact score text captured. If the user+ // edits the textarea before committing, discard the stale comparison instead+ // of letting it target a different token.+ useEffect(() => {+ reset();+ setActiveIndex(null);+ }, [value, reset]);++ const commit = () => {+ const accepted = rows+ .filter((row) => row.accepted && row.sung)+ .sort((a, b) => b.note.start - a.note.start);+ if (!accepted.length) return;+ const next = accepted.reduce(+ (text, row) => replaceNotePitch(text, row.note, pitchLabel(row.sung)),+ value,+ );+ onChange?.(next);+ reset();+ setActiveIndex(null);+ };++ return (+ <div className="bg-port-card border border-port-border rounded-lg p-3">+ <div className="flex items-end justify-between gap-3 flex-wrap">+ <div>+ <h3 className="flex items-center gap-2 text-sm font-semibold text-white">+ <Mic size={15} className="text-port-accent" /> Sing to verify+ {phase === VERIFY_COUNT_IN && (+ <span className="text-xs font-normal text-port-warning">● count-in {beat ?? ''}</span>+ )}+ {phase === VERIFY_RECORDING && (+ <span className="text-xs font-normal text-port-error">● singing… beat {beat ?? ''}</span>+ )}+ </h3>+ <p className="text-xs text-gray-500 mt-1">+ Sing the written melody, compare each pitch, then choose which sung notes become part of the score.+ </p>+ </div>++ <div className="flex items-end gap-2 flex-wrap">+ <div>+ <label htmlFor="sing-to-verify-start-bar" className="block text-xs text-gray-400 mb-1">+ Start bar+ </label>+ <select+ id="sing-to-verify-start-bar"+ value={Math.min(startBar, measureCount)}+ onChange={(event) => setStartBar(Number(event.target.value))}+ disabled={recording}+ className="bg-port-bg border border-port-border rounded-lg px-2.5 py-1.5 text-xs text-white focus:border-port-accent focus:outline-none disabled:opacity-50"+ >+ {Array.from({ length: measureCount }, (_, index) => (+ <option key={index + 1} value={index + 1}>Bar {index + 1}</option>+ ))}+ </select>+ </div>+ {recording ? (+ <button+ type="button"+ onClick={stop}+ 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={() => start(startBar)}+ disabled={!score.measures.some((measure) => measure.notes.some((note) => !note.rest))}+ 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-40"+ >+ <Mic size={14} /> Sing+ </button>+ )}+ </div>+ </div>++ {error && <p className="mt-2 text-xs text-port-error">{error}</p>}++ {rows.length > 0 && !recording && (+ <div className="mt-3 space-y-3">+ <div className="bg-port-bg border border-port-border rounded-lg p-3 overflow-x-auto">+ <ScoreSheet+ text={value}+ controls={false}+ noteColors={noteColors}+ activeNoteIndex={activeIndex}+ />+ </div>++ <div className="flex items-center justify-between gap-2 flex-wrap">+ <p className="text-xs text-gray-400">+ {acceptedCount} of {rows.filter((row) => row.sung).length} detected notes accepted+ </p>+ <div className="flex items-center gap-2 flex-wrap">+ <button+ type="button"+ onClick={acceptAll}+ disabled={!rows.some((row) => row.sung)}+ className="px-2.5 py-1.5 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white disabled:opacity-40"+ >+ Accept all sung+ </button>+ <button+ type="button"+ onClick={commit}+ disabled={acceptedCount === 0}+ 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-40"+ >+ <Check size={14} /> Commit accepted notes+ </button>+ <button+ type="button"+ onClick={() => { reset(); setActiveIndex(null); }}+ className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg text-gray-400 hover:text-white"+ >+ <RotateCcw size={14} /> Reset+ </button>+ </div>+ </div>++ <div className="grid gap-2 sm:grid-cols-2">+ {rows.map((row) => {+ const canAccept = !!row.sung;+ const cents = row.cents == null ? 'no clear pitch' : `${row.cents >= 0 ? '+' : ''}${Math.round(row.cents)}¢`;+ return (+ <div+ key={row.index}+ className={`flex items-center justify-between gap-3 rounded-lg border p-2.5 ${+ activeIndex === row.index ? 'border-port-accent bg-port-accent/10' : 'border-port-border bg-port-bg'+ }`}+ onMouseEnter={() => setActiveIndex(row.index)}+ onFocus={() => setActiveIndex(row.index)}+ >+ <button+ type="button"+ onClick={() => setActiveIndex(row.index)}+ className="min-w-0 text-left"+ >+ <span className="block text-sm text-white">+ {pitchLabel(row.written)} <span className="text-gray-500">→</span> {pitchLabel(row.sung)}+ </span>+ <span className="block text-xs text-gray-500">{cents} · {row.grade}</span>+ </button>+ <button+ type="button"+ onClick={() => toggleAccept(row.index)}+ disabled={!canAccept}+ aria-pressed={row.accepted}+ className={`shrink-0 px-2.5 py-1.5 text-xs rounded-lg border disabled:opacity-40 ${+ row.accepted+ ? 'border-port-accent bg-port-accent text-white'+ : 'border-port-border text-gray-300 hover:text-white'+ }`}+ >+ {row.accepted ? 'Keep written' : 'Accept sung'}+ </button>+ </div>+ );+ })}+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/songs/SingToVerify.test.jsx b/client/src/components/songs/SingToVerify.test.jsxnew file mode 100644index 0000000000..a63fbbeafe--- /dev/null+++ b/client/src/components/songs/SingToVerify.test.jsx@@ -0,0 +1,105 @@+import { fireEvent, render, screen } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { parseScore } from '../../lib/scoreNotation.js';++const start = vi.fn();+const stop = vi.fn();+const reset = vi.fn();+const toggleAccept = vi.fn();+const acceptAll = vi.fn();+let hookState = { phase: 'idle', beat: null, rows: [], error: null };++vi.mock('../../hooks/useSingToVerify.js', () => ({+ __esModule: true,+ default: () => ({ ...hookState, start, stop, reset, toggleAccept, acceptAll }),+ VERIFY_IDLE: 'idle',+ VERIFY_COUNT_IN: 'countIn',+ VERIFY_RECORDING: 'recording',+}));++vi.mock('./ScoreSheet.jsx', () => ({+ default: ({ activeNoteIndex }) => <div data-testid="score-sheet" data-active={activeNoteIndex ?? ''} />,+}));++import SingToVerify from './SingToVerify.jsx';++const value = 'key: C\ntime: 4/4\n| C4q D4q |';+const parsedNotes = parseScore(value).measures[0].notes;++describe('SingToVerify', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ hookState = { phase: 'idle', beat: null, rows: [], error: null };+ });++ it('starts at the selected bar and stops an active capture', () => {+ const { rerender } = render(<SingToVerify value={`${value}\n| E4q |`} tempo={120} />);+ fireEvent.change(screen.getByLabelText(/start bar/i), { target: { value: '2' } });+ fireEvent.click(screen.getByRole('button', { name: /^sing$/i }));+ expect(start).toHaveBeenCalledWith(2);++ hookState = { ...hookState, phase: 'recording', beat: 1 };+ rerender(<SingToVerify value={`${value}\n| E4q |`} tempo={120} />);+ fireEvent.click(screen.getByRole('button', { name: /stop/i }));+ expect(stop).toHaveBeenCalled();+ });++ it('toggles one written-to-sung row between accept and keep', () => {+ hookState = {+ phase: 'idle',+ beat: null,+ error: null,+ rows: [{+ index: 0,+ note: parsedNotes[0],+ written: { letter: 'C', accidental: '', octave: 4 },+ sung: { letter: 'D', accidental: 'b', octave: 4 },+ cents: 100,+ grade: 'off',+ accepted: false,+ }],+ };+ const { rerender } = render(<SingToVerify value={value} tempo={120} />);+ fireEvent.click(screen.getByRole('button', { name: /accept sung/i }));+ expect(toggleAccept).toHaveBeenCalledWith(0);++ hookState = { ...hookState, rows: [{ ...hookState.rows[0], accepted: true }] };+ rerender(<SingToVerify value={value} tempo={120} />);+ fireEvent.click(screen.getByRole('button', { name: /keep written/i }));+ expect(toggleAccept).toHaveBeenLastCalledWith(0);+ });++ it('commits only accepted pitches through onChange', () => {+ const onChange = vi.fn();+ hookState = {+ phase: 'idle',+ beat: null,+ error: null,+ rows: [+ {+ index: 0,+ note: parsedNotes[0],+ written: { letter: 'C', accidental: '', octave: 4 },+ sung: { letter: 'F', accidental: '#', octave: 4 },+ cents: 600,+ grade: 'off',+ accepted: true,+ },+ {+ index: 1,+ note: parsedNotes[1],+ written: { letter: 'D', accidental: '', octave: 4 },+ sung: { letter: 'E', accidental: '', octave: 4 },+ cents: 200,+ grade: 'off',+ accepted: false,+ },+ ],+ };+ render(<SingToVerify value={value} tempo={120} onChange={onChange} />);+ fireEvent.click(screen.getByRole('button', { name: /commit accepted notes/i }));+ expect(onChange).toHaveBeenCalledWith('key: C\ntime: 4/4\n| F#4q D4q |');+ expect(reset).toHaveBeenCalled();+ });+});+diff --git a/client/src/components/songs/SongScoreEditor.jsx b/client/src/components/songs/SongScoreEditor.jsxindex 2dbe4f378f..56236f8ac0 100644--- a/client/src/components/songs/SongScoreEditor.jsx+++ b/client/src/components/songs/SongScoreEditor.jsx@@ -16,6 +16,7 @@ import { useCallback, useMemo, useRef, useState } from 'react';import { Music, ChevronDown, ChevronRight, AlertTriangle } from 'lucide-react';import ScoreSheet from './ScoreSheet.jsx';import SingToScore from './SingToScore.jsx';+import SingToVerify from './SingToVerify.jsx';import { parseScore } from '../../lib/scoreNotation.js';const PLACEHOLDER = `clef: treble@@ -117,7 +118,7 @@ export default function SongScoreEditor({ value, onChange }) {/>{/* Sing a melody → transcribe it into the notation above. */}- <div className="mt-3">+ <div className="mt-3 grid gap-3 xl:grid-cols-2"><SingToScorevalue={value || ''}tempo={score.tempo}@@ -125,6 +126,11 @@ export default function SongScoreEditor({ value, onChange }) {hasSelection={hasSelection}onInsert={insertNotation}/>+ <SingToVerify+ value={value || ''}+ tempo={score.tempo}+ onChange={onChange}+ /></div>{/* Parse feedback — beat mismatches and unrecognized tokens. */}diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 420a9e772e..489b7bc4bb 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -158,6 +158,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useVisionModelIds` | `{ idsByProvider, loaded }` — vision-capable model ids the server reports (Ollama `/api/show` + LM Studio `type:'vlm'`), keyed by the provider id that serves them (`{ ollama: Set, lmstudio: Set }`), `null` until fetched; `loaded` flips once the fetch settles. Drops `backend:'cli'` rows (a blanket per-provider claim, not a per-model fact) and never vouches for a provider the server didn't enumerate. | Any VISION model picker — pass `idsByProvider` to `visionLocalModelFilter` / `assignmentModelOptions` so a new multimodal family (`gemma4`) isn't hidden by the stale client id regex, and so an installed VLM shows even when the provider's stored `models` snapshot is stale; gate any "none installed" messaging on `loaded` and on the provider being a local backend. || `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. |+| `useSingToVerify` | Captures a singer from a selected score bar after a one-bar count-in, aligns the pitch track to written-note windows, and exposes `{ phase, beat, rows, error, start, stop, reset, toggleAccept, acceptAll }` for explicit note-by-note correction. Tears down mic/analyser/tracker/metronome on stop and unmount. | The Song editor's Sing-to-verify 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. || `useTwinEvaluationSuite` | Shared lifecycle for the three Digital Twin evaluation-suite panels (Values-Alignment, Adversarial-Boundary, Multi-Turn): loads suite + recent history (silenced), runs every selected provider/model in parallel, prepends fresh runs, and handles the stale-persona / partial-failure toast fan-out. `countField` names the suite's pass-count key so history stays generic. Returns `{ items, history, loading, running, results, expanded, setExpanded, run, reload }`. | The Digital Twin `TwinEvaluationSuitePanel` presentation shell — don't re-roll the load/run/history dance per suite. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex ef8a0cd5d6..3ebccb123e 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -31,6 +31,8 @@ export { default as useSlotInFlight } from './useSlotInFlight.js';export { default as useSseJobSlot } from './useSseJobSlot.js';export { default as useSingToScore } from './useSingToScore.js';export * from './useSingToScore.js';+export { default as useSingToVerify } from './useSingToVerify.js';+export * from './useSingToVerify.js';export { default as useSongTraining } from './useSongTraining.js';export { default as useMediaPreviewActions } from './useMediaPreviewActions.js';export { default as useKeyboardControls } from './useKeyboardControls.js';diff --git a/client/src/hooks/useSingToVerify.js b/client/src/hooks/useSingToVerify.jsnew file mode 100644index 0000000000..ecc170e7af--- /dev/null+++ b/client/src/hooks/useSingToVerify.js@@ -0,0 +1,144 @@+// useSingToVerify — capture a sung phrase and align it note-for-note against an+// existing score, without changing the score until the user accepts pitches.++import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { createStreamAnalyser } from '../lib/audioRecorder.js';+import { createMetronome, clampBpm, DEFAULT_BPM } from '../lib/metronome.js';+import { createPitchTracker } from '../lib/pitchDetect.js';+import { parseScore } from '../lib/scoreNotation.js';+import { alignSingToVerify } from '../lib/singToVerify.js';+import useMounted from './useMounted.js';++export const VERIFY_IDLE = 'idle';+export const VERIFY_COUNT_IN = 'countIn';+export const VERIFY_RECORDING = 'recording';++const FRAME_INTERVAL_MS = 30;+const nowMs = () => (typeof performance !== 'undefined' ? performance.now() : Date.now());++export default function useSingToVerify({ score: scoreText = '', tempo } = {}) {+ const [phase, setPhase] = useState(VERIFY_IDLE);+ const [beat, setBeat] = useState(null);+ const [rows, setRows] = useState([]);+ const [error, setError] = useState(null);++ const score = useMemo(() => parseScore(scoreText), [scoreText]);+ const mountedRef = useMounted();+ const streamRef = useRef(null);+ const analyserRef = useRef(null);+ const trackerRef = useRef(null);+ const metronomeRef = useRef(null);+ const trackRef = useRef([]);+ const captureStartRef = useRef(0);+ const startBarRef = useRef(1);+ const capturingRef = useRef(false);++ const bpm = clampBpm(tempo ?? score.tempo) ?? DEFAULT_BPM;++ const teardown = useCallback(() => {+ if (metronomeRef.current) { metronomeRef.current.stop(); metronomeRef.current = null; }+ if (trackerRef.current) { trackerRef.current.stop(); trackerRef.current = null; }+ if (analyserRef.current) { analyserRef.current.close(); analyserRef.current = null; }+ if (streamRef.current) {+ streamRef.current.getTracks().forEach((track) => track.stop());+ streamRef.current = null;+ }+ capturingRef.current = false;+ }, []);++ const stop = useCallback(() => {+ if (phase === VERIFY_IDLE) return;+ const captureEndMs = capturingRef.current+ ? Math.max(0, nowMs() - captureStartRef.current)+ : 0;+ teardown();+ const nextRows = alignSingToVerify(score, trackRef.current, {+ bpm,+ startBar: startBarRef.current,+ captureEndMs,+ });+ if (!mountedRef.current) return;+ setRows(nextRows);+ setPhase(VERIFY_IDLE);+ setBeat(null);+ }, [phase, score, bpm, teardown, mountedRef]);++ const start = useCallback(async (startBar = 1) => {+ if (phase !== VERIFY_IDLE) return;+ setError(null);+ setRows([]);+ trackRef.current = [];+ startBarRef.current = startBar;++ const stream = await navigator.mediaDevices.getUserMedia({ audio: true }).catch((err) => {+ if (mountedRef.current) setError(err?.message || 'Microphone access denied');+ return null;+ });+ if (!stream) return;+ if (!mountedRef.current) {+ stream.getTracks().forEach((track) => track.stop());+ return;+ }+ streamRef.current = stream;++ const graph = createStreamAnalyser(stream);+ analyserRef.current = graph;+ trackerRef.current = createPitchTracker(graph.analyser, {+ intervalMs: FRAME_INTERVAL_MS,+ holdClarity: 0.9,+ releaseFrames: 0,+ onUpdate: (update) => {+ if (!capturingRef.current) return;+ trackRef.current.push({+ tMs: nowMs() - captureStartRef.current,+ hz: update.hz,+ clarity: update.clarity,+ });+ },+ });++ setPhase(VERIFY_COUNT_IN);+ const metronome = createMetronome({+ bpm,+ beatsPerBar: score.time.beats,+ beatValue: score.time.beatValue,+ countInBars: 1,+ onBeat: (info) => {+ if (mountedRef.current) setBeat(info.beat);+ },+ onCountInComplete: () => {+ if (!mountedRef.current) return;+ captureStartRef.current = nowMs();+ capturingRef.current = true;+ setPhase(VERIFY_RECORDING);+ },+ });+ metronomeRef.current = metronome;+ await metronome.start().catch((err) => {+ if (mountedRef.current) setError(err?.message || 'Could not start audio');+ teardown();+ if (mountedRef.current) setPhase(VERIFY_IDLE);+ });+ }, [phase, bpm, score.time.beats, score.time.beatValue, teardown, mountedRef]);++ const reset = useCallback(() => {+ setRows([]);+ setError(null);+ }, []);++ const toggleAccept = useCallback((index) => {+ setRows((current) => current.map((row) =>+ row.index === index && row.sung ? { ...row, accepted: !row.accepted } : row));+ }, []);++ const acceptAll = useCallback(() => {+ setRows((current) => current.map((row) => row.sung ? { ...row, accepted: true } : row));+ }, []);++ const teardownRef = useRef(teardown);+ teardownRef.current = teardown;+ useEffect(() => () => teardownRef.current(), []);++ return { phase, beat, rows, error, start, stop, reset, toggleAccept, acceptAll };+}+diff --git a/client/src/hooks/useSingToVerify.test.js b/client/src/hooks/useSingToVerify.test.jsnew file mode 100644index 0000000000..61308fbb1a--- /dev/null+++ b/client/src/hooks/useSingToVerify.test.js@@ -0,0 +1,99 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const analyserClose = vi.fn();+const trackerStop = vi.fn();+const metronomeStop = vi.fn();+const trackStop = vi.fn();+let trackerOnUpdate = null;+let metronomeOptions = null;+let clock = 1000;+const { alignMock } = vi.hoisted(() => ({ alignMock: vi.fn(() => [{ index: 0, accepted: false }]) }));++vi.mock('../lib/audioRecorder.js', () => ({+ createStreamAnalyser: vi.fn(() => ({ analyser: {}, close: analyserClose })),+}));++vi.mock('../lib/pitchDetect.js', () => ({+ createPitchTracker: vi.fn((analyser, options) => {+ trackerOnUpdate = options.onUpdate;+ return { stop: trackerStop };+ }),+}));++vi.mock('../lib/metronome.js', async (importActual) => {+ const actual = await importActual();+ return {+ ...actual,+ createMetronome: vi.fn((options) => {+ metronomeOptions = options;+ return { start: vi.fn(async () => {}), stop: metronomeStop };+ }),+ };+});++vi.mock('../lib/singToVerify.js', () => ({ alignSingToVerify: alignMock }));++import useSingToVerify, {+ VERIFY_COUNT_IN,+ VERIFY_IDLE,+ VERIFY_RECORDING,+} from './useSingToVerify.js';++const fakeStream = () => ({ getTracks: () => [{ stop: trackStop }] });++describe('useSingToVerify', () => {+ beforeEach(() => {+ analyserClose.mockClear();+ trackerStop.mockClear();+ metronomeStop.mockClear();+ trackStop.mockClear();+ alignMock.mockClear();+ trackerOnUpdate = null;+ metronomeOptions = null;+ clock = 1000;+ global.performance = { now: () => clock };+ global.navigator.mediaDevices = { getUserMedia: vi.fn(async () => fakeStream()) };+ });++ afterEach(() => vi.clearAllMocks());++ it('captures from the selected start bar and aligns rows on stop', async () => {+ const { result } = renderHook(() => useSingToVerify({+ tempo: 120,+ score: 'time: 4/4\n| C4q D4q |',+ }));+ expect(result.current.phase).toBe(VERIFY_IDLE);++ await act(async () => { await result.current.start(2); });+ expect(result.current.phase).toBe(VERIFY_COUNT_IN);+ act(() => metronomeOptions.onCountInComplete());+ expect(result.current.phase).toBe(VERIFY_RECORDING);++ clock = 1100;+ act(() => trackerOnUpdate({ hz: 261.6, clarity: 0.98 }));+ clock = 1600;+ act(() => result.current.stop());++ expect(alignMock).toHaveBeenCalledWith(+ expect.any(Object),+ [{ tMs: 100, hz: 261.6, clarity: 0.98 }],+ expect.objectContaining({ bpm: 120, startBar: 2, captureEndMs: 600 }),+ );+ expect(result.current.rows).toEqual([{ index: 0, accepted: false }]);+ });++ it('tears down mic stream, analyser, tracker, and metronome on unmount', async () => {+ const { result, unmount } = renderHook(() => useSingToVerify({+ tempo: 120,+ score: 'time: 4/4\n| C4q |',+ }));+ await act(async () => { await result.current.start(1); });+ unmount();+ expect(metronomeStop).toHaveBeenCalled();+ expect(trackerStop).toHaveBeenCalled();+ expect(analyserClose).toHaveBeenCalled();+ expect(trackStop).toHaveBeenCalled();+ });+});+diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 2a784ad3e5..a94333861e 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -138,9 +138,10 @@ grep -i "what you want to do" client/src/lib/README.md| `midiPlayback.js` | Synth preview of a transcribed `.mid` (#2490) — `createMidiPlayer(data, { onEnded })` plays the `parseMidiFile` view-model as velocity-scaled oscillator tones through a per-play master bus on the shared `AudioContext`, with the same lookahead-scheduler idiom + tone envelope (`scheduleTone`) as `scorePlayback.js`. Transport: `play`/`pause`/`stop`/`seek(sec)` (seek re-anchors a running transport and sounds the tails of notes sustaining across the seek point) and `position()` for the `<MidiPianoRoll>` moving playhead. Pure (no React) — `useMidiPlayer` wraps it. || `pianoKeyboard.js` | Piano-keyboard geometry for the song system's Synthesia-style piano-roll visualizer (`<PianoRoll>`). Pure math, no canvas/React. `keyboardRange(midis, { minSemitones })` → `{ lowMidi, highMidi }` padded out to whole C–B octaves (min 2) so the keyboard always starts on a C / ends on a B and never collapses for a one-note part; `buildKeyboardLayout({ lowMidi, highMidi, width })` → `{ keys:[{midi,isBlack,x,w}], whiteWidth, blackWidth }` (white keys tiled edge-to-edge, black keys overlaid centered on the boundary, narrower); plus `isBlackKey(midi)`, `midiNoteName(midi)` (sharps spelling), `pitchClass(midi)` (positive modulo), the canonical `PITCH_CLASS_NAMES` table (re-exported by `referenceAnalysis.js`, consumed by `midiChords.js` — single source for note/chord spelling), and the `BLACK_KEY_RATIO`/`BLACK_KEY_HEIGHT_RATIO` constants. Pairs with `scorePlayback`'s per-note `midi` field. || `referenceAnalysis.js` | Reference-audio analysis for the Rounds workbench (#2106) — pure DSP + diff helpers behind the "analyze a reference's attached audio" view. `extractPitchTrack(samples, sampleRate, { startMs, endMs, hopMs })` frames decoded PCM through `detectFrequency` offline (faster than realtime) into the `[{ tMs, hz, clarity }]` shape `singToScore` consumes; `proposeSegmentScore(samples, sampleRate, { startMs, endMs, bpm, key })` runs the solo-segment pipeline (extract → `transcribePitchTrack` on the round's tempo/key grid) → `{ track, body, text }`; `buildScoreText({ key, tempo, body })` wraps a transcribed body in a lead-sheet header; `barPitchClasses(scoreText)` / `diffScoreBars(proposed, existing)` compare a proposed part against a stored scorePart per bar by octave-collapsed pitch-class sequence (drives the review diff highlighting). Stacked-mix extraction (#2121, spectral diff v2): `magnitudeSpectrum(frame, { fftSize })` (hand-rolled radix-2 FFT, Hann-windowed) / `averageMagnitudeSpectrum(samples, sampleRate, { startMs, endMs })` build a backing profile; `estimateSpectralF0(mag, sampleRate, fftSize)` picks the fundamental by weighted (1/k) harmonic sum (octave-robust); `extractSpectralDiffTrack(samples, sampleRate, { startMs, endMs, bgStartMs, bgEndMs })` subtracts the backing profile per frame and estimates f0 on the residual to recover a voice that never plays solo; `proposeStackedSegmentScore(...)` is its `proposeSegmentScore` counterpart. Zero LLM calls — pure local DSP. |-| `scoreNotation.js` | Parser for the PortOS lead-sheet notation — a dependency-free text format for melody + chords + lyrics that the `<ScoreSheet>` SVG renderer draws (no abcjs / VexFlow / OSMD). `parseScore(text)` → `{ clef, key, keySig, time, tempo, measures, errors }`; plus `parsePitch`, `diatonicStep`, `durationBeats`, `keySignature`, `DURATIONS`, and `scoreHasMusic(text)`. Forgiving: bad tokens collect into `errors` and are skipped, never thrown. Pure — the renderer only does geometry. |+| `scoreNotation.js` | Parser for the PortOS lead-sheet notation — a dependency-free text format for melody + chords + lyrics that the `<ScoreSheet>` SVG renderer draws (no abcjs / VexFlow / OSMD). `parseScore(text)` → `{ clef, key, keySig, time, tempo, measures, errors }`, with each parsed note carrying its raw token and source offsets; `replaceNotePitch(text, note, pitch)` uses those spans to rewrite only one pitch while preserving the rest byte-for-byte. Plus `parsePitch`, `diatonicStep`, `durationBeats`, `keySignature`, `DURATIONS`, and `scoreHasMusic(text)`. Forgiving: bad tokens collect into `errors` and are skipped, never thrown. Pure — the renderer only does geometry. || `scorePlayback.js` | Melody synth playback for the lead-sheet notation — companion to `songPlayback.js` (which stacks recorded vocal takes), this synthesizes the WRITTEN melody as soft `OscillatorNode` reference tones on a lazy shared `AudioContext` (no MIDI.js / Tone.js). `buildSchedule(score, bpm?)` is the pure notes→`{ midi, freq, startSec, durSec }` mapping (A4=440, quarter-beat = `(60/bpm)·(beatValue/4)` so it honors the time signature; `midi` feeds the `<PianoRoll>` key mapping); `noteToFrequency`/`midiToFreq`/`pitchToMidi` convert pitches; `createScorePlayer(score, { bpm, onNote, onEnded })` plays/pauses/stops with a lookahead scheduler and emits the now-sounding note index for the `<ScoreSheet>` playhead; `createMultiScorePlayer(parts, { bpm, onNote, onEnded })` synthesizes several parts (melody + checked harmony) together on one master bus (level backs off as voices stack) with a per-part `onNote(partId, index)` playhead, plus `position()`/`duration()` (score-seconds) for the continuous piano-roll visualizer. Both players are thin schedulers over the shared `lookaheadTransport.js`. Also exports the pieces `midiPlayback.js` shares: `scheduleTone` (attack/release envelope) and `makeSafeCall(label)` (interval-callback guard); the `SYNTH_TIMING` lookahead constants now live in `lookaheadTransport.js`. || `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. |+| `singToVerify.js` | Pure strict-1:1 score verification: `alignSingToVerify(score, track, { bpm, startBar, captureEndMs })` aligns clear sung-pitch frames to `buildColorMatchTimeline` windows, preserves detected octave and key-aware spelling, and returns written→sung rows with raw cents, grade, source note, and explicit acceptance state. Reached silent windows are `missed`; notes after Stop remain `pending`. || `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. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex e6b0f386f9..db1706b6cf 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -111,6 +111,7 @@ export * from './referenceAnalysis.js';export * from './scoreNotation.js';export * from './scorePlayback.js';export * from './singToScore.js';+export * from './singToVerify.js';export * from './songCraft.js';export * from './songPlayback.js';export * from './songProgress.js';diff --git a/client/src/lib/scoreNotation.js b/client/src/lib/scoreNotation.jsindex 2a97151e9d..7adb25936d 100644--- a/client/src/lib/scoreNotation.js+++ b/client/src/lib/scoreNotation.js@@ -147,10 +147,19 @@ const parseTimeSignature = (raw) => {// [chord]? (r | PITCH) DURATION dots? (lyric)?const TOKEN_RE = /^(?:\[([^\]]*)\])?(r|[A-Ga-g](?:#{1,2}|b{1,2}|n)?-?\d)([whqest])(\.*)(?:\((.*)\))?$/;-const parseToken = (token) => {+const parseToken = (token, start = null) => {const m = TOKEN_RE.exec(token);if (!m) return { error: `unrecognized token "${token}"` };const [, chord, core, durCode, dotStr, lyric] = m;+ const tokenSource = Number.isInteger(start)+ ? {+ raw: token,+ start,+ end: start + token.length,+ pitchStart: start + (chord == null ? 0 : token.indexOf(']') + 1),+ pitchEnd: start + (chord == null ? 0 : token.indexOf(']') + 1) + core.length,+ }+ : { raw: token };const dots = dotStr ? dotStr.length : 0;// Carry the static duration properties (filled / stem / flags) the renderer// needs alongside the per-token dots/beats, so a duration object is fully@@ -158,7 +167,7 @@ const parseToken = (token) => {const base = DURATIONS[durCode];const duration = { code: durCode, dots, beats: durationBeats(durCode, dots), filled: base.filled, stem: base.stem, flags: base.flags };if (core === 'r') {- return { rest: true, duration, chord: chord || '' };+ return { rest: true, duration, chord: chord || '', ...tokenSource };}const pitch = parsePitch(core);if (!pitch) return { error: `bad pitch in "${token}"` };@@ -169,6 +178,7 @@ const parseToken = (token) => {duration,chord: chord || '',lyric: lyric || '',+ ...tokenSource,};};@@ -177,14 +187,21 @@ const parseToken = (token) => {// summed duration (handy for the renderer to flag incomplete bars, and for// tests). Always returns a usable object — never throws.export const parseScore = (text) => {+ const source = String(text || '');const header = { ...DEFAULT_HEADER };const errors = [];const bodyLines = [];- const lines = String(text || '').split(/\r?\n/);- for (const rawLine of lines) {+ let lineStart = 0;+ for (const rawLine of source.split(/\r?\n/)) {+ const rawEnd = lineStart + rawLine.length;+ const newlineLength = source.startsWith('\r\n', rawEnd) ? 2 : (source[rawEnd] === '\n' ? 1 : 0);+ const nextLineStart = rawEnd + newlineLength;const line = rawLine.trim();- if (!line) continue;+ if (!line) {+ lineStart = nextLineStart;+ continue;+ }// A header line is `key: value` and contains no `|` (music) and no note// tokens. We detect it by the leading `word:` shape before any `|`.const headerMatch = /^([A-Za-z]+)\s*:\s*(.+)$/.exec(line);@@ -199,33 +216,53 @@ export const parseScore = (text) => {if (ts) { header.beats = ts.beats; header.beatValue = ts.beatValue; }else errors.push(`bad time signature "${value}"`);}+ lineStart = nextLineStart;continue;}- bodyLines.push(line);+ bodyLines.push({ rawLine, start: lineStart });+ lineStart = nextLineStart;}- // Join the music body and split into measures on `|`. Empty segments (from a- // leading/trailing/double `|`) are dropped.- const body = bodyLines.join(' ');- const segments = body.split('|').map((s) => s.trim()).filter(Boolean);- const measures = segments.map((segment, mi) => {- const notes = [];- // A standalone `[chord]` token attaches to the NEXT note (the readable form- // `[C] E4q`); the attached form `[C]E4q` also works. `pendingChord` carries a- // bare bracket forward until a note consumes it.- let pendingChord = '';- for (const token of segment.split(/\s+/).filter(Boolean)) {+ // Scan the original source instead of joining/reflowing the body. Each parsed+ // note carries offsets back into `source`, so a caller can surgically replace+ // its pitch while preserving every other byte (including line breaks).+ const measures = [];+ let notes = [];+ let pendingChord = '';+ let segmentHasToken = false;+ const finishMeasure = () => {+ if (!segmentHasToken) return;+ const beats = notes.reduce((sum, n) => sum + (n.duration?.beats || 0), 0);+ measures.push({ notes, beats });+ notes = [];+ pendingChord = '';+ segmentHasToken = false;+ };++ for (const { rawLine, start } of bodyLines) {+ for (const match of rawLine.matchAll(/\||[^\s|]+/g)) {+ const token = match[0];+ if (token === '|') {+ finishMeasure();+ continue;+ }+ segmentHasToken = true;const bare = /^\[([^\]]*)\]$/.exec(token);- if (bare) { pendingChord = bare[1]; continue; }- const parsed = parseToken(token);- if (parsed.error) { errors.push(`measure ${mi + 1}: ${parsed.error}`); continue; }+ if (bare) {+ pendingChord = bare[1];+ continue;+ }+ const parsed = parseToken(token, start + match.index);+ if (parsed.error) {+ errors.push(`measure ${measures.length + 1}: ${parsed.error}`);+ continue;+ }if (pendingChord && !parsed.chord) parsed.chord = pendingChord;pendingChord = '';notes.push(parsed);}- const beats = notes.reduce((sum, n) => sum + (n.duration?.beats || 0), 0);- return { notes, beats };- });+ }+ finishMeasure();return {clef: header.clef,@@ -238,6 +275,22 @@ export const parseScore = (text) => {};};+// Replace only the pitch characters inside one parsed note token. Source spans+// are validated against the current text so a stale note object cannot rewrite+// a different score after the editor changes.+export const replaceNotePitch = (text, note, newPitch) => {+ const source = String(text || '');+ const replacement = parsePitch(newPitch);+ if (!note || note.rest || !replacement) throw new Error('A pitched note and valid replacement pitch are required');+ if (!Number.isInteger(note.start) || !Number.isInteger(note.end)+ || !Number.isInteger(note.pitchStart) || !Number.isInteger(note.pitchEnd)+ || source.slice(note.start, note.end) !== note.raw) {+ throw new Error('The note source span is stale or invalid');+ }+ const pitchText = `${replacement.letter}${replacement.accidental}${replacement.octave}`;+ return source.slice(0, note.pitchStart) + pitchText + source.slice(note.pitchEnd);+};+// True when the text contains at least one parseable note — lets the UI decide// whether to show the staff or an empty-state hint without rendering first.export const scoreHasMusic = (text) => parseScore(text).measures.some((m) => m.notes.length > 0);diff --git a/client/src/lib/scoreNotation.test.js b/client/src/lib/scoreNotation.test.jsindex 942956cacc..6f47313c9f 100644--- a/client/src/lib/scoreNotation.test.js+++ b/client/src/lib/scoreNotation.test.js@@ -5,6 +5,7 @@ import {diatonicStep,durationBeats,keySignature,+ replaceNotePitch,scoreHasMusic,DURATIONS,} from './scoreNotation.js';@@ -187,6 +188,47 @@ describe('parseScore', () => {expect(s.measures).toHaveLength(8);for (const m of s.measures) expect(m.beats).toBeCloseTo(4, 5);});++ it('keeps source spans across formatted multi-line bodies', () => {+ const text = [+ 'key: Bb',+ '',+ '| [Bb] Bb3q.(Sing) C4e(now) |',+ ' | [F7]D4h(through) rq |',+ ].join('\r\n');+ const notes = parseScore(text).measures.flatMap((measure) => measure.notes);+ expect(notes.map((note) => text.slice(note.start, note.end))).toEqual([+ 'Bb3q.(Sing)',+ 'C4e(now)',+ '[F7]D4h(through)',+ 'rq',+ ]);+ expect(notes.map((note) => note.raw)).toEqual([+ 'Bb3q.(Sing)',+ 'C4e(now)',+ '[F7]D4h(through)',+ 'rq',+ ]);+ });+});++describe('replaceNotePitch', () => {+ it('rewrites only the pitch and preserves formatting, chord, duration, dots, and lyric', () => {+ const text = 'key: C\n\n| [C] C4q. (bad-gap) [G7]F#4h.(held) |';+ const note = parseScore(text).measures[0].notes[1];+ const next = replaceNotePitch(text, note, 'Bb3');+ expect(next).toBe('key: C\n\n| [C] C4q. (bad-gap) [G7]Bb3h.(held) |');+ expect(next.slice(0, note.start)).toBe(text.slice(0, note.start));+ expect(next.slice(note.pitchStart + 'Bb3'.length)).toBe(text.slice(note.pitchEnd));+ });++ it('rejects rests, invalid pitches, and stale spans', () => {+ const text = '| C4q rq |';+ const [note, rest] = parseScore(text).measures[0].notes;+ expect(() => replaceNotePitch(text, rest, 'D4')).toThrow(/pitched note/i);+ expect(() => replaceNotePitch(text, note, 'nope')).toThrow(/valid replacement/i);+ expect(() => replaceNotePitch(`${text} `, { ...note, raw: 'D4q' }, 'D4')).toThrow(/stale/i);+ });});describe('scoreHasMusic', () => {diff --git a/client/src/lib/singToScore.js b/client/src/lib/singToScore.jsindex d01e8acbce..759cda8aa9 100644--- a/client/src/lib/singToScore.js+++ b/client/src/lib/singToScore.js@@ -205,7 +205,7 @@ const FLAT_SPELLING = {// We adjust the octave for the flat respelling so the *pitch* is unchanged// (e.g. C#5 → Db5 stays the same sounding note; only the name changes — same// octave because Db and C# share octave boundaries above C).-const spellNote = (note, keySig) => {+export const spellNote = (note, keySig) => {if (!note) return null;if (keySig?.type !== 'flat' || !note.accidental) return note;// Recover the pitch class from the detector's sharp spelling.diff --git a/client/src/lib/singToVerify.js b/client/src/lib/singToVerify.jsnew file mode 100644index 0000000000..dcd5de73c7--- /dev/null+++ b/client/src/lib/singToVerify.js@@ -0,0 +1,114 @@+// Pure sing-to-verify alignment. It maps a captured vocal pitch track onto the+// written score's existing note windows, producing a strict 1:1 pitch diff.++import {+ buildColorMatchTimeline,+ centsBetween,+ GRADE,+ MATCH_CLOSE_CENTS,+ MATCH_IN_TUNE_CENTS,+} from './colorMatch.js';+import { frequencyToNote } from './pitchDetect.js';+import { spellNote } from './singToScore.js';++const DEFAULT_CLARITY = 0.9;++const median = (values) => {+ if (!values.length) return null;+ const sorted = [...values].sort((a, b) => a - b);+ const middle = sorted.length >> 1;+ return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;+};++const pitchShape = (pitch) => pitch && ({+ letter: pitch.letter,+ accidental: pitch.accidental || '',+ octave: pitch.octave,+});++const gradeRawCents = (cents) => {+ if (cents == null) return GRADE.MISSED;+ const distance = Math.abs(cents);+ if (distance <= MATCH_IN_TUNE_CENTS) return GRADE.IN_TUNE;+ if (distance <= MATCH_CLOSE_CENTS) return GRADE.CLOSE;+ return GRADE.OFF;+};++/**+ * Align captured pitch frames to written notes from `startBar` onward.+ *+ * `captureEndMs` distinguishes a silent-but-reached window (`missed`) from a+ * note after Stop (`pending`). It defaults to the final frame timestamp.+ */+export const alignSingToVerify = (+ score,+ track,+ {+ bpm,+ startBar = 1,+ captureEndMs,+ clarityThreshold = DEFAULT_CLARITY,+ } = {},+) => {+ const measures = score?.measures || [];+ const safeStartBar = Math.min(Math.max(1, Number(startBar) || 1), Math.max(1, measures.length));+ const allNotes = measures.flatMap((measure) => measure.notes || []);+ const startIndex = measures+ .slice(0, safeStartBar - 1)+ .reduce((count, measure) => count + (measure.notes?.length || 0), 0);+ const timeline = buildColorMatchTimeline(score, { bpm });+ const firstWindow = timeline.notes.find((note) => note.index >= startIndex);+ if (!firstWindow) return [];++ const frames = Array.isArray(track)+ ? track.filter((frame) => frame && Number.isFinite(frame.tMs))+ : [];+ const resolvedEnd = Number.isFinite(captureEndMs)+ ? Math.max(0, captureEndMs)+ : Math.max(0, ...frames.map((frame) => frame.tMs));+ // Capture starts on beat 1 of the selected bar, not on its first pitched+ // note. Leading rests in that bar must retain their full waiting time.+ const offsetMs = measures+ .slice(0, safeStartBar - 1)+ .reduce((duration, measure) => duration + (measure.beats || 0), 0)+ * timeline.msPerQuarter;++ return timeline.notes+ .filter((window) => window.index >= startIndex)+ .map((window) => {+ const note = allNotes[window.index];+ const startMs = window.startMs - offsetMs;+ const endMs = window.endMs - offsetMs;+ if (startMs >= resolvedEnd) {+ return {+ index: window.index,+ note,+ written: pitchShape(note?.pitch),+ sung: null,+ cents: null,+ grade: GRADE.PENDING,+ accepted: false,+ };+ }++ const hz = median(frames+ .filter((frame) =>+ frame.tMs >= startMs+ && frame.tMs < endMs+ && Number.isFinite(frame.hz)+ && frame.hz > 0+ && (frame.clarity ?? 1) >= clarityThreshold)+ .map((frame) => frame.hz));+ const detected = hz == null ? null : spellNote(frequencyToNote(hz), score?.keySig);+ const cents = centsBetween(hz, window.targetHz);+ return {+ index: window.index,+ note,+ written: pitchShape(note?.pitch),+ sung: pitchShape(detected),+ cents,+ grade: gradeRawCents(cents),+ accepted: false,+ };+ });+};diff --git a/client/src/lib/singToVerify.test.js b/client/src/lib/singToVerify.test.jsnew file mode 100644index 0000000000..e390cc6a14--- /dev/null+++ b/client/src/lib/singToVerify.test.js@@ -0,0 +1,73 @@+import { describe, expect, it } from 'vitest';+import { GRADE } from './colorMatch.js';+import { noteToFrequency } from './pitchDetect.js';+import { parseScore } from './scoreNotation.js';+import { alignSingToVerify } from './singToVerify.js';++const hz = (pitch) => noteToFrequency(pitch);+const frame = (tMs, pitch, clarity = 0.98) => ({ tMs, hz: hz(pitch), clarity });+const score = parseScore('key: C\ntime: 4/4\ntempo: 120\n| C4q D4q E4q F4q |');++describe('alignSingToVerify', () => {+ it('aligns an exact match and an off-by-a-semitone pitch to written windows', () => {+ const rows = alignSingToVerify(score, [+ frame(100, { letter: 'C', octave: 4 }),+ frame(600, { letter: 'D', accidental: '#', octave: 4 }),+ ], { captureEndMs: 1000 });+ expect(rows[0]).toMatchObject({+ index: 0,+ written: { letter: 'C', accidental: '', octave: 4 },+ sung: { letter: 'C', accidental: '', octave: 4 },+ grade: GRADE.IN_TUNE,+ accepted: false,+ });+ expect(rows[1].grade).toBe(GRADE.OFF);+ expect(rows[1].cents).toBeCloseTo(100, 1);+ expect(rows[2].grade).toBe(GRADE.PENDING);+ });++ it('keeps octave differences as corrections instead of folding them', () => {+ const rows = alignSingToVerify(score, [+ frame(100, { letter: 'C', octave: 5 }),+ ], { captureEndMs: 500 });+ expect(rows[0].sung).toMatchObject({ letter: 'C', octave: 5 });+ expect(rows[0].cents).toBeCloseTo(1200, 1);+ expect(rows[0].grade).toBe(GRADE.OFF);+ });++ it('grades a reached silent window missed and leaves later notes pending', () => {+ const rows = alignSingToVerify(score, [+ { tMs: 100, hz: null, clarity: 0.1 },+ ], { captureEndMs: 500 });+ expect(rows[0].grade).toBe(GRADE.MISSED);+ expect(rows[1].grade).toBe(GRADE.PENDING);+ });++ it('offsets capture time to the selected start bar', () => {+ const twoBars = parseScore('time: 2/4\ntempo: 120\n| C4q D4q |\n| E4q F4q |');+ const rows = alignSingToVerify(twoBars, [+ frame(100, { letter: 'E', octave: 4 }),+ ], { startBar: 2, captureEndMs: 500 });+ expect(rows.map((row) => row.index)).toEqual([2, 3]);+ expect(rows[0].grade).toBe(GRADE.IN_TUNE);+ });++ it('keeps leading rests in the selected bar on the capture clock', () => {+ const withRest = parseScore('time: 2/4\ntempo: 120\n| C4h |\n| rq E4q |');+ const rows = alignSingToVerify(withRest, [+ frame(600, { letter: 'E', octave: 4 }),+ ], { startBar: 2, captureEndMs: 1000 });+ expect(rows[0].index).toBe(2);+ expect(rows[0].grade).toBe(GRADE.IN_TUNE);+ });++ it('marks notes after an early stop pending', () => {+ const rows = alignSingToVerify(score, [+ frame(100, { letter: 'C', octave: 4 }),+ ], { captureEndMs: 600 });+ expect(rows[0].grade).toBe(GRADE.IN_TUNE);+ expect(rows[1].grade).toBe(GRADE.MISSED);+ expect(rows[2].grade).toBe(GRADE.PENDING);+ expect(rows[3].grade).toBe(GRADE.PENDING);+ });+});