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

address review (claude): fix clobbered changelog + guard stacked mode against silent solo fallback (#2121)

Adam Eivy16f8106a6f2f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 56818bdb8e..6ea05434cb 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -30,7 +30,8 @@
## Rounds
-- **[issue-2121] Reference analysis can now pull a voice out of a stacked mix, not just solo spans.** The "analyze a reference's attached audio" workbench used to only transcribe time ranges where a voice sings *alone* — useless for the many layered TikTok builds where a new part enters over the layers already playing and never appears solo. Each segment now has a **Stacked** toggle: turn it on and set a short *backing reference* window from the moment just before the voice enters, and extraction subtracts that backing layer's spectrum (a hand-rolled FFT + spectral-diff, all pure local DSP — zero AI calls) to recover the newly-added voice's pitch line, then transcribes it onto the round's tempo/key grid exactly like the solo path. Enabling the toggle auto-seeds a sensible backing window ending right where the voice enters; you can nudge it or set it from the playhead. Solo extraction is unchanged. Ah Poor Bird, Rose Rose Rose Red, and Zum Gali Gali carried melody/lyric choices that differ from other printed versions with no note explaining why — so a future accuracy check (or the AI evaluate feature) could mistake a deliberate variant for an error. Their notation now spells out each variant (Ah Poor Bird's C natural vs. the harmonic-minor C♯; Rose's verse and ending-note choices; Zum Gali Gali's D-minor transposition and refrain-only form) and cites the sources it was checked against.
+- **[issue-2121] Reference analysis can now pull a voice out of a stacked mix, not just solo spans.** The "analyze a reference's attached audio" workbench used to only transcribe time ranges where a voice sings *alone* — useless for the many layered TikTok builds where a new part enters over the layers already playing and never appears solo. Each segment now has a **Stacked** toggle: turn it on and set a short *backing reference* window from the moment just before the voice enters, and extraction subtracts that backing layer's spectrum (a hand-rolled FFT + spectral-diff, all pure local DSP — zero AI calls) to recover the newly-added voice's pitch line, then transcribes it onto the round's tempo/key grid exactly like the solo path. Enabling the toggle auto-seeds a sensible backing window ending right where the voice enters; you can nudge it or set it from the playhead. Solo extraction is unchanged.
+- **[issue-2108] Built-in rounds now document their melody variant points.** Ah Poor Bird, Rose Rose Rose Red, and Zum Gali Gali carried melody/lyric choices that differ from other printed versions with no note explaining why — so a future accuracy check (or the AI evaluate feature) could mistake a deliberate variant for an error. Their notation now spells out each variant (Ah Poor Bird's C natural vs. the harmonic-minor C♯; Rose's verse and ending-note choices; Zum Gali Gali's D-minor transposition and refrain-only form) and cites the sources it was checked against.
## Fixed
diff --git a/client/src/components/songs/ReferenceAnalysis.jsx b/client/src/components/songs/ReferenceAnalysis.jsx
index 70d4654f49..766758de98 100644
--- a/client/src/components/songs/ReferenceAnalysis.jsx
+++ b/client/src/components/songs/ReferenceAnalysis.jsx
@@ -261,6 +261,14 @@ const BASE_TARGET = '__base__';
// the pair IS "stacked mode" — the server persists it only when valid (#2121).
const isStacked = (seg) => Number.isFinite(seg.bgStartMs) && Number.isFinite(seg.bgEndMs) && seg.bgEndMs > seg.bgStartMs;
+// A backing reference shorter than this can't hold even one FFT analysis frame
+// (2048 samples ≥ 128 ms at 16 kHz, less at higher rates) — averaging its
+// spectrum would fail and extraction would silently fall back to no-subtraction
+// (i.e. transcribe the loud backing layer AS the new voice). So we refuse to
+// seed, commit, or extract a window narrower than this, surfacing a toast
+// instead of a wrong-but-silent result (#2121).
+const MIN_BACKING_MS = 300;
+
export default function ReferenceAnalysis({
reference, layers = [], scoreParts = [], baseScore = '', tempo = null, songKey = '',
onUpdateReference, onApplyPart, onClose,
@@ -341,13 +349,28 @@ export default function ReferenceAnalysis({
const bgEndMs = seg.startMs;
const preRoll = Math.min(4000, Math.max(1500, seg.endMs - seg.startMs));
const bgStartMs = Math.max(0, bgEndMs - preRoll);
- if (bgEndMs <= bgStartMs) {
+ if (bgEndMs - bgStartMs < MIN_BACKING_MS) {
toast.error('Not enough audio before this segment for a backing reference — move the segment start later.');
return;
}
setSegments(segments.map((s, i) => (i === idx ? { ...s, bgStartMs, bgEndMs } : s)));
}, [segments, setSegments]);
+ // Commit an edit to one end of the backing window, but only if the pair stays
+ // a valid, usable range — otherwise the segment would drop out of stacked mode
+ // (isStacked flips false) and silently revert to solo extraction. Reject the
+ // edit with a toast so the backing editor stays put and the mode is stable.
+ const commitBacking = useCallback((idx, field, ms) => {
+ const seg = segments[idx];
+ const bgStartMs = field === 'bgStartMs' ? ms : seg.bgStartMs;
+ const bgEndMs = field === 'bgEndMs' ? ms : seg.bgEndMs;
+ if (bgEndMs - bgStartMs < MIN_BACKING_MS) {
+ toast.error(`The backing reference must be at least ${(MIN_BACKING_MS / 1000).toFixed(1)}s and end before the voice enters.`);
+ return;
+ }
+ updateSegment(idx, { [field]: ms });
+ }, [segments, updateSegment]);
+
const seekTo = useCallback((ms) => {
const el = audioRef.current;
if (!el) return;
@@ -385,6 +408,13 @@ export default function ReferenceAnalysis({
const extractSegment = useCallback((seg) => {
if (!decoded) return;
const stacked = isStacked(seg);
+ // Defense-in-depth against a too-short backing window (e.g. a hand-edited or
+ // peer-synced segment the server accepted but that can't hold an FFT frame):
+ // don't let stacked extraction silently degrade to solo-on-the-mix.
+ if (stacked && (seg.bgEndMs - seg.bgStartMs) < MIN_BACKING_MS) {
+ toast.error(`The backing reference is too short — give it at least ${(MIN_BACKING_MS / 1000).toFixed(1)}s of the layers before the voice enters.`);
+ return;
+ }
setExtracting(true);
// Yield a frame so the button's busy state paints before the O(n·lag) DSP.
setTimeout(() => {
@@ -632,12 +662,12 @@ export default function ReferenceAnalysis({
<SecondsInput
key={`bg-start-${seg.bgStartMs}`}
valueMs={seg.bgStartMs}
- onCommit={(ms) => updateSegment(idx, { bgStartMs: ms })}
+ onCommit={(ms) => commitBacking(idx, 'bgStartMs', ms)}
ariaLabel="Backing reference start (seconds)"
/>
<span>s</span>
</label>
- <button type="button" onClick={() => updateSegment(idx, { bgStartMs: currentMs() })} title="Set backing start from playhead" aria-label="Set backing start from playhead" className="p-1 text-gray-500 hover:text-port-accent">
+ <button type="button" onClick={() => commitBacking(idx, 'bgStartMs', currentMs())} title="Set backing start from playhead" aria-label="Set backing start from playhead" className="p-1 text-gray-500 hover:text-port-accent">
<Flag size={14} />
</button>
<label className="flex items-center gap-1 text-xs text-gray-400">
@@ -645,12 +675,12 @@ export default function ReferenceAnalysis({
<SecondsInput
key={`bg-end-${seg.bgEndMs}`}
valueMs={seg.bgEndMs}
- onCommit={(ms) => updateSegment(idx, { bgEndMs: ms })}
+ onCommit={(ms) => commitBacking(idx, 'bgEndMs', ms)}
ariaLabel="Backing reference end (seconds)"
/>
<span>s</span>
</label>
- <button type="button" onClick={() => updateSegment(idx, { bgEndMs: currentMs() })} title="Set backing end from playhead" aria-label="Set backing end from playhead" className="p-1 text-gray-500 hover:text-port-accent">
+ <button type="button" onClick={() => commitBacking(idx, 'bgEndMs', currentMs())} title="Set backing end from playhead" aria-label="Set backing end from playhead" className="p-1 text-gray-500 hover:text-port-accent">
<FlagOff size={14} />
</button>
<button type="button" onClick={() => playSegment({ startMs: seg.bgStartMs, endMs: seg.bgEndMs })} title="Play the backing reference" aria-label="Play backing reference" className="p-1 text-gray-500 hover:text-port-accent">
diff --git a/client/src/components/songs/ReferenceAnalysis.test.jsx b/client/src/components/songs/ReferenceAnalysis.test.jsx
index a5288ca89c..0e644d2359 100644
--- a/client/src/components/songs/ReferenceAnalysis.test.jsx
+++ b/client/src/components/songs/ReferenceAnalysis.test.jsx
@@ -295,6 +295,34 @@ describe('ReferenceAnalysis — stacked-mix extraction (#2121)', () => {
expect(toastError).toHaveBeenCalledWith(expect.stringMatching(/not enough audio before/i));
});
+ it('rejects an invalid backing-window edit instead of silently dropping stacked mode', async () => {
+ installFakeAudio();
+ render(
+ <ControlledAnalysis
+ initialRef={{ ...baseRef, segments: [{ layerId: 'bass', startMs: 3000, endMs: 6000 }] }}
+ layers={layers}
+ scoreParts={[]}
+ tempo={60}
+ songKey="C"
+ onApplyPart={vi.fn()}
+ onClose={vi.fn()}
+ />,
+ );
+ // Enable stacked → backing [0, 3000] seeded, "Extract from mix" shows.
+ fireEvent.click(screen.getByRole('button', { name: /stacked/i }));
+ expect(await screen.findByRole('button', { name: /extract from mix/i })).toBeTruthy();
+
+ // Collapse the backing 'to' below 'from' + the minimum → the edit is
+ // rejected with a toast, and the segment STAYS in stacked mode (the row and
+ // "Extract from mix" persist), rather than silently reverting to solo.
+ const bgEnd = screen.getByLabelText(/backing reference end/i);
+ fireEvent.change(bgEnd, { target: { value: '0.1' } });
+ fireEvent.blur(bgEnd);
+ expect(toastError).toHaveBeenCalledWith(expect.stringMatching(/backing reference must be at least/i));
+ expect(screen.getByRole('button', { name: /extract from mix/i })).toBeTruthy();
+ expect(screen.getByLabelText(/backing reference end/i)).toBeTruthy();
+ });
+
it('recovers a new voice from a stacked mix end-to-end (toggle → extract from mix)', async () => {
// [0, 0.8s]: C4 backing alone. [0.8, 1.8s]: C4 + a new A4 (440) on top.
const audio = concatArr(harmonicTone(262, 0.8), mixArr(harmonicTone(262, 1.0), harmonicTone(440, 1.0)));
diff --git a/client/src/lib/referenceAnalysis.js b/client/src/lib/referenceAnalysis.js
index f66104f363..15c78994e3 100644
--- a/client/src/lib/referenceAnalysis.js
+++ b/client/src/lib/referenceAnalysis.js
@@ -301,11 +301,15 @@ const medianOf = (values) => {
* Estimate the fundamental frequency of a magnitude spectrum by weighted
* harmonic sum. For each candidate f0 on a ~5-cent grid across [minHz, maxHz]
* we sum interpolated magnitudes at its harmonics k·f0 (k = 1…H, below
- * Nyquist) weighted by 1/k. The 1/k weighting favors the TRUE fundamental over
- * its octave errors: f0/2 misses the strong first harmonic (its k=1 term lands
- * on empty spectrum) and 2·f0 drops the fundamental term entirely, so both
- * score below the real f0 — the frequency-domain analogue of the NSDF core's
- * first-strong-peak trick. `clarity` is the residual prominence of the winning
+ * Nyquist) weighted by 1/k. The 1/k weighting biases toward the TRUE
+ * fundamental over its octave errors: f0/2 misses the strong first harmonic
+ * (its k=1 term lands on empty spectrum) and 2·f0 drops the fundamental term
+ * entirely, so both usually score below the real f0 — the frequency-domain
+ * analogue of the NSDF core's first-strong-peak trick. It is a bias, not a
+ * guarantee: when spectral subtraction has gutted the fundamental bin (backing
+ * energy overlapped it), 2·f0 can still win and the note reads an octave high —
+ * which is why the result is a reviewable/editable PROPOSAL, not an auto-apply.
+ * `clarity` is the residual prominence of the winning
* candidate over the grid's median score, in [0, 1]: a clean harmonic series
* towers over a mostly-empty grid (→ 1); broadband noise scores flat (→ 0).
*