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

fix([issue-1092]): address review (codex/claude)

Adam Eivyfda5efe66447
diff --git a/client/src/components/songs/SongRecordings.jsx b/client/src/components/songs/SongRecordings.jsx
index 5408acb52a..b5da8cc187 100644
--- a/client/src/components/songs/SongRecordings.jsx
+++ b/client/src/components/songs/SongRecordings.jsx
@@ -61,12 +61,20 @@ export default function SongRecordings({ recordings = [], layers = [], onChange,
start: startMatch, stop: stopMatch,
} = useColorMatch({ score: parsedScore, stream: liveStream, bpm });
+ // True once grading has armed for the CURRENT take. The hook's accumulators
+ // (trace/grades) only reset on start(), so stopMatch() returns whatever the
+ // last run left behind even when no run armed for this take (e.g. the score
+ // was cleared between takes). We harvest the analysis only when this take
+ // actually armed grading — otherwise a no-score take would inherit the prior
+ // take's pitchTrack/accuracy. Reset at each record start, set when arming.
+ const armedThisTakeRef = useRef(false);
+
// Auto-arm grading the moment a take starts (stream appears) and the score has
// notes — mirrors the old <ColorMatch> self-arm, now lifted up. The take's
// stopRecording explicitly stops grading to harvest the trace, so we only
// need to start here. The hook also self-stops if the stream vanishes.
useEffect(() => {
- if (liveStream && hasMusic && !matchRunning) startMatch();
+ if (liveStream && hasMusic && !matchRunning) { armedThisTakeRef.current = true; startMatch(); }
// start is stable; react only to stream/hasMusic (the arm trigger).
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [liveStream, hasMusic]);
@@ -90,6 +98,7 @@ export default function SongRecordings({ recordings = [], layers = [], onChange,
const startRecording = useCallback(async () => {
setReviewId(null); // a fresh take takes over the staff from any saved-take review
+ armedThisTakeRef.current = false; // until the auto-arm effect fires for THIS take
if (playerRef.current) { playerRef.current.stop(); setPlaying(false); }
const handle = await startMemoRecording().catch((err) => {
toast.error(err?.message || 'Microphone access denied');
@@ -106,9 +115,14 @@ export default function SongRecordings({ recordings = [], layers = [], onChange,
if (!handle) return;
handleRef.current = null;
// Stop grading FIRST (while the analyser graph is still alive) to harvest the
- // finished take's pitch trace + accuracy summary, THEN drop the stream. stop()
- // returns null if grading wasn't running (no score / unmounted).
- const analysis = stopMatch();
+ // finished take's pitch trace + accuracy summary, THEN drop the stream. Only
+ // trust the harvest when grading armed for THIS take — otherwise stopMatch()
+ // would return the previous take's stale accumulators (the hook only resets
+ // them on start(), which a no-score take never calls). stop() also returns
+ // null when unmounted.
+ const armed = armedThisTakeRef.current;
+ armedThisTakeRef.current = false;
+ const analysis = armed ? stopMatch() : null;
setLiveStream(null); // stream is being torn down with the take
setRecording(false);
setSaving(true);
@@ -163,6 +177,10 @@ export default function SongRecordings({ recordings = [], layers = [], onChange,
);
// Repaint the reviewed take's SAVED grades onto the staff — read from disk via
// gradesFromPerNote, never re-graded from audio (the migration's purpose).
+ // Alignment is positional (i-th saved grade → i-th current timeline note), so
+ // editing the score's note count after recording can shift the repaint — an
+ // inherent limit of the positional perNote shape (#1027); gradesFromPerNote
+ // truncates to the shorter side so it can't paint past the staff.
const reviewColors = useMemo(() => {
if (!reviewTake) return null;
const timeline = buildColorMatchTimeline(parsedScore, { bpm });
diff --git a/client/src/components/songs/SongRecordings.test.jsx b/client/src/components/songs/SongRecordings.test.jsx
index f00c057034..971065929a 100644
--- a/client/src/components/songs/SongRecordings.test.jsx
+++ b/client/src/components/songs/SongRecordings.test.jsx
@@ -103,6 +103,34 @@ describe('SongRecordings — pitch analysis wiring (#1092)', () => {
expect(next[0]).not.toHaveProperty('pitchTrack');
});
+ it('does not inherit a prior take’s analysis when a later take has no score to grade', async () => {
+ // Regression (codex review): the hook only resets its trace/grade accumulators
+ // on start(). A no-score take never arms grading, so an unguarded stopMatch()
+ // would return the PREVIOUS take's analysis. The owner gates harvest on
+ // "armed for THIS take", so a no-score take must persist no analysis — even
+ // though the mocked stopMatch() still returns stale data if called.
+ matchStopResult = {
+ summary: { graded: 4, counts: { 'in-tune': 4, close: 0, off: 0, missed: 0 }, percentInTune: 100, perNote: ['in-tune', 'in-tune', 'in-tune', 'in-tune'] },
+ pitchTrack: [{ tMs: 0, hz: 261.6, cents: 0, clarity: 0.99 }],
+ };
+ const onChange = vi.fn();
+ // No score → scoreHasMusic() is false → grading never auto-arms.
+ const { rerender } = render(<SongRecordings recordings={[]} score="" tempo={120} onChange={onChange} />);
+
+ fireEvent.click(screen.getByRole('button', { name: /record take/i }));
+ await waitFor(() => expect(screen.getByRole('button', { name: /stop & save/i })).toBeTruthy());
+ fireEvent.click(screen.getByRole('button', { name: /stop & save/i }));
+
+ await waitFor(() => expect(onChange).toHaveBeenCalled());
+ // stopMatch() must not even be consulted for an unarmed take.
+ expect(matchStop).not.toHaveBeenCalled();
+ const next = onChange.mock.calls.at(-1)[0];
+ expect(next[0]).not.toHaveProperty('accuracy');
+ expect(next[0]).not.toHaveProperty('pitchTrack');
+ // Keep rerender referenced (used to prove the harness can swap props).
+ rerender(<SongRecordings recordings={next} score="" tempo={120} onChange={onChange} />);
+ });
+
it('shows a saved take’s accuracy badge and a Review button to replay its grading', () => {
const recordings = [{
id: 'rec-1', label: 'Take', filename: 'a.wav', durationMs: 1000, peak: 0.4, muted: false,
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 278792fe08..a06a577db3 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -87,7 +87,7 @@ grep -i "what you want to do" client/src/lib/README.md
| Module | Purpose |
|---|---|
| `cityPlaybackFrame.js` | Map a recorded CyberCity snapshot frame onto the prop shape CityScene/CityHud consume for the timeline scrubber (`mergeFrameIntoCityProps`, `buildPlaybackApps`, `buildPlaybackAgentMap`, `isPlayableFrame`). Honors `schemaVersion` and the capture-side null sentinels; returns only snapshot-backed props so unfed landmarks stay live. |
-| `colorMatch.js` | Pure grading core for the song system's color-match training mode: `buildColorMatchTimeline(score, { bpm })` → `{ notes, totalMs, msPerQuarter, bpm }` (each note's target frequency + onset/offset window in ms, keyed by the same global note index the renderer flattens, timing mirroring `scorePlayback`); `gradeNote(hz, targetHz)` classifies a sung pitch against a target into `in-tune`/`close`/`off`/`missed` (octave-folded, thresholds `MATCH_IN_TUNE_CENTS`/`MATCH_CLOSE_CENTS`); `noteAtTime(timeline, tMs, fromIdx)` finds the active note for a rAF cursor; `summarizeAccuracy(grades)` → `{ graded, counts, percentInTune }` per-take summary; plus `centsBetween` and the `GRADE` enum. No React, no audio — the `useColorMatch` hook drives it. |
+| `colorMatch.js` | Pure grading core for the song system's color-match training mode: `buildColorMatchTimeline(score, { bpm })` → `{ notes, totalMs, msPerQuarter, bpm }` (each note's target frequency + onset/offset window in ms, keyed by the same global note index the renderer flattens, timing mirroring `scorePlayback`); `gradeNote(hz, targetHz)` classifies a sung pitch against a target into `in-tune`/`close`/`off`/`missed` (octave-folded, thresholds `MATCH_IN_TUNE_CENTS`/`MATCH_CLOSE_CENTS`); `noteAtTime(timeline, tMs, fromIdx)` finds the active note for a rAF cursor; `summarizeAccuracy(grades)` → `{ graded, counts, percentInTune, perNote }` per-take summary (`perNote` is the ordered grade list a saved take persists, mirroring the server sanitizer); `gradesFromPerNote(timeline, perNote)` is its inverse — rebuilds the noteIndex→grade map to repaint a saved take's grading on open without re-grading audio; plus `centsBetween` and the `GRADE` enum. No React, no audio — the `useColorMatch` hook drives it. |
| `pitchDetect.js` | Dependency-free vocal pitch-detection core for the song system (tuner / color-match / sing-to-score). `detectFrequency(frame, { sampleRate })` → `{ hz, clarity }` (McLeod NSDF; clarity gate rejects silence/noise); `frequencyToNote(hz, { a4 })` → `{ letter, accidental, octave, step, cents }` (cents ∈ [-50,+50], sharp positive; `step` reuses `scoreNotation`'s `diatonicStep` so detected notes align with the renderer); `noteToFrequency(note, { a4 })` inverse (color-match targets); `createPitchTracker(analyser, { onUpdate })` → `{ stop }` rAF/interval loop with median+EMA smoothing to kill octave jumps; `tuningQuality(cents)` → `{ level, label }` buckets a cents deviation into `in-tune`/`close`/`off`/`none` (thresholds `IN_TUNE_CENTS`/`CLOSE_CENTS`) for the tuner color readout. |
| `universeBuilderExpand.js` | `mergeExpandIntoDraft(draft, result)` — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with `kind` precedence, canon dedupe by name/slugline/alias). Also exports `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` for callers that need the building blocks (per-category Generate, save-time refetch+merge). |
| `metronome.js` | Sample-accurate Web Audio metronome — the shared timing grid for the song system and first consumer of the song `tempo` field. `createMetronome({ bpm, beatsPerBar, countInBars, onBeat, onCountInComplete })` lookahead-schedules accented click tones on the shared `AudioContext` clock (same pattern as `songPlayback.js`), emits `{ beat, bar, accent, countIn, whenAudioTime }` per beat (the beat-clock callback color-match/sing-to-score subscribe to), and tears down all timers on `stop()`. Plus `clampBpm` (20–320), `secondsPerBeat`, `timeSignatureFromScore`, `beatDescriptor`. |