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

harden SongBook from review: locked attachment mutations, content deep-merge, import clamps, PD seed songs

[._.]/ Adam Eivydde7c562d493
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 5b1c35e044..730db937cf 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -109,6 +109,6 @@
- **[issue-2535] Paginate the remaining privacy + digital-twin list endpoints, completing the sweep.** The last unbounded index `GET`s flagged by #2535 — privacy `/vault`, `/orgs`, `/changes`, `/brokers`, `/broker-cases`, and digital-twin `/documents` — now opt into the shared `paginateArray` envelope exactly like the creative-catalog routes shipped in #2636: `isPaginationRequested(req.query)` gates a bounded `{ items, total, limit, offset }` response (`defaultLimit: 50`, `maxLimit: 500`) the moment a client passes `limit`/`offset`, while a param-less request returns the full array byte-for-byte, so no client change is required. Because the four privacy list-query schemas are `.strict()` (they'd reject unknown keys), a local `paginationQueryFields` fragment (`limit`/`offset` as passthrough strings — `parsePagination` does the parse+clamp) is spread into `privacyVaultListQuerySchema`, `privacyOrgListQuerySchema`, `privacyBrokerListQuerySchema`, and `privacyBrokerCaseListQuerySchema` in `privacyValidation.js`; the `/orgs` handler strips `limit`/`offset` before passing filters to `listOrgs` so pagination never leaks into the service query. New route tests cover the vault/orgs/changes/broker-cases envelopes (filters preserved) and the digital-twin documents envelope. This closes the remaining slice of #2535 (the CoS-tasks default-paginated shape and the creative-catalog/media routes shipped previously).
- **[issue-2642] Require provider/runner provenance before excluding environmental failures from task learning.** Environmental-failure exclusion previously trusted `errorAnalysis.category` alone, but that category is produced by the `analyzeAgentFailure` regex sweep over the failed agent's output tail — so ordinary task output could be misclassified as an infra category (e.g. a failing test whose tail prints "rate limit" tripping the unscoped `/rate.?limit/`) and the run would be silently diverted out of the learning aggregates as an "outage." `analyzeAgentFailure` now stamps an `origin` provenance marker on every classification: `'provider'`/`'runner'` when the match carries a genuine structured signal (an `API Error: NNN` line, a Node error code like `ECONNREFUSED`, a provider token like `overloaded_error`/`not_found_error`, or the structural startup-failure), and `'output-scan'` when it comes only from a loose keyword alternative. Mixed patterns (e.g. `API Error: 429` vs a bare `rate limit`) gate the promotion through a per-pattern `structuredMarker` sub-pattern via the new pure `resolvePatternOrigin` helper. The exclusion gate in `recordTaskCompletion` (`server/services/taskLearning/metrics.js`) now runs through a pure `shouldDivertToEnvironmental(outcomeSuccess, category, origin)` that additionally requires `origin !== 'output-scan'`, so an output-scan false positive counts as a genuine failure while structured signals stay excluded. Back-compat is preserved: an `errorAnalysis` with no `origin` (older records / federated peers) keeps the category-only behavior, and the routing-side signature filter is unchanged (it already fails safe). New unit tests cover the provenance stamping across the classifiers and all three acceptance cases in the gate.
- **[issue-2532] Finish thinning the Universe Builder route into focused feature lifecycles.** `pages/UniverseBuilder.jsx` is now a 9-line compatibility shell over the presentational editor, while draft hydration/persistence and canon-safe merges live in `useUniverseDraft`, AI expansion/refinement lives in `useUniverseExpand`, and bulk-render configuration plus per-entry job queues live in `useUniverseRender`. The existing Bible/Cast/Places/Objects panels moved out of the route module with their behavior and named exports preserved. New hook tests cover hydration, dirty saves, deletion-wins canon merges, locked expansion rows, all-trunk render selection, and backend guards; the full client suite remains green.
-- **SongBook — a Brain repertoire for guitar tabs, chord sheets, and sheet music with learning-stage tracking and an autoscrolling play view.** New `/songbook` index (filter by stage/instrument/tag/search, all URL-addressable) and `/songbook/:id` full-bleed viewer: tab/chord/ChordPro content renders with highlighted chord tokens, section headers, and horizontally-scrollable tab staffs; an Ultimate-Guitar-style autoscroll (play/pause, speed slider, keyboard shortcuts, screen wake-lock) paces long charts, with non-destructive transpose and font-size controls persisted per song. Each song tracks a learning stage (`new → learning → learned → memorized`) flippable from the card or viewer. Songs import by paste (auto-cleanup of HTML remnants + format detection) or by URL — a server-side SSRF-guarded fetch with an Ultimate Guitar extractor and generic `<pre>`/plain-text fallbacks returns an editable draft, never auto-saving. Sheet-music/MIDI/image attachments upload per song: metadata (name, size, SHA-256) lives in the synced record while bytes stay machine-local under `data/brain/songbook/` (peers show "not on this machine"). Songs are a first-class Brain entity type (`data/brain/songs.json`), so they federate across machines with LWW sync, tombstone deletes, and reconcile coverage automatically — and they're reachable from ⌘K and voice nav (`nav.brain.songbook`). New pure `tabNotation` lib (line classification, ChordPro, transpose with column preservation, paste normalization) with extensive unit tests.
+- **SongBook — a Brain repertoire for guitar tabs, chord sheets, and sheet music with learning-stage tracking and an autoscrolling play view.** New `/songbook` index (filter by stage/instrument/tag/search, all URL-addressable) and `/songbook/:id` full-bleed viewer: tab/chord/ChordPro content renders with highlighted chord tokens, section headers, and horizontally-scrollable tab staffs; an Ultimate-Guitar-style autoscroll (play/pause, speed slider, keyboard shortcuts, screen wake-lock) paces long charts, with non-destructive transpose and font-size controls persisted per song. Each song tracks a learning stage (`new → learning → learned → memorized`) flippable from the card or viewer. Songs import by paste (auto-cleanup of HTML remnants + format detection) or by URL — a server-side SSRF-guarded fetch with an Ultimate Guitar extractor and generic `<pre>`/plain-text fallbacks returns an editable draft, never auto-saving. Sheet-music/MIDI/image attachments upload per song: metadata (name, size, SHA-256) lives in the synced record while bytes stay machine-local under `data/brain/songbook/` (peers show "not on this machine"). Songs are a first-class Brain entity type (`data/brain/songs.json`), so they federate across machines with LWW sync, tombstone deletes, and reconcile coverage automatically — and they're reachable from ⌘K and voice nav (`nav.brain.songbook`). New pure `tabNotation` lib (line classification, ChordPro, transpose with column preservation, paste normalization) with extensive unit tests. Ships three public-domain seed songs — "House of the Rising Sun" arranged for guitar, piano, and ukulele — seeded into existing installs by migration 190 (never overwriting a user-edited, synced, or deleted copy). The parser also handles dash-joined chord changes (`Am-Am7` classifies, renders, and transposes as one token) and Unicode accidentals (♯/♭ normalize to #/b on paste so `F♯m` transposes correctly).
- **Fix the app-manager Git tab's "Clean N merged" button counting worktree-locked branches, so cleanup deleted zero and toasted "No merged branches to clean up".** `getBranches` marked a local branch `merged: true` from `git branch --merged` alone, but `deleteMergedBranches` (correctly) skips branches checked out in a worktree — `git branch -d` can't delete them. On any install with active CoS-agent/claim worktrees, those merged-but-locked branches inflated the button's count while yielding no deletions. `getBranches` now also returns a `worktree` flag (branch checked out in another worktree), the Git tab's `localMergedCount` counts only `merged && !worktree` so the button reflects what the server will actually delete, and locked branches render a `worktree` badge next to `merged` so the user sees why they linger. Server + client tests cover the count and badge.
diff --git a/PLAN.md b/PLAN.md
index e569068174..3339c5b825 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -32,6 +32,9 @@ by `/do:replan --issues`:
`routes/attachments.js` + `routes/brainSongbook.js`). Left out of the SongBook
pass because uploads.js has a different response shape and uses the full
`EXTENSION_MIME_MAP` rather than an allowlist.
+ Also fix while there: `routes/attachments.js`'s 50MB cap is unreachable —
+ base64 ×4/3 inflation exceeds the 55mb express.json body limit above ~41MB
+ (same latent mismatch fixed in `routes/brainSongbook.js`, which now caps at 40MB).
- [ ] SongBook practice/spaced-rep integration (SM-2 style, cf.
`meatspacePostMemory`) — the `stage` field on `songs` records is manual in v1
(`server/lib/brainValidation.js` `songStageEnum`).
diff --git a/client/src/hooks/useWakeLock.js b/client/src/hooks/useWakeLock.js
index 59ca16ab6a..5138fc28e5 100644
--- a/client/src/hooks/useWakeLock.js
+++ b/client/src/hooks/useWakeLock.js
@@ -8,7 +8,10 @@ import { useEffect, useRef } from 'react';
* The browser force-releases wake locks when the tab is hidden, so a
* visibilitychange listener re-acquires on return while still active. A
* generation counter makes a request that resolves after deactivation/unmount
- * release itself immediately instead of leaking a held lock.
+ * release itself immediately instead of leaking a held lock, and an in-flight
+ * request ref keeps concurrent same-generation acquires from racing (two
+ * pending wakeLock.request calls — the second overwriting lockRef while the
+ * first's sentinel is never released).
*/
export default function useWakeLock(active) {
const lockRef = useRef(null);
@@ -19,17 +22,31 @@ export default function useWakeLock(active) {
if (!active || !wakeLock?.request) return undefined;
const generation = ++generationRef.current;
+ // In-flight request for THIS activation — effect-local so a stale
+ // generation's pending request never blocks the next activation's acquire
+ // (cross-generation staleness is the generation counter's job).
+ let pending = null;
- const acquire = async () => {
- const lock = await wakeLock.request('screen').catch(() => null);
- if (!lock) return;
- // Deactivated (or re-activated) while the request was in flight — this
- // acquisition is stale; release it rather than adopting it.
- if (generationRef.current !== generation) {
- lock.release().catch(() => {});
- return;
- }
- lockRef.current = lock;
+ const acquire = () => {
+ // Re-entrancy guard: skip when a request is already pending, or a live
+ // (not UA-released) lock is already held — a second concurrent request
+ // would leak whichever sentinel loses the lockRef assignment.
+ if (pending) return;
+ if (lockRef.current && !lockRef.current.released) return;
+ pending = wakeLock.request('screen')
+ .catch(() => null)
+ .then((lock) => {
+ pending = null;
+ if (!lock) return;
+ // Deactivated (or re-activated) while the request was in flight, or
+ // a live lock is somehow already held — this acquisition is stale;
+ // release it rather than adopting it.
+ if (generationRef.current !== generation || (lockRef.current && !lockRef.current.released)) {
+ lock.release().catch(() => {});
+ return;
+ }
+ lockRef.current = lock;
+ });
};
const onVisibility = () => {
diff --git a/client/src/lib/tabNotation.js b/client/src/lib/tabNotation.js
index 30620f96de..09eee7b0a9 100644
--- a/client/src/lib/tabNotation.js
+++ b/client/src/lib/tabNotation.js
@@ -55,6 +55,17 @@ const isChordToken = (token) => token.length > 0 && token.length <= 12 && CHORD_
// tokens that fail the density gate anyway.
const isAmbiguousChordToken = (token) => /^[A-G]$/.test(token);
+// Dash-joined chord changes ("Am-Am7", "E-Em7") — chord sheets write these
+// for a quick change inside one bar. Valid only when every dash-separated
+// part is a chord token AND at least one part is unambiguous, so hyphenated
+// lyric fragments ("A-round") and letter runs ("A-B-C") stay words.
+const isDashChordToken = (token) => {
+ if (token.length > 25 || !token.includes('-')) return false;
+ const parts = token.split('-');
+ if (parts.length < 2) return false;
+ return parts.every(isChordToken) && parts.some((p) => !isAmbiguousChordToken(p));
+};
+
// Rhythm/bar noise commonly interleaved on chord lines — ignored by the
// density calculation rather than counted against it.
const FILLER_TOKEN_RE = /^(?:\|+|\/+|%|-+|\.+|,|[([]?x\d{1,2}[)\]]?)$/i;
@@ -65,6 +76,7 @@ const chordTokenInfo = (token, col) => {
if (isChordToken(token)) return { kind: 'chord', name: token, col };
const paren = /^\((.+)\)$/.exec(token);
if (paren && isChordToken(paren[1])) return { kind: 'chord', name: paren[1], col: col + 1 };
+ if (isDashChordToken(token)) return { kind: 'chord', name: token, col };
if (FILLER_TOKEN_RE.test(token)) return { kind: 'filler' };
return { kind: 'other' };
};
@@ -120,7 +132,7 @@ const parseChordLyric = (line) => {
let m;
while ((m = re.exec(line))) {
bare += line.slice(last, m.index);
- if (isChordToken(m[1])) chords.push({ name: m[1], col: bare.length });
+ if (isChordToken(m[1]) || isDashChordToken(m[1])) chords.push({ name: m[1], col: bare.length });
else bare += m[0];
last = m.index + m[0].length;
}
@@ -178,7 +190,9 @@ const classifyLine = (raw) => {
if (GENERIC_DIRECTIVE_RE.test(line)) return { type: 'text', text: line, chordpro: true };
const bracket = BRACKET_SECTION_RE.exec(line);
- if (bracket && !isChordToken(bracket[1].trim())) {
+ // A whole-line bracketed chord — plain ([Am]) or dash-joined ([Am-Am7]) — is
+ // ChordPro inline notation, not a section header.
+ if (bracket && !isChordToken(bracket[1].trim()) && !isDashChordToken(bracket[1].trim())) {
return { type: 'section', text: line, label: bracket[1].trim() };
}
@@ -281,9 +295,10 @@ const detabLine = (line) => {
// Clean up pasted content: CRLF/CR → LF, <br>/<p>/<div> boundaries → newlines,
// strip real HTML tags (a tag must start with a letter, so tab harmonics like
-// e|--<7>--| survive), decode common entities, expand tabs, trim trailing
-// whitespace per line, collapse runs of 3+ blank lines to 2, and trim
-// leading/trailing blank lines.
+// e|--<7>--| survive), decode common entities, map Unicode accidentals
+// (♯ → #, ♭ → b) so 'F♯m' classifies and transposes like 'F#m', expand tabs,
+// trim trailing whitespace per line, collapse runs of 3+ blank lines to 2, and
+// trim leading/trailing blank lines.
export const normalizePastedTab = (text) => {
if (typeof text !== 'string' || !text) return '';
const cleaned = decodeEntities(
@@ -293,6 +308,8 @@ export const normalizePastedTab = (text) => {
.replace(/<\/?[A-Za-z][A-Za-z0-9-]*(?:\s[^>]*)?\/?>/g, ''),
);
return cleaned
+ .replace(/♯/g, '#')
+ .replace(/♭/g, 'b')
.split('\n')
.map((line) => detabLine(line).replace(/\s+$/, ''))
.join('\n')
@@ -328,6 +345,9 @@ export const transposeChordName = (name, n) => {
const raw = String(name ?? '');
if (!Number.isFinite(n)) return raw;
if (/^N\.?C\.?$/.test(raw)) return raw;
+ if (isDashChordToken(raw)) {
+ return raw.split('-').map((part) => transposeChordName(part, n)).join('-');
+ }
if (!isChordToken(raw)) return raw;
const m = /^([A-G])([#b]?)(.*)$/.exec(raw);
if (!m) return raw;
@@ -346,7 +366,7 @@ export const transposeChordName = (name, n) => {
};
const transposeToken = (token, n) => {
- if (isChordToken(token)) return transposeChordName(token, n);
+ if (isChordToken(token) || isDashChordToken(token)) return transposeChordName(token, n);
const paren = /^\((.+)\)$/.exec(token);
if (paren && isChordToken(paren[1])) return `(${transposeChordName(paren[1], n)})`;
return token;
@@ -381,7 +401,9 @@ export const transposeText = (text, n) => {
if (c.type === 'chords') return transposeChordLine(raw, Math.trunc(n));
if (c.type === 'chordlyric') {
return raw.replace(/\[([^\]]*)\]/g, (all, inner) =>
- isChordToken(inner) ? `[${transposeChordName(inner, n)}]` : all,
+ isChordToken(inner) || isDashChordToken(inner)
+ ? `[${transposeChordName(inner, n)}]`
+ : all,
);
}
return raw;
diff --git a/client/src/lib/tabNotation.test.js b/client/src/lib/tabNotation.test.js
index 2b2864543e..ef2f5bdd85 100644
--- a/client/src/lib/tabNotation.test.js
+++ b/client/src/lib/tabNotation.test.js
@@ -98,6 +98,21 @@ describe('parseTabSheet — line classification', () => {
expect(types('C Am F G repeat')).toEqual(['chords']); // 4/5 = 80%
});
+ it('classifies dash-joined chord changes as chords with the joined token as name', () => {
+ const am = parseTabSheet('Am-Am7').lines[0];
+ expect(am.type).toBe('chords');
+ expect(am.chords).toEqual([{ name: 'Am-Am7', col: 0 }]);
+ const e = parseTabSheet('E-Em7').lines[0];
+ expect(e.type).toBe('chords');
+ expect(e.chords).toEqual([{ name: 'E-Em7', col: 0 }]);
+ });
+
+ it('keeps hyphenated lyric fragments and bare letter runs as text', () => {
+ expect(types('A-round the corner')).toEqual(['text']);
+ // Every dash part is an ambiguous bare root — stays a word, not a chord.
+ expect(types('A-B')).toEqual(['text']);
+ });
+
it('promotes only the line directly under a chords line to lyric', () => {
const sheet = 'C G\nFirst invented line\nSecond invented line';
expect(types(sheet)).toEqual(['chords', 'lyric', 'text']);
@@ -298,6 +313,15 @@ describe('normalizePastedTab', () => {
expect(normalizePastedTab('&bogus; C G')).toBe('&bogus; C G');
});
+ it('maps Unicode accidentals to ASCII so mixed lines classify and transpose', () => {
+ expect(normalizePastedTab('F♯m B♭')).toBe('F#m Bb');
+ // After normalize, the line classifies as chords and transposes; the raw
+ // parser (no normalize) would treat 'F♯m' as a word and leave it behind.
+ const normalized = normalizePastedTab('F♯m A');
+ expect(parseTabSheet(normalized).lines[0].type).toBe('chords');
+ expect(transposeText(normalized, 2)).toBe('G#m B');
+ });
+
it('expands tabs to 8-column stops', () => {
expect(normalizePastedTab('C\tG')).toBe('C G');
expect(normalizePastedTab('Am7\tD')).toBe('Am7 D');
@@ -365,6 +389,14 @@ describe('transposeChordName', () => {
expect(transposeChordName('G', 1)).toBe('Ab');
});
+ it('transposes each part of a dash-joined chord change', () => {
+ expect(transposeChordName('Am-Am7', 2)).toBe('Bm-Bm7');
+ expect(transposeChordName('E-Em7', 2)).toBe('F#-F#m7');
+ // Not a dash chord (all-ambiguous / lyric fragment) → untouched.
+ expect(transposeChordName('A-B', 2)).toBe('A-B');
+ expect(transposeChordName('A-round', 2)).toBe('A-round');
+ });
+
it('passes through N.C. and non-chords unchanged', () => {
expect(transposeChordName('N.C.', 5)).toBe('N.C.');
expect(transposeChordName('hello', 3)).toBe('hello');
@@ -413,6 +445,18 @@ describe('transposeText', () => {
expect(transposeText('[C]Hum a [G]made-up [Am]tune', 2)).toBe('[D]Hum a [A]made-up [Bm]tune');
});
+ it('transposes dash-joined chord lines and keeps non-chord dash words', () => {
+ expect(transposeText('Am-Am7\nE-Em7', 2)).toBe('Bm-Bm7\nF#-F#m7');
+ expect(transposeText('A-round the corner', 2)).toBe('A-round the corner');
+ expect(transposeText('A-B', 2)).toBe('A-B');
+ });
+
+ it('transposes inline ChordPro dash chords — mid-lyric and whole-line', () => {
+ expect(transposeText('[Am-Am7]la la', 2)).toBe('[Bm-Bm7]la la');
+ // A whole-line [Am-Am7] is inline chord notation, not a section header.
+ expect(transposeText('[Am-Am7]', 2)).toBe('[Bm-Bm7]');
+ });
+
it('leaves non-chord brackets alone on chordlyric lines', () => {
expect(transposeText('[C]La la [weird] la', 2)).toBe('[D]La la [weird] la');
});
diff --git a/client/src/pages/SongBookImport.jsx b/client/src/pages/SongBookImport.jsx
index 5e39abc8ed..11794eeb5c 100644
--- a/client/src/pages/SongBookImport.jsx
+++ b/client/src/pages/SongBookImport.jsx
@@ -90,9 +90,11 @@ export default function SongBookImport() {
const onPasteButton = useCallback(async () => {
const text = await readClipboard();
if (text == null) { toast.error('Clipboard unavailable — paste into the box instead'); return; }
- const clean = normalizePastedTab(text);
- setPasted(clean);
- applyMetaDefaults(parseTabSheet(clean).meta);
+ // Store the RAW clipboard text — the `normalized` memo runs the single
+ // normalize pass. Pre-normalizing here would double entity-decode
+ // (&amp;lt; → &lt; → <) and strip entity-encoded markup as if it were tags.
+ setPasted(text);
+ applyMetaDefaults(parseTabSheet(normalizePastedTab(text)).meta);
}, [applyMetaDefaults]);
// Error mapping lives in the .catch alone — it swallows every rejection, so
@@ -135,8 +137,12 @@ export default function SongBookImport() {
};
if (tab === 'url' && fetched?.sourceUrl) body.sourceUrl = fetched.sourceUrl;
if (tab === 'paste') {
- if (pasteMeta.key) body.key = pasteMeta.key;
- if (Number.isInteger(pasteMeta.capo)) body.capo = pasteMeta.capo;
+ // Clamp ChordPro meta to songInputSchema's bounds — a pasted {capo: 13}
+ // or an over-long {key:} must not 400 the POST with no form field to fix.
+ if (pasteMeta.key) body.key = String(pasteMeta.key).slice(0, 20);
+ if (Number.isInteger(pasteMeta.capo) && pasteMeta.capo >= 0 && pasteMeta.capo <= 12) {
+ body.capo = pasteMeta.capo;
+ }
}
const song = await createSong(body, { silent: true });
if (song?.id) navigate(`/songbook/${song.id}`);
diff --git a/client/src/pages/SongBookImport.test.jsx b/client/src/pages/SongBookImport.test.jsx
new file mode 100644
index 0000000000..eddc591ed5
--- /dev/null
+++ b/client/src/pages/SongBookImport.test.jsx
@@ -0,0 +1,72 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import { MemoryRouter, Routes, Route } from 'react-router-dom';
+
+// Mock the api barrel (RoundEditor.test.jsx harness style).
+const api = vi.hoisted(() => ({
+ createSong: vi.fn(),
+ importSongFromUrl: vi.fn(),
+}));
+vi.mock('../services/api', () => api);
+vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));
+
+const clipboard = vi.hoisted(() => ({ readClipboard: vi.fn() }));
+vi.mock('../lib/clipboard.js', () => clipboard);
+
+import SongBookImport from './SongBookImport.jsx';
+
+const renderPage = (path = '/songbook/import') => render(
+ <MemoryRouter initialEntries={[path]}>
+ <Routes><Route path="/songbook/import" element={<SongBookImport />} /></Routes>
+ </MemoryRouter>,
+);
+
+// All fixture content is invented (privacy convention).
+describe('SongBookImport', () => {
+ beforeEach(() => {
+ api.createSong.mockReset().mockResolvedValue({ id: 'new-song-1' });
+ api.importSongFromUrl.mockReset();
+ clipboard.readClipboard.mockReset();
+ });
+
+ it('paste button stores the RAW clipboard text — normalization runs exactly once', async () => {
+ // Pre-normalizing before setPasted would double entity-decode:
+ // &amp;lt; → &lt; (first pass) → < (memo's second pass), turning
+ // entity-encoded markup into tags that get stripped.
+ clipboard.readClipboard.mockResolvedValue('&amp;lt; C G Am');
+ renderPage();
+ fireEvent.click(screen.getByRole('button', { name: 'Paste' }));
+ const textarea = await screen.findByLabelText('Pasted tab content');
+ await waitFor(() => expect(textarea.value).toBe('&amp;lt; C G Am'));
+
+ // Save sends the single-pass-normalized text (&amp;lt; → &lt;, not <).
+ fireEvent.change(screen.getByLabelText('Title'), { target: { value: 'Example Song' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save song' }));
+ await waitFor(() => expect(api.createSong).toHaveBeenCalled());
+ const [body] = api.createSong.mock.calls[0];
+ expect(body.content.text).toBe('&lt; C G Am');
+ });
+
+ it('clamps ChordPro meta before sending: out-of-range capo dropped, long key sliced to 20', async () => {
+ const sheet = '{key: ThisKeyNameIsWayTooLongForTheSchema}\n{capo: 13}\nC G Am\nInvented lyric line';
+ renderPage();
+ fireEvent.change(screen.getByLabelText('Pasted tab content'), { target: { value: sheet } });
+ fireEvent.change(screen.getByLabelText('Title'), { target: { value: 'Example Song' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save song' }));
+ await waitFor(() => expect(api.createSong).toHaveBeenCalled());
+ const [body] = api.createSong.mock.calls[0];
+ expect(body.key).toBe('ThisKeyNameIsWayTooL'); // sliced at songInputSchema's 20-char max
+ expect('capo' in body).toBe(false); // 13 is outside 0..12 — dropped, POST can't 400
+ });
+
+ it('sends an in-range pasted capo through unchanged', async () => {
+ renderPage();
+ fireEvent.change(screen.getByLabelText('Pasted tab content'), {
+ target: { value: '{capo: 3}\nC G Am' },
+ });
+ fireEvent.change(screen.getByLabelText('Title'), { target: { value: 'Example Song' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save song' }));
+ await waitFor(() => expect(api.createSong).toHaveBeenCalled());
+ expect(api.createSong.mock.calls[0][0].capo).toBe(3);
+ });
+});
diff --git a/client/src/pages/SongBookViewer.jsx b/client/src/pages/SongBookViewer.jsx
index 2417c38f3e..91c1eb858e 100644
--- a/client/src/pages/SongBookViewer.jsx
+++ b/client/src/pages/SongBookViewer.jsx
@@ -46,12 +46,18 @@ import { transposeText } from '../lib/tabNotation.js';
import { safeReadStorage, safeWriteStorage } from '../lib/safeStorage.js';
import { formatBytes } from '../utils/formatters';
import { isHttpUrl } from '../utils/urlNormalize';
-import { readFileAsBase64, ATTACHMENT_MAX_FILE_SIZE } from '../utils/fileUpload';
+import { readFileAsBase64 } from '../utils/fileUpload';
import {
getSong, updateSong, deleteSong,
listSongAttachments, uploadSongAttachment, deleteSongAttachment, songAttachmentUrl,
} from '../services/api';
+// Mirrors MAX_ATTACHMENT_SIZE in server/routes/brainSongbook.js — 40MB, the
+// largest raw payload that survives base64 ×4/3 inflation under the server's
+// 55mb express.json limit. Deliberately NOT utils/fileUpload's
+// ATTACHMENT_MAX_FILE_SIZE (50MB) — other surfaces still use that cap.
+const SONGBOOK_MAX_FILE_SIZE = 40 * 1024 * 1024;
+
const TRANSPOSE_MIN = -11;
const TRANSPOSE_MAX = 11;
const FONT_MIN = 0.625;
@@ -91,9 +97,15 @@ export default function SongBookViewer() {
const [song, setSong] = useState(null);
const [loading, setLoading] = useState(true);
const [notFound, setNotFound] = useState(false);
+ const [loadError, setLoadError] = useState(false);
+ // Bump to re-run the load effect (the Retry button on a non-404 failure).
+ const [retryKey, setRetryKey] = useState(0);
const [draft, setDraft] = useState(null);
// null = not fetched yet, [] = fetched-and-empty (sentinel convention).
const [attachments, setAttachments] = useState(null);
+ // Once any attachment mutation has run, the (slow) initial list response is
+ // stale — it must not clobber the optimistic upload/delete state.
+ const attachmentsMutatedRef = useRef(false);
const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();
useEffect(() => {
@@ -101,7 +113,9 @@ export default function SongBookViewer() {
setSong(null);
setDraft(null);
setAttachments(null);
+ attachmentsMutatedRef.current = false;
setNotFound(false);
+ setLoadError(false);
setLoading(true);
getSong(id, { silent: true })
.then((s) => {
@@ -109,13 +123,23 @@ export default function SongBookViewer() {
setSong(s);
setDraft(toDraft(s));
})
- .catch(() => { if (!cancelled) setNotFound(true); })
+ .catch((err) => {
+ if (cancelled) return;
+ // Only a genuine 404 means "not found" — anything else (network blip,
+ // 5xx) gets a retryable load-error state instead of a lying fallback.
+ if (err?.status === 404) setNotFound(true);
+ else setLoadError(true);
+ })
.finally(() => { if (!cancelled) setLoading(false); });
listSongAttachments(id, { silent: true })
- .then((list) => { if (!cancelled) setAttachments(Array.isArray(list) ? list : []); })
- .catch(() => { if (!cancelled) setAttachments([]); });
+ .then((list) => {
+ if (!cancelled && !attachmentsMutatedRef.current) setAttachments(Array.isArray(list) ? list : []);
+ })
+ .catch(() => {
+ if (!cancelled && !attachmentsMutatedRef.current) setAttachments([]);
+ });
return () => { cancelled = true; };
- }, [id]);
+ }, [id, retryKey]);
// --- Transpose: render-time only, persisted per song via safeStorage.
const [transpose, setTransposeState] = useState(0);
@@ -215,13 +239,14 @@ export default function SongBookViewer() {
const fileInputRef = useRef(null);
const [uploadFiles, uploading] = useAsyncAction(async (files) => {
for (const file of Array.from(files)) {
- if (file.size > ATTACHMENT_MAX_FILE_SIZE) {
- toast.error(`"${file.name}" exceeds ${Math.round(ATTACHMENT_MAX_FILE_SIZE / 1024 / 1024)}MB limit`);
+ if (file.size > SONGBOOK_MAX_FILE_SIZE) {
+ toast.error(`"${file.name}" exceeds ${Math.round(SONGBOOK_MAX_FILE_SIZE / 1024 / 1024)}MB limit`);
continue;
}
const data = await readFileAsBase64(file);
const res = await uploadSongAttachment(id, { filename: file.name, data }, { silent: true });
if (res?.attachment) {
+ attachmentsMutatedRef.current = true;
setAttachments((prev) => [...(prev || []), { ...res.attachment, present: true }]);
}
}
@@ -230,6 +255,7 @@ export default function SongBookViewer() {
const onDeleteAttachment = useCallback((filename) => confirmDelete(() =>
deleteSongAttachment(id, filename, { silent: true })
.then((res) => {
+ attachmentsMutatedRef.current = true;
// Server returns the updated meta list; carry over local present flags.
setAttachments((prev) => (res?.attachments || []).map((meta) => ({
...meta,
@@ -253,6 +279,28 @@ export default function SongBookViewer() {
);
}
+ if (loadError) {
+ return (
+ <div className="flex flex-col h-full items-center justify-center text-center p-6">
+ <ListMusic size={32} className="text-gray-600 mb-3" />
+ <h2 className="text-white font-semibold mb-1">Couldn't load this song</h2>
+ <p className="text-gray-400 text-sm mb-4">Something went wrong fetching it — the song may still exist.</p>
+ <div className="flex items-center gap-3">
+ <button
+ type="button"
+ onClick={() => setRetryKey((k) => k + 1)}
+ className="px-4 py-2 rounded-lg text-sm bg-port-accent text-white hover:bg-port-accent/90"
+ >
+ Retry
+ </button>
+ <Link to="/songbook" className="px-4 py-2 rounded-lg text-sm bg-port-accent/10 text-port-accent hover:bg-port-accent/20">
+ Back to SongBook
+ </Link>
+ </div>
+ </div>
+ );
+ }
+
if (loading || !song) {
return <p className="p-6 text-sm text-gray-500">Loading song…</p>;
}
diff --git a/client/src/pages/SongBookViewer.test.jsx b/client/src/pages/SongBookViewer.test.jsx
index 472a6c91f0..fabeff0e0b 100644
--- a/client/src/pages/SongBookViewer.test.jsx
+++ b/client/src/pages/SongBookViewer.test.jsx
@@ -77,6 +77,20 @@ describe('SongBookViewer', () => {
expect(screen.getByText('Back to SongBook')).toBeTruthy();
});
+ it('shows a retryable load-error state (not "not found") for a non-404 failure', async () => {
+ api.getSong.mockRejectedValueOnce(Object.assign(new Error('boom'), { status: 500 }));
+ api.listSongAttachments.mockRejectedValue(new Error('boom'));
+ renderPage();
+ expect(await screen.findByText("Couldn't load this song")).toBeTruthy();
+ expect(screen.queryByText('Song not found')).toBeNull();
+
+ // Retry re-runs the load; the next attempt succeeds and renders the song.
+ api.getSong.mockResolvedValue(song());
+ api.listSongAttachments.mockResolvedValue([]);
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+ expect(await screen.findByText('Example Song')).toBeTruthy();
+ });
+
it('flips the stage via a partial updateSong and merges the server record', async () => {
api.updateSong.mockResolvedValue(song({ stage: 'learned' }));
renderPage();
diff --git a/data.reference/brain/songs.json b/data.reference/brain/songs.json
index 79802cb55a..509579ced9 100644
--- a/data.reference/brain/songs.json
+++ b/data.reference/brain/songs.json
@@ -1,3 +1,73 @@
{
- "records": {}
+ "records": {
+ "song-seed-hotrs-guitar": {
+ "title": "House of the Rising Sun",
+ "artist": "Traditional",
+ "instrument": "guitar",
+ "stage": "new",
+ "tags": [
+ "folk",
+ "traditional",
+ "public-domain"
+ ],
+ "key": "Am",
+ "capo": 0,
+ "tuning": "EADGBE standard",
+ "sourceUrl": "",
+ "content": {
+ "format": "tab",
+ "text": "[Verse 1]\nAm C D F\nThere is a house in New Orleans\nAm C E\nThey call the Rising Sun\nAm C D F\nAnd it's been the ruin of many a poor boy\nAm E Am\nAnd God, I know I'm one\n\n[Verse 2]\nAm C D F\nMy mother was a tailor\nAm C E\nShe sewed my new blue jeans\nAm C D F\nMy father was a gambling man\nAm E Am\nDown in New Orleans\n\n[Verse 3]\nAm C D F\nOh mother, tell your children\nAm C E\nNot to do what I have done\nAm C D F\nSpend your lives in sin and misery\nAm E Am\nIn the house of the Rising Sun"
+ },
+ "notes": "Arpeggiated 6/8 — the classic pattern. Traditional song, public domain.",
+ "attachments": [],
+ "createdAt": "2026-07-15T00:00:00.000Z",
+ "updatedAt": "2026-07-15T00:00:00.000Z"
+ },
+ "song-seed-hotrs-piano": {
+ "title": "House of the Rising Sun",
+ "artist": "Traditional",
+ "instrument": "piano",
+ "stage": "new",
+ "tags": [
+ "folk",
+ "traditional",
+ "public-domain"
+ ],
+ "key": "Am",
+ "capo": 0,
+ "tuning": "",
+ "sourceUrl": "",
+ "content": {
+ "format": "tab",
+ "text": "[Verse 1]\nAm C D F\nThere is a house in New Orleans\nAm C E\nThey call the Rising Sun\nAm C D F\nAnd it's been the ruin of many a poor boy\nAm E Am\nAnd God, I know I'm one\n\n[Verse 2]\nAm C D F\nMy mother was a tailor\nAm C E\nShe sewed my new blue jeans\nAm C D F\nMy father was a gambling man\nAm E Am\nDown in New Orleans\n\n[Verse 3]\nAm C D F\nOh mother, tell your children\nAm C E\nNot to do what I have done\nAm C D F\nSpend your lives in sin and misery\nAm E Am\nIn the house of the Rising Sun"
+ },
+ "notes": "Roll the chords in 6/8; melody sits on top of Am–C–D–F. Traditional song, public domain.",
+ "attachments": [],
+ "createdAt": "2026-07-15T00:00:00.000Z",
+ "updatedAt": "2026-07-15T00:00:00.000Z"
+ },
+ "song-seed-hotrs-ukulele": {
+ "title": "House of the Rising Sun",
+ "artist": "Traditional",
+ "instrument": "ukulele",
+ "stage": "new",
+ "tags": [
+ "folk",
+ "traditional",
+ "public-domain"
+ ],
+ "key": "Am",
+ "capo": 0,
+ "tuning": "GCEA",
+ "sourceUrl": "",
+ "content": {
+ "format": "tab",
+ "text": "[Verse 1]\nAm C D F\nThere is a house in New Orleans\nAm C E\nThey call the Rising Sun\nAm C D F\nAnd it's been the ruin of many a poor boy\nAm E Am\nAnd God, I know I'm one\n\n[Verse 2]\nAm C D F\nMy mother was a tailor\nAm C E\nShe sewed my new blue jeans\nAm C D F\nMy father was a gambling man\nAm E Am\nDown in New Orleans\n\n[Verse 3]\nAm C D F\nOh mother, tell your children\nAm C E\nNot to do what I have done\nAm C D F\nSpend your lives in sin and misery\nAm E Am\nIn the house of the Rising Sun"
+ },
+ "notes": "Same shapes as guitar — Am, C, D, F, E are all first-position on uke. Traditional song, public domain.",
+ "attachments": [],
+ "createdAt": "2026-07-15T00:00:00.000Z",
+ "updatedAt": "2026-07-15T00:00:00.000Z"
+ }
+ }
}
diff --git a/docs/plans/2026-07-15-songbook.md b/docs/plans/2026-07-15-songbook.md
index 3b6673ae3d..131d407fba 100644
--- a/docs/plans/2026-07-15-songbook.md
+++ b/docs/plans/2026-07-15-songbook.md
@@ -232,3 +232,24 @@ are kept as the original design record.
Gmail sync), and the attachment upload/serve pipeline via
`saveBase64Upload` / `serveLocalFile` in `server/lib/fileUtils.js` with a
curated `SONGBOOK_ATTACHMENT_EXTENSIONS` allowlist.
+- **PUT content deep-merge.** `songUpdateSchema` (brainValidation.js) is
+ defaults-free down to the nested `content` object, and the PUT handler
+ deep-merges a partial `content` over the stored song's content — so
+ `{ content: { text } }` no longer resets format to 'tab' and
+ `{ content: { format } }` no longer wipes the text (a wipe that federated).
+- **Locked read-modify-write via `brainStorage.updateWith`.** New primitive
+ re-reads the fresh record INSIDE `withStoreWriteLock`, applies
+ `fn(record) → partial` (null aborts), and persists with `update()`'s exact
+ semantics. The PUT content merge and both attachment handlers use it, closing
+ the snapshot-outside-the-lock clobber against concurrent uploads/deletes and
+ peer-sync applies; a mid-request tombstone now 404s cleanly.
+- **Seed songs + migration 190.** `data.reference/brain/songs.json` ships three
+ public-domain "House of the Rising Sun" records (guitar/piano/ukulele);
+ `scripts/migrations/190-seed-songbook-songs.js` merges them into existing
+ installs (setup-data only copies missing files), never overwriting an
+ existing/edited/tombstoned id.
+- **Dash-joined chord support.** `tabNotation.js` treats `Am-Am7`-style quick
+ changes as one chord token (classification, ChordPro inline brackets, and
+ transposition — `Am-Am7` → `Bm-Bm7`), while hyphenated lyric fragments
+ ("A-round") and bare letter runs ("A-B") stay words; ♯/♭ normalize to ASCII
+ accidentals on paste.
diff --git a/scripts/migrations/190-seed-songbook-songs.js b/scripts/migrations/190-seed-songbook-songs.js
new file mode 100644
index 0000000000..5c50c04b36
--- /dev/null
+++ b/scripts/migrations/190-seed-songbook-songs.js
@@ -0,0 +1,69 @@
+/**
+ * Migration 190 — seed the SongBook starter songs into existing installs.
+ *
+ * The SongBook feature ships three public-domain seed records ("House of the
+ * Rising Sun" for guitar / piano / ukulele) in data.reference/brain/songs.json.
+ * Fresh installs get them because scripts/setup-data.js copies the whole file —
+ * but setup-data only copies MISSING files, so an existing install whose
+ * data/brain/songs.json was already created (even empty, by the feature's
+ * first boot) would never receive the seeds. This migration merges them in.
+ *
+ * Idempotent and non-destructive: a seed id already present in the live store
+ * — a user-edited copy, a synced copy from a peer, or a tombstone from a
+ * deliberate delete — is NEVER overwritten (so a deleted seed stays deleted).
+ * The file is written only when at least one record was added. The seeds carry
+ * no originInstanceId; brainStorage's boot-time backfill stamps it, exactly as
+ * it does for the setup-data copy path.
+ */
+
+import { readFile, writeFile, mkdir } from 'fs/promises';
+import { join, dirname } from 'path';
+
+// tryReadFile convention: missing/unreadable → fallback (the migration runner
+// executes before the service layer is wired, so no server/lib imports here).
+async function readJsonOr(path, fallback) {
+ const raw = await readFile(path, 'utf-8').catch(() => null);
+ if (raw == null) return fallback;
+ try {
+ return JSON.parse(raw);
+ } catch {
+ return fallback;
+ }
+}
+
+export async function up({ rootDir }) {
+ const seedPath = join(rootDir, 'data.reference', 'brain', 'songs.json');
+ const livePath = join(rootDir, 'data', 'brain', 'songs.json');
+
+ const seed = await readJsonOr(seedPath, null);
+ const seedRecords = seed?.records && typeof seed.records === 'object' ? seed.records : {};
+ const seedIds = Object.keys(seedRecords);
+ if (seedIds.length === 0) {
+ console.log('🎸 songbook-seed: no seed records in data.reference — no-op.');
+ return { ok: true, reason: 'no-seeds' };
+ }
+
+ const live = await readJsonOr(livePath, { records: {} });
+ if (!live.records || typeof live.records !== 'object') live.records = {};
+
+ let added = 0;
+ for (const id of seedIds) {
+ // Never overwrite an existing id — a user-edited copy, a peer-synced copy,
+ // or a tombstone (deleted seed) all stay untouched.
+ if (live.records[id] !== undefined) continue;
+ live.records[id] = seedRecords[id];
+ added += 1;
+ }
+
+ if (added === 0) {
+ console.log('🎸 songbook-seed: all seed songs already present — no-op.');
+ return { ok: true, reason: 'already-present' };
+ }
+
+ await mkdir(dirname(livePath), { recursive: true });
+ await writeFile(livePath, JSON.stringify(live, null, 2) + '\n');
+ console.log(`🎸 songbook-seed: added ${added} public-domain starter song(s) to data/brain/songs.json.`);
+ return { ok: true, reason: 'seeded', added };
+}
+
+export default { up };
diff --git a/scripts/migrations/190-seed-songbook-songs.test.js b/scripts/migrations/190-seed-songbook-songs.test.js
new file mode 100644
index 0000000000..f73b9c2e78
--- /dev/null
+++ b/scripts/migrations/190-seed-songbook-songs.test.js
@@ -0,0 +1,128 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import migration from './190-seed-songbook-songs.js';
+
+let rootDir;
+let liveDir;
+let seedDir;
+
+beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-190-'));
+ liveDir = join(rootDir, 'data', 'brain');
+ seedDir = join(rootDir, 'data.reference', 'brain');
+ mkdirSync(seedDir, { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+});
+
+// Invented seed fixture (privacy convention) — mirrors the shipped shape:
+// records keyed by stable id, no originInstanceId (boot backfill stamps it).
+const SEEDS = {
+ records: {
+ 'song-seed-alpha': { title: 'Example Song A', artist: 'Traditional', attachments: [], createdAt: '2026-07-15T00:00:00.000Z', updatedAt: '2026-07-15T00:00:00.000Z' },
+ 'song-seed-beta': { title: 'Example Song B', artist: 'Traditional', attachments: [], createdAt: '2026-07-15T00:00:00.000Z', updatedAt: '2026-07-15T00:00:00.000Z' },
+ },
+};
+
+const writeSeed = (obj = SEEDS) => writeFileSync(join(seedDir, 'songs.json'), JSON.stringify(obj, null, 2));
+const writeLive = (obj) => {
+ mkdirSync(liveDir, { recursive: true });
+ writeFileSync(join(liveDir, 'songs.json'), JSON.stringify(obj, null, 2));
+};
+const readLive = () => JSON.parse(readFileSync(join(liveDir, 'songs.json'), 'utf-8'));
+
+describe('migration 190 — seed songbook songs', () => {
+ it('adds every seed to an existing empty store (the setup-data gap)', async () => {
+ writeSeed();
+ writeLive({ records: {} });
+ const result = await migration.up({ rootDir });
+ expect(result).toMatchObject({ ok: true, reason: 'seeded', added: 2 });
+ expect(Object.keys(readLive().records).sort()).toEqual(['song-seed-alpha', 'song-seed-beta']);
+ });
+
+ it('creates the live store (with parent dirs) when missing', async () => {
+ writeSeed();
+ const result = await migration.up({ rootDir });
+ expect(result.added).toBe(2);
+ expect(readLive().records['song-seed-alpha'].title).toBe('Example Song A');
+ });
+
+ it('never overwrites an existing id — user-edited and tombstoned copies survive', async () => {
+ writeSeed();
+ writeLive({
+ records: {
+ 'song-seed-alpha': { title: 'My Customized Copy', updatedAt: '2026-08-01T00:00:00.000Z' },
+ 'song-seed-beta': { _deleted: true, updatedAt: '2026-08-01T00:00:00.000Z', deletedAt: '2026-08-01T00:00:00.000Z', originInstanceId: 'x' },
+ 'user-song-1': { title: 'User Song' },
+ },
+ });
+ const result = await migration.up({ rootDir });
+ expect(result.reason).toBe('already-present');
+ const live = readLive();
+ expect(live.records['song-seed-alpha'].title).toBe('My Customized Copy');
+ expect(live.records['song-seed-beta']._deleted).toBe(true); // deleted seed stays deleted
+ expect(live.records['user-song-1'].title).toBe('User Song');
+ });
+
+ it('is idempotent — a second run adds nothing', async () => {
+ writeSeed();
+ writeLive({ records: {} });
+ await migration.up({ rootDir });
+ const second = await migration.up({ rootDir });
+ expect(second.reason).toBe('already-present');
+ expect(Object.keys(readLive().records)).toHaveLength(2);
+ });
+
+ it('adds only the missing seeds when some are already present', async () => {
+ writeSeed();
+ writeLive({ records: { 'song-seed-alpha': { title: 'Kept' } } });
+ const result = await migration.up({ rootDir });
+ expect(result.added).toBe(1);
+ const live = readLive();
+ expect(live.records['song-seed-alpha'].title).toBe('Kept');
+ expect(live.records['song-seed-beta'].title).toBe('Example Song B');
+ });
+
+ it('no-ops when the seed file is missing or empty', async () => {
+ const missing = await migration.up({ rootDir });
+ expect(missing).toMatchObject({ ok: true, reason: 'no-seeds' });
+ expect(existsSync(join(liveDir, 'songs.json'))).toBe(false);
+
+ writeSeed({ records: {} });
+ const empty = await migration.up({ rootDir });
+ expect(empty.reason).toBe('no-seeds');
+ });
+
+ it('treats an unreadable live file as an empty store', async () => {
+ writeSeed();
+ mkdirSync(liveDir, { recursive: true });
+ writeFileSync(join(liveDir, 'songs.json'), '{not json');
+ const result = await migration.up({ rootDir });
+ expect(result.added).toBe(2);
+ expect(Object.keys(readLive().records)).toHaveLength(2);
+ });
+
+ it('seeds the SHIPPED reference records against a real repo layout shape', async () => {
+ // Sanity-pin the shipped seed file: three instrument variants of the same
+ // public-domain song, no originInstanceId, stable ids.
+ const shipped = JSON.parse(readFileSync(new URL('../../data.reference/brain/songs.json', import.meta.url), 'utf-8'));
+ const ids = Object.keys(shipped.records);
+ expect(ids.sort()).toEqual(['song-seed-hotrs-guitar', 'song-seed-hotrs-piano', 'song-seed-hotrs-ukulele']);
+ for (const id of ids) {
+ const rec = shipped.records[id];
+ expect(rec.title).toBe('House of the Rising Sun');
+ expect(rec.artist).toBe('Traditional');
+ expect(rec.originInstanceId).toBeUndefined(); // boot backfill stamps it
+ expect(rec.attachments).toEqual([]);
+ expect(rec.content.format).toBe('tab');
+ expect(rec.content.text).toContain('There is a house in New Orleans');
+ expect(rec.createdAt).toBe('2026-07-15T00:00:00.000Z');
+ }
+ expect(new Set(ids.map((id) => shipped.records[id].instrument))).toEqual(new Set(['guitar', 'piano', 'ukulele']));
+ });
+});
diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.js
index 7f9842f140..5eaa1d163c 100644
--- a/server/lib/brainValidation.js
+++ b/server/lib/brainValidation.js
@@ -562,6 +562,13 @@ export const songInstrumentEnum = z.enum(['guitar', 'piano', 'ukulele', 'bass',
// Content notation format (drives the client-side parser/renderer)
export const songContentFormatEnum = z.enum(['chordpro', 'tab', 'plain']);
+// Nested content object — named so the update schema below can rebuild it
+// defaults-free (partialWithoutDefaults only strips TOP-LEVEL field defaults).
+const songContentSchema = z.object({
+ format: songContentFormatEnum.optional().default('tab'),
+ text: z.string().max(200000).optional().default('')
+});
+
// Create/Update Song input schema. Attachment metadata ({ filename, label,
// mime, size, sha256 }) is server-managed — synced in the record, mutated only
// by the attachment endpoints, never client-suppliable (no schema key here, so
@@ -576,13 +583,21 @@ export const songInputSchema = z.object({
capo: z.number().int().min(0).max(12).optional().default(0),
tuning: z.string().trim().max(40).optional().default(''),
sourceUrl: z.string().trim().max(2000).optional().default(''),
- content: z.object({
- format: songContentFormatEnum.optional().default('tab'),
- text: z.string().max(200000).optional().default('')
- }).optional().default({ format: 'tab', text: '' }),
+ content: songContentSchema.optional().default({ format: 'tab', text: '' }),
notes: z.string().max(5000).optional().default('')
});
+// PUT /api/brain/songbook/:id — defaults-free partial. partialWithoutDefaults
+// only strips top-level defaults (see the zodCompat docstring): a
+// present-but-partial `content` object would still inflate its inner defaults
+// — `{ content: { text } }` resetting format to 'tab', `{ content: { format } }`
+// wiping the whole text (and the wipe federates). The nested content field is
+// rebuilt defaults-free too; the route deep-merges `data.content` over the
+// stored song's content so an omitted inner key preserves the stored value.
+export const songUpdateSchema = partialWithoutDefaults(songInputSchema).extend({
+ content: partialWithoutDefaults(songContentSchema).optional()
+});
+
// POST /api/brain/songbook/import/url
export const songImportUrlSchema = z.object({
url: z.string().url().max(2000)
diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.js
index 6b7a51d08b..9bae612348 100644
--- a/server/lib/fileUtils.test.js
+++ b/server/lib/fileUtils.test.js
@@ -41,6 +41,9 @@ import {
detectImageFormat,
EXTENSION_MIME_MAP,
ATTACHMENT_ALLOWED_EXTENSIONS,
+ SONGBOOK_ATTACHMENT_EXTENSIONS,
+ saveBase64Upload,
+ serveLocalFile,
} from './fileUtils.js';
import { copyFileSync, existsSync, mkdirSync } from 'fs';
import { dirname } from 'path';
@@ -1153,3 +1156,91 @@ describe('detectImageFormat', () => {
expect(detectImageFormat(null)).toBeNull();
});
});
+
+describe('saveBase64Upload (shared attachment upload pipeline)', () => {
+ let dir;
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'save-b64-test-'));
+ });
+ afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ const opts = { allowedExtensions: SONGBOOK_ATTACHMENT_EXTENSIONS, maxBytes: 10 };
+ const b64 = (s) => Buffer.from(s).toString('base64');
+
+ it('persists within the cap and returns the uuid-prefixed name, buffer, size, and mime', async () => {
+ const saved = await saveBase64Upload(dir, { filename: 'sheet.txt', data: b64('ten bytes!') }, opts);
+ expect(saved.filename).toMatch(/^[0-9a-f]{8}-sheet\.txt$/);
+ expect(saved.size).toBe(10);
+ expect(saved.mime).toBe('text/plain');
+ expect(saved.buffer.toString('utf-8')).toBe('ten bytes!');
+ expect(existsSync(saved.filePath)).toBe(true);
+ expect(saved.filePath.startsWith(dir)).toBe(true);
+ });
+
+ it('rejects a payload over maxBytes with a 400 FILE_TOO_LARGE', async () => {
+ await expect(saveBase64Upload(dir, { filename: 'big.txt', data: b64('eleven bytes') }, opts))
+ .rejects.toMatchObject({ status: 400, code: 'FILE_TOO_LARGE' });
+ });
+
+ it('rejects an extension outside the allowlist with a 400 INVALID_FILE_TYPE', async () => {
+ await expect(saveBase64Upload(dir, { filename: 'app.exe', data: b64('x') }, opts))
+ .rejects.toMatchObject({ status: 400, code: 'INVALID_FILE_TYPE' });
+ });
+
+ it('rejects a traversal-shaped filename ("../x") with a 400', async () => {
+ await expect(saveBase64Upload(dir, { filename: '../x', data: b64('x') }, opts))
+ .rejects.toMatchObject({ status: 400 });
+ });
+
+ it('sanitizes a traversal filename with an allowed extension to a basename inside the dir', async () => {
+ const saved = await saveBase64Upload(dir, { filename: '../../evil.txt', data: b64('x') }, opts);
+ expect(saved.filename).toMatch(/^[0-9a-f]{8}-evil\.txt$/); // directory parts stripped
+ expect(saved.filePath.startsWith(dir)).toBe(true);
+ expect(existsSync(saved.filePath)).toBe(true);
+ });
+});
+
+describe('serveLocalFile (shared attachment serving pipeline)', () => {
+ let dir;
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'serve-local-test-'));
+ });
+ afterEach(() => {
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ const mockRes = () => ({
+ headers: {},
+ set(name, value) { this.headers[name] = value; return this; },
+ type: vi.fn(function type() { return this; }),
+ sendFile: vi.fn(),
+ });
+
+ it('serves a benign MIME inline with nosniff and no attachment disposition', async () => {
+ writeFileSync(join(dir, 'safe.txt'), 'hello');
+ const res = mockRes();
+ await serveLocalFile(res, dir, 'safe.txt');
+ expect(res.headers['X-Content-Type-Options']).toBe('nosniff');
+ expect(res.headers['Content-Disposition']).toBeUndefined();
+ expect(res.sendFile).toHaveBeenCalledWith(join(dir, 'safe.txt'));
+ });
+
+ it('forces Content-Disposition: attachment for a risky MIME (svg)', async () => {
+ writeFileSync(join(dir, 'sheet.svg'), '<svg/>');
+ const res = mockRes();
+ await serveLocalFile(res, dir, 'sheet.svg');
+ expect(res.headers['X-Content-Type-Options']).toBe('nosniff');
+ expect(res.headers['Content-Disposition']).toBe('attachment; filename="sheet.svg"');
+ expect(res.sendFile).toHaveBeenCalledWith(join(dir, 'sheet.svg'));
+ });
+
+ it('404s with the parametrized missingError for absent bytes', async () => {
+ const res = mockRes();
+ await expect(serveLocalFile(res, dir, 'nope.txt', {
+ missingError: { message: 'Attachment file is not on this machine', code: 'NOT_ON_THIS_MACHINE' },
+ })).rejects.toMatchObject({ status: 404, code: 'NOT_ON_THIS_MACHINE' });
+ expect(res.sendFile).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/lib/safeUrlFetch.js b/server/lib/safeUrlFetch.js
index 254497eda2..35bf383db7 100644
--- a/server/lib/safeUrlFetch.js
+++ b/server/lib/safeUrlFetch.js
@@ -208,31 +208,16 @@ async function fetchGuarded(url, { timeoutMs = DEFAULT_TIMEOUT_MS, headers, bloc
}
/**
- * Fetch a URL's body as text. Returns the string on a 2xx, or null on any
- * failure (network error, non-ok status, blocked redirect). `blockPrivate` opts
- * into the strict block-all-private posture and `throwOnUnsafe: false` returns
- * null (instead of throwing a 400) when the first hop is unsafe — both used by
- * RSS feed fetches.
+ * Read a response body into a Buffer bounded by `maxBytes`, or null when the
+ * body exceeds the cap. The cap is enforced first via Content-Length (cheap
+ * early-out) and then bounds PEAK MEMORY by streaming the body and aborting the
+ * moment accumulated bytes exceed it — so a server that omits or lies about
+ * Content-Length can't stream gigabytes into memory before a post-read check
+ * fires. Falls back to a buffered read only when the response exposes no
+ * stream (e.g. a test double). Shared by fetchPublicBinary and the opt-in
+ * fetchPublicText cap.
*/
-export async function fetchPublicText(url, { timeoutMs, headers, blockPrivate = false, throwOnUnsafe = true } = {}) {
- const res = await fetchGuarded(url, { timeoutMs, headers, blockPrivate, throwOnUnsafe });
- if (!res?.ok) return null;
- return res.text();
-}
-
-/**
- * Fetch a URL's body as a Buffer. Returns `{ buffer, contentType }` on a 2xx
- * within the size cap, or null on any failure. The cap is enforced first via
- * Content-Length (cheap early-out) and then bounds PEAK MEMORY by streaming the
- * body and aborting the moment accumulated bytes exceed it — so a server that
- * omits or lies about Content-Length can't stream gigabytes into memory before a
- * post-read check fires. Falls back to a buffered read only when the response
- * exposes no stream (e.g. a test double).
- */
-export async function fetchPublicBinary(url, { timeoutMs, headers, maxBytes = DEFAULT_MAX_BYTES, blockPrivate = false, throwOnUnsafe = true } = {}) {
- const res = await fetchGuarded(url, { timeoutMs, headers, blockPrivate, throwOnUnsafe });
- if (!res?.ok) return null;
- const contentType = res.headers.get('content-type') || '';
+async function readBodyCapped(res, maxBytes) {
const declared = Number(res.headers.get('content-length'));
if (maxBytes && Number.isFinite(declared) && declared > maxBytes) return null;
@@ -241,7 +226,7 @@ export async function fetchPublicBinary(url, { timeoutMs, headers, maxBytes = DE
// buffered read, still capped post-read.
const buffer = Buffer.from(await res.arrayBuffer());
if (maxBytes && buffer.byteLength > maxBytes) return null;
- return { buffer, contentType };
+ return buffer;
}
const reader = res.body.getReader();
@@ -261,5 +246,36 @@ export async function fetchPublicBinary(url, { timeoutMs, headers, maxBytes = DE
} finally {
try { reader.releaseLock(); } catch { /* already released by cancel() */ }
}
- return { buffer: Buffer.concat(chunks), contentType };
+ return Buffer.concat(chunks);
+}
+
+/**
+ * Fetch a URL's body as text. Returns the string on a 2xx, or null on any
+ * failure (network error, non-ok status, blocked redirect). `blockPrivate` opts
+ * into the strict block-all-private posture and `throwOnUnsafe: false` returns
+ * null (instead of throwing a 400) when the first hop is unsafe — both used by
+ * RSS feed fetches. `maxBytes` (opt-in — no default, so existing callers keep
+ * the plain `res.text()` behavior) streams the body through the shared cap and
+ * returns null when it's exceeded, bounding peak memory exactly like
+ * fetchPublicBinary.
+ */
+export async function fetchPublicText(url, { timeoutMs, headers, maxBytes, blockPrivate = false, throwOnUnsafe = true } = {}) {
+ const res = await fetchGuarded(url, { timeoutMs, headers, blockPrivate, throwOnUnsafe });
+ if (!res?.ok) return null;
+ if (!maxBytes) return res.text();
+ const buffer = await readBodyCapped(res, maxBytes);
+ return buffer === null ? null : buffer.toString('utf-8');
+}
+
+/**
+ * Fetch a URL's body as a Buffer. Returns `{ buffer, contentType }` on a 2xx
+ * within the size cap, or null on any failure (see readBodyCapped for the
+ * streaming peak-memory bound).
+ */
+export async function fetchPublicBinary(url, { timeoutMs, headers, maxBytes = DEFAULT_MAX_BYTES, blockPrivate = false, throwOnUnsafe = true } = {}) {
+ const res = await fetchGuarded(url, { timeoutMs, headers, blockPrivate, throwOnUnsafe });
+ if (!res?.ok) return null;
+ const contentType = res.headers.get('content-type') || '';
+ const buffer = await readBodyCapped(res, maxBytes);
+ return buffer === null ? null : { buffer, contentType };
}
diff --git a/server/lib/safeUrlFetch.test.js b/server/lib/safeUrlFetch.test.js
index 344b8cbb0b..a0b334c297 100644
--- a/server/lib/safeUrlFetch.test.js
+++ b/server/lib/safeUrlFetch.test.js
@@ -225,6 +225,34 @@ const streamRes = (chunks, { headers = {}, ok = true, status = 200 } = {}) => {
};
};
+describe('fetchPublicText — opt-in maxBytes cap', () => {
+ const enc = (s) => new TextEncoder().encode(s);
+
+ it('returns the streamed text when within the cap', async () => {
+ fetchMock.mockResolvedValue(streamRes([enc('hel'), enc('lo')]));
+ expect(await fetchPublicText('https://example.com/page', { maxBytes: 1024 })).toBe('hello');
+ });
+
+ it('returns null when the declared Content-Length exceeds the cap', async () => {
+ fetchMock.mockResolvedValue(res({ text: 'x', headers: { 'content-length': String(99 * 1024 * 1024) } }));
+ expect(await fetchPublicText('https://example.com/page', { maxBytes: 1024 })).toBeNull();
+ });
+
+ it('aborts a no-Content-Length body that exceeds the cap (bounds peak memory)', async () => {
+ const r = streamRes([new Uint8Array(600), new Uint8Array(600)]); // 1200 > cap
+ fetchMock.mockResolvedValue(r);
+ expect(await fetchPublicText('https://example.com/page', { maxBytes: 1024 })).toBeNull();
+ expect(r.body._cancel).toHaveBeenCalled();
+ });
+
+ it('keeps the uncapped res.text() path when maxBytes is not passed', async () => {
+ // A response with NO readable stream still works without maxBytes —
+ // proving existing callers see no behavior change.
+ fetchMock.mockResolvedValue(res({ text: 'plain body' }));
+ expect(await fetchPublicText('https://example.com/page')).toBe('plain body');
+ });
+});
+
describe('fetchPublicBinary', () => {
it('returns the buffer + content-type from a non-streaming response (fallback)', async () => {
const bytes = new Uint8Array([1, 2, 3]).buffer;
diff --git a/server/routes/brainSongbook.js b/server/routes/brainSongbook.js
index 7e881fab6f..438c448d9f 100644
--- a/server/routes/brainSongbook.js
+++ b/server/routes/brainSongbook.js
@@ -19,9 +19,9 @@ import { join, resolve } from 'path';
import { createHash } from 'crypto';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
-import { partialWithoutDefaults } from '../lib/zodCompat.js';
import {
songInputSchema,
+ songUpdateSchema,
songImportUrlSchema,
songAttachmentUploadSchema,
} from '../lib/brainValidation.js';
@@ -34,8 +34,12 @@ import {
const router = Router();
-// Max attachment size: 50MB (matches routes/attachments.js — sheet-music PDFs)
-const MAX_ATTACHMENT_SIZE = 50 * 1024 * 1024;
+// Max attachment size: 40MB. Uploads arrive base64-encoded in a JSON body
+// (×4/3 inflation), and the express.json limit is 55mb — so anything above
+// ~41MB raw can never reach this route. 40MB keeps the advertised cap
+// reachable. (routes/attachments.js still claims 50MB with the same latent
+// mismatch — tracked in PLAN.md's uploads-consolidation follow-up.)
+const MAX_ATTACHMENT_SIZE = 40 * 1024 * 1024;
// Read lazily (not captured at module load) so test PATHS mocks with
// per-suite temp roots resolve correctly.
@@ -103,12 +107,18 @@ router.post('/', asyncHandler(async (req, res) => {
}));
router.put('/:id', asyncHandler(async (req, res) => {
- // partialWithoutDefaults (not .partial()) so an omitted field is genuinely
- // absent instead of resetting to its default (see zodCompat.js). The schema
- // has no `attachments` key, so Zod's unknown-key stripping drops any
- // client-supplied attachments — the record's server-managed list survives.
- const data = validateRequest(partialWithoutDefaults(songInputSchema), req.body);
- const song = requireSong(await brainStorage.update('songs', req.params.id, data));
+ // songUpdateSchema is defaults-free down to the nested `content` object, so
+ // an omitted field (or omitted content.format/text) is genuinely absent
+ // instead of resetting to its default (see brainValidation.js / zodCompat.js).
+ // The schema has no `attachments` key, so Zod's unknown-key stripping drops
+ // any client-supplied attachments — the record's server-managed list survives.
+ // A partial `content` deep-merges over the stored song's content inside the
+ // store write lock (updateWith), so `{ content: { text } }` keeps the stored
+ // format and `{ content: { format } }` keeps the stored text.
+ const data = validateRequest(songUpdateSchema, req.body);
+ const song = requireSong(await brainStorage.updateWith('songs', req.params.id, (fresh) => (
+ data.content ? { ...data, content: { ...fresh.content, ...data.content } } : data
+ )));
res.json(song);
}));
@@ -141,9 +151,13 @@ router.post('/:id/attachments', asyncHandler(async (req, res) => {
size: saved.size,
sha256: createHash('sha256').update(saved.buffer).digest('hex'),
};
- await brainStorage.update('songs', song.id, {
- attachments: [...(Array.isArray(song.attachments) ? song.attachments : []), attachment],
- });
+ // Append against the FRESH record inside the store write lock (updateWith) —
+ // a concurrent upload/delete or a peer-sync apply landing between the read
+ // above and this write would otherwise be clobbered (and win LWW). requireSong
+ // 404s the mid-request tombstone race instead of 201-ing meta never persisted.
+ requireSong(await brainStorage.updateWith('songs', song.id, (fresh) => ({
+ attachments: [...(Array.isArray(fresh.attachments) ? fresh.attachments : []), attachment],
+ })));
console.log(`🎸 Song attachment saved: ${saved.filename} (${saved.size} bytes)`);
res.status(201).json({ attachment });
@@ -176,9 +190,13 @@ router.delete('/:id/attachments/:filename', asyncHandler(async (req, res) => {
const song = await getSongOr404(req.params.id);
const { safeFilename, filepath } = resolveAttachment(song, req.params.filename);
- const updated = await brainStorage.update('songs', song.id, {
- attachments: song.attachments.filter((a) => a.filename !== safeFilename),
- });
+ // Filter against the FRESH record inside the store write lock (updateWith) so
+ // a concurrent upload/peer-sync apply isn't clobbered; requireSong 404s the
+ // mid-request tombstone race instead of TypeError-ing on a null record.
+ const updated = requireSong(await brainStorage.updateWith('songs', song.id, (fresh) => ({
+ attachments: (Array.isArray(fresh.attachments) ? fresh.attachments : [])
+ .filter((a) => a.filename !== safeFilename),
+ })));
// Bytes may legitimately be absent on this machine (meta synced from a peer).
if (await pathExists(filepath)) {
diff --git a/server/routes/brainSongbook.test.js b/server/routes/brainSongbook.test.js
index 0d8a8198f9..bd70fa4f37 100644
--- a/server/routes/brainSongbook.test.js
+++ b/server/routes/brainSongbook.test.js
@@ -31,6 +31,7 @@ vi.mock('../services/brainStorage.js', () => ({
getById: vi.fn(),
create: vi.fn(),
update: vi.fn(),
+ updateWith: vi.fn(),
remove: vi.fn(),
}));
@@ -54,6 +55,21 @@ const buildApp = () => {
return app;
};
+// Mirror updateWith's contract against a given "fresh" record: run the
+// route's fn, capture the partial updates it produced, and return the merged
+// record (or null when the record is gone). `seen.updates` lets tests assert
+// exactly what the route asked to persist.
+const mockUpdateWith = (freshSong) => {
+ const seen = { updates: null };
+ brainStorage.updateWith.mockImplementation(async (type, id, fn) => {
+ if (!freshSong) return null;
+ const updates = await fn({ ...freshSong });
+ seen.updates = updates;
+ return updates ? { ...freshSong, ...updates } : null;
+ });
+ return seen;
+};
+
const baseSong = (overrides = {}) => ({
id: SONG_ID,
title: 'Example Song',
@@ -154,14 +170,38 @@ describe('Brain SongBook routes', () => {
describe('PUT /api/brain/songbook/:id', () => {
it('updates only the sent fields (no default injection) — the stage-flip path', async () => {
- brainStorage.update.mockResolvedValue(baseSong({ stage: 'learning' }));
+ const stored = baseSong({ capo: 5, key: 'Em', content: { format: 'chordpro', text: '{t: Example Song}' } });
+ const seen = mockUpdateWith(stored);
const res = await request(app)
.put(`/api/brain/songbook/${SONG_ID}`)
.send({ stage: 'learning' });
expect(res.status).toBe(200);
expect(res.body.stage).toBe('learning');
- // Exactly the sent field — an omitted title/capo/etc. must not reset to defaults.
- expect(brainStorage.update).toHaveBeenCalledWith('songs', SONG_ID, { stage: 'learning' });
+ // Exactly the sent field — an omitted title/capo/content/etc. must not reset to defaults.
+ expect(seen.updates).toEqual({ stage: 'learning' });
+ expect(res.body.capo).toBe(5);
+ expect(res.body.content).toEqual({ format: 'chordpro', text: '{t: Example Song}' });
+ });
+
+ it('deep-merges a partial content: { text } preserves the stored format', async () => {
+ const stored = baseSong({ content: { format: 'chordpro', text: '{t: Old}' } });
+ const seen = mockUpdateWith(stored);
+ const res = await request(app)
+ .put(`/api/brain/songbook/${SONG_ID}`)
+ .send({ content: { text: 'new text' } });
+ expect(res.status).toBe(200);
+ expect(seen.updates.content).toEqual({ format: 'chordpro', text: 'new text' });
+ expect(res.body.content).toEqual({ format: 'chordpro', text: 'new text' });
+ });
+
+ it('deep-merges a partial content: { format } preserves the stored text', async () => {
+ const stored = baseSong({ content: { format: 'chordpro', text: '{t: Keep me}' } });
+ const seen = mockUpdateWith(stored);
+ const res = await request(app)
+ .put(`/api/brain/songbook/${SONG_ID}`)
+ .send({ content: { format: 'plain' } });
+ expect(res.status).toBe(200);
+ expect(seen.updates.content).toEqual({ format: 'plain', text: '{t: Keep me}' });
});
it('400s on an invalid stage', async () => {
@@ -169,19 +209,19 @@ describe('Brain SongBook routes', () => {
.put(`/api/brain/songbook/${SONG_ID}`)
.send({ stage: 'perfected' });
expect(res.status).toBe(400);
- expect(brainStorage.update).not.toHaveBeenCalled();
+ expect(brainStorage.updateWith).not.toHaveBeenCalled();
});
it('strips client-supplied attachments', async () => {
- brainStorage.update.mockResolvedValue(baseSong());
+ const seen = mockUpdateWith(baseSong());
await request(app)
.put(`/api/brain/songbook/${SONG_ID}`)
.send({ title: 'New Title', attachments: [{ filename: 'forged.pdf', mime: 'application/pdf', size: 1, sha256: 'x'.repeat(64) }] });
- expect(brainStorage.update).toHaveBeenCalledWith('songs', SONG_ID, { title: 'New Title' });
+ expect(seen.updates).toEqual({ title: 'New Title' });
});
it('404s when the song is missing', async () => {
- brainStorage.update.mockResolvedValue(null);
+ brainStorage.updateWith.mockResolvedValue(null);
const res = await request(app)
.put(`/api/brain/songbook/${SONG_ID}`)
.send({ title: 'X' });
@@ -243,7 +283,7 @@ describe('Brain SongBook routes', () => {
it('writes bytes, hashes them, and appends meta to the record', async () => {
const song = baseSong();
brainStorage.getById.mockResolvedValue(song);
- brainStorage.update.mockImplementation(async (type, id, fields) => ({ ...song, ...fields }));
+ const seen = mockUpdateWith(song);
const payload = Buffer.from('invented sheet music');
const res = await request(app)
@@ -263,15 +303,31 @@ describe('Brain SongBook routes', () => {
expect(existsSync(filepath)).toBe(true);
expect(readFileSync(filepath, 'utf-8')).toBe('invented sheet music');
- // Meta appended via the entity store (federates with the record)
- expect(brainStorage.update).toHaveBeenCalledWith('songs', SONG_ID, {
- attachments: [attachment],
- });
+ // Meta appended via the locked read-modify-write (federates with the record)
+ expect(brainStorage.updateWith).toHaveBeenCalledWith('songs', SONG_ID, expect.any(Function));
+ expect(seen.updates).toEqual({ attachments: [attachment] });
+ });
+
+ it('appends meta computed from the FRESH record, not the pre-read snapshot', async () => {
+ // The route reads the song (empty attachments), but by the time updateWith
+ // runs, a concurrent writer added one — the append must keep it.
+ brainStorage.getById.mockResolvedValue(baseSong({ attachments: [] }));
+ const concurrent = { filename: 'aaaaaaaa-concurrent.pdf', label: '', mime: 'application/pdf', size: 3, sha256: 'a'.repeat(64) };
+ const seen = mockUpdateWith(baseSong({ attachments: [concurrent] }));
+
+ const res = await request(app)
+ .post(`/api/brain/songbook/${SONG_ID}/attachments`)
+ .send({ filename: 'sheet.txt', data: Buffer.from('x').toString('base64') });
+
+ expect(res.status).toBe(201);
+ expect(seen.updates.attachments).toHaveLength(2);
+ expect(seen.updates.attachments[0]).toEqual(concurrent);
+ expect(seen.updates.attachments[1].filename).toMatch(/-sheet\.txt$/);
});
it('accepts MIDI files (songbook-specific allowlist extension)', async () => {
brainStorage.getById.mockResolvedValue(baseSong());
- brainStorage.update.mockImplementation(async (type, id, fields) => ({ ...baseSong(), ...fields }));
+ mockUpdateWith(baseSong());
const res = await request(app)
.post(`/api/brain/songbook/${SONG_ID}/attachments`)
.send({ filename: 'melody.mid', data: Buffer.from('MThd').toString('base64') });
@@ -285,7 +341,7 @@ describe('Brain SongBook routes', () => {
.post(`/api/brain/songbook/${SONG_ID}/attachments`)
.send({ filename: 'app.exe', data: Buffer.from('nope').toString('base64') });
expect(res.status).toBe(400);
- expect(brainStorage.update).not.toHaveBeenCalled();
+ expect(brainStorage.updateWith).not.toHaveBeenCalled();
});
it('404s when the song is missing', async () => {
@@ -295,6 +351,18 @@ describe('Brain SongBook routes', () => {
.send({ filename: 'sheet.txt', data: Buffer.from('x').toString('base64') });
expect(res.status).toBe(404);
});
+
+ it('404s (not 201) when the song is tombstoned mid-request', async () => {
+ // getById saw the song, but by the time the locked write runs it's gone —
+ // updateWith returns null and the route must 404, never 201 a meta that
+ // was never persisted.
+ brainStorage.getById.mockResolvedValue(baseSong());
+ brainStorage.updateWith.mockResolvedValue(null);
+ const res = await request(app)
+ .post(`/api/brain/songbook/${SONG_ID}/attachments`)
+ .send({ filename: 'sheet.txt', data: Buffer.from('x').toString('base64') });
+ expect(res.status).toBe(404);
+ });
});
describe('GET /api/brain/songbook/:id/attachments', () => {
@@ -357,20 +425,39 @@ describe('Brain SongBook routes', () => {
const meta = { filename: 'ffffffff-gone.txt', label: '', mime: 'text/plain', size: 9, sha256: 'f'.repeat(64) };
const song = baseSong({ attachments: [meta] });
brainStorage.getById.mockResolvedValue(song);
- brainStorage.update.mockImplementation(async (type, id, fields) => ({ ...song, ...fields }));
+ const seen = mockUpdateWith(song);
const res = await request(app).delete(`/api/brain/songbook/${SONG_ID}/attachments/ffffffff-gone.txt`);
expect(res.status).toBe(200);
expect(res.body).toMatchObject({ success: true, filename: 'ffffffff-gone.txt', attachments: [] });
- expect(brainStorage.update).toHaveBeenCalledWith('songs', SONG_ID, { attachments: [] });
+ expect(seen.updates).toEqual({ attachments: [] });
expect(existsSync(filepath)).toBe(false);
});
+ it('filters from the FRESH record, preserving a concurrently-added meta', async () => {
+ const target = { filename: 'ffffffff-gone.txt', label: '', mime: 'text/plain', size: 9, sha256: 'f'.repeat(64) };
+ const concurrent = { filename: 'bbbbbbbb-new.pdf', label: '', mime: 'application/pdf', size: 4, sha256: 'b'.repeat(64) };
+ brainStorage.getById.mockResolvedValue(baseSong({ attachments: [target] }));
+ const seen = mockUpdateWith(baseSong({ attachments: [target, concurrent] }));
+
+ const res = await request(app).delete(`/api/brain/songbook/${SONG_ID}/attachments/ffffffff-gone.txt`);
+ expect(res.status).toBe(200);
+ expect(seen.updates).toEqual({ attachments: [concurrent] });
+ });
+
it('404s for a meta not on the record', async () => {
brainStorage.getById.mockResolvedValue(baseSong({ attachments: [] }));
const res = await request(app).delete(`/api/brain/songbook/${SONG_ID}/attachments/nope.txt`);
expect(res.status).toBe(404);
- expect(brainStorage.update).not.toHaveBeenCalled();
+ expect(brainStorage.updateWith).not.toHaveBeenCalled();
+ });
+
+ it('404s (not 500) when the song is tombstoned mid-request', async () => {
+ const meta = { filename: 'ffffffff-gone.txt', label: '', mime: 'text/plain', size: 9, sha256: 'f'.repeat(64) };
+ brainStorage.getById.mockResolvedValue(baseSong({ attachments: [meta] }));
+ brainStorage.updateWith.mockResolvedValue(null);
+ const res = await request(app).delete(`/api/brain/songbook/${SONG_ID}/attachments/ffffffff-gone.txt`);
+ expect(res.status).toBe(404);
});
});
});
diff --git a/server/services/brainSongbookImport.js b/server/services/brainSongbookImport.js
index cf18c64924..665739cadd 100644
--- a/server/services/brainSongbookImport.js
+++ b/server/services/brainSongbookImport.js
@@ -58,9 +58,15 @@ export function extractUltimateGuitarStore(html) {
// Observed shape nests under a top-level `store` key; tolerate both.
const data = parsed?.store?.page?.data ?? parsed?.page?.data;
const content = data?.tab_view?.wiki_tab?.content;
- if (typeof content !== 'string' || !content.trim()) return null;
+ if (typeof content !== 'string') return null;
+ // Gate on the POST-strip text, not the raw content — marker-only content
+ // ("[tab][/tab]") strips to nothing and must fall through to the next
+ // extractor (a real <pre> on the page) instead of short-circuiting the
+ // cascade into an empty draft / 422.
+ const text = normalizeSheetText(stripUgMarkers(content));
+ if (!text) return null;
return {
- text: normalizeSheetText(stripUgMarkers(content)),
+ text,
title: typeof data?.tab?.song_name === 'string' ? data.tab.song_name.trim() : '',
artist: typeof data?.tab?.artist_name === 'string' ? data.tab.artist_name.trim() : '',
};
@@ -154,6 +160,9 @@ export function buildDraftFromHtml(html, url) {
export async function importSongFromUrl(url) {
const html = await fetchPublicText(url, {
timeoutMs: 20000,
+ // Cap the page at 4MB (streamed — bounds peak memory): tab pages are text;
+ // anything bigger is not a chord sheet.
+ maxBytes: 4 * 1024 * 1024,
headers: { 'User-Agent': 'Mozilla/5.0 (compatible; PortOS-SongBook/1.0)' },
});
if (html === null) {
diff --git a/server/services/brainSongbookImport.test.js b/server/services/brainSongbookImport.test.js
index 8225ef8dde..c33c8bc379 100644
--- a/server/services/brainSongbookImport.test.js
+++ b/server/services/brainSongbookImport.test.js
@@ -82,6 +82,11 @@ describe('extractUltimateGuitarStore', () => {
const empty = { store: { page: { data: { tab_view: { wiki_tab: { content: ' ' } } } } } };
expect(extractUltimateGuitarStore(buildUgHtml(empty))).toBeNull();
});
+
+ it('returns null when content is marker-only and strips to nothing', () => {
+ const markerOnly = { store: { page: { data: { tab_view: { wiki_tab: { content: '[tab][/tab]' } } } } } };
+ expect(extractUltimateGuitarStore(buildUgHtml(markerOnly))).toBeNull();
+ });
});
describe('extractLargestPre', () => {
@@ -163,6 +168,16 @@ describe('buildDraftFromHtml', () => {
expect(draft.content.text).toContain('example progression sheet');
});
+ it('falls through marker-only UG content to a real <pre> on the page', () => {
+ // The js-store gate must key on the POST-strip text: "[tab][/tab]" strips
+ // to nothing, so the cascade continues to the <pre> instead of 422-ing.
+ const markerOnly = { store: { page: { data: { tab_view: { wiki_tab: { content: '[tab][/tab]' } } } } } };
+ const html = buildUgHtml(markerOnly).replace('</body>', '<pre>e|--0--2--3--| example tab staff</pre></body>');
+ const draft = buildDraftFromHtml(html, URL);
+ expect(draft.content.format).toBe('tab');
+ expect(draft.content.text).toContain('e|--0--2--3--|');
+ });
+
it('falls back to plain tag-stripped text when nothing else matches', () => {
const html = '<html><head><title>Example Song - The Placeholders</title><style>.x{}</style></head>' +
'<body><script>var a = 1;</script><p>Just some lyric text on a plain page</p></body></html>';
diff --git a/server/services/brainStorage.js b/server/services/brainStorage.js
index 1a3a205b56..b466a7e79b 100644
--- a/server/services/brainStorage.js
+++ b/server/services/brainStorage.js
@@ -328,6 +328,55 @@ export async function update(type, id, updates) {
});
}
+/**
+ * Locked read-modify-write update.
+ *
+ * `update(type, id, partial)` merges a partial the CALLER computed — usually
+ * from a record snapshot read OUTSIDE the store write lock. When the partial
+ * is derived from the current record (append to / filter an array field like
+ * `attachments`), a concurrent writer landing between the snapshot read and
+ * the update silently gets clobbered (and the clobber wins LWW federation).
+ *
+ * `updateWith` closes that window: INSIDE withStoreWriteLock it re-reads the
+ * fresh record, calls `fn({ id, ...record })` → a partial-updates object (or
+ * null/undefined to abort without writing), then merges/persists with exactly
+ * `update()`'s semantics — immutable originInstanceId/createdAt, fresh
+ * updatedAt stamp, cache write-through, `${type}:upserted` event, and a sync
+ * log append. Returns the updated `{ id, ...record }`, or null when the record
+ * is missing/tombstoned or fn aborted.
+ */
+export async function updateWith(type, id, fn) {
+ return withStoreWriteLock(async () => {
+ const data = await loadJsonStore(type);
+
+ // A tombstoned record is gone — treat it as not-found rather than reviving it.
+ if (!data.records[id] || isTombstone(data.records[id])) {
+ return null;
+ }
+
+ const updates = await fn({ id, ...data.records[id] });
+ if (!updates) return null;
+
+ const record = {
+ ...data.records[id],
+ ...updates,
+ // Preserve immutable fields — originInstanceId tracks the creating instance
+ originInstanceId: data.records[id].originInstanceId,
+ createdAt: data.records[id].createdAt,
+ updatedAt: now()
+ };
+
+ data.records[id] = record;
+ await saveJsonStore(type, data);
+ brainEvents.emit(`${type}:upserted`, { id, record: { id, ...record } });
+ await brainSyncLog.appendChange('update', type, id, record, record.originInstanceId)
+ .catch(err => console.error(`⚠️ Sync log append failed for update ${type}/${id}: ${err.message}`));
+
+ console.log(`🧠 Updated ${type} record: ${id}`);
+ return { id, ...record };
+ });
+}
+
/**
* Upsert a record under a CALLER-PROVIDED id (full replace, create-if-missing).
*
diff --git a/server/services/brainStorage.test.js b/server/services/brainStorage.test.js
index 27a5aaee7b..46e2d43624 100644
--- a/server/services/brainStorage.test.js
+++ b/server/services/brainStorage.test.js
@@ -238,6 +238,64 @@ describe('memory recency ordering', () => {
});
});
+describe('updateWith (locked read-modify-write)', () => {
+ it('applies fn against the fresh record — two sequential array appends both land', async () => {
+ const created = await brainStorage.create('songs', { title: 'RMW Song', attachments: [] });
+ const append = (meta) => brainStorage.updateWith('songs', created.id, (fresh) => ({
+ attachments: [...fresh.attachments, meta],
+ }));
+
+ await append({ filename: 'a.pdf' });
+ const second = await append({ filename: 'b.pdf' });
+ expect(second.attachments.map((a) => a.filename)).toEqual(['a.pdf', 'b.pdf']);
+
+ brainStorage.invalidateAllCaches();
+ const stored = await brainStorage.getById('songs', created.id);
+ expect(stored.attachments.map((a) => a.filename)).toEqual(['a.pdf', 'b.pdf']);
+ });
+
+ it('serializes concurrent updateWith calls so neither clobbers the other', async () => {
+ const created = await brainStorage.create('songs', { title: 'Concurrent Song', attachments: [] });
+ const append = (meta) => brainStorage.updateWith('songs', created.id, (fresh) => ({
+ attachments: [...fresh.attachments, meta],
+ }));
+
+ // Fire both without awaiting in between — the store write lock must make
+ // the second fn see the first's write (the race the snapshot+update()
+ // pattern loses).
+ await Promise.all([append({ filename: 'x.pdf' }), append({ filename: 'y.pdf' })]);
+
+ brainStorage.invalidateAllCaches();
+ const stored = await brainStorage.getById('songs', created.id);
+ expect(stored.attachments.map((a) => a.filename).sort()).toEqual(['x.pdf', 'y.pdf']);
+ });
+
+ it('mirrors update() semantics: immutable fields preserved, updatedAt stamped', async () => {
+ const created = await brainStorage.create('songs', { title: 'Stamp Song' });
+ const updated = await brainStorage.updateWith('songs', created.id, () => ({ title: 'Renamed' }));
+ expect(updated.title).toBe('Renamed');
+ expect(updated.originInstanceId).toBe(created.originInstanceId);
+ expect(updated.createdAt).toBe(created.createdAt);
+ expect(updated.updatedAt >= created.updatedAt).toBe(true);
+ });
+
+ it('returns null for a missing or tombstoned record without calling through', async () => {
+ expect(await brainStorage.updateWith('songs', 'no-such-id', () => ({ title: 'x' }))).toBeNull();
+ const created = await brainStorage.create('songs', { title: 'Gone Song' });
+ await brainStorage.remove('songs', created.id);
+ expect(await brainStorage.updateWith('songs', created.id, () => ({ title: 'x' }))).toBeNull();
+ });
+
+ it('aborts without writing when fn returns null', async () => {
+ const created = await brainStorage.create('songs', { title: 'Abort Song' });
+ expect(await brainStorage.updateWith('songs', created.id, () => null)).toBeNull();
+ brainStorage.invalidateAllCaches();
+ const stored = await brainStorage.getById('songs', created.id);
+ expect(stored.title).toBe('Abort Song');
+ expect(stored.updatedAt).toBe(created.updatedAt); // no write happened
+ });
+});
+
describe('songs entity enrollment (SongBook)', () => {
it('lists songs in BRAIN_ENTITY_TYPES so sync/GC/backfill all cover it', () => {
expect(brainStorage.BRAIN_ENTITY_TYPES).toContain('songs');