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
SongBook — guitar tabs, chord sheets & sheet music in the Brain
Date: 2026-07-15. Status: approved design, implemented on feature/songbook.
What it is
A repertoire tracker inside the Brain: songs the user knows or is learning (guitar
tabs, chord/lyric sheets, piano sheet music), each with a learning stage
(new → learning → learned → memorized), plus an Ultimate-Guitar-style playback
view with adjustable autoscroll, transpose, and font sizing. Content arrives by
paste (auto-formatted) or by URL import (server-side fetch + extraction).
Storage: Brain entity type songs (NOT a new data store)
Songs enroll in the existing Brain entity store — add 'songs' to
BRAIN_ENTITY_TYPES, FILES, and the caches map in
server/services/brainStorage.js. That single enrollment derives: sync-log
appends, LWW peer sync, tombstone deletes + GC, reconcile checksum coverage, and
originInstanceId backfill. Older peers skip the unknown type gracefully
(applyRemoteChanges skips unknown types), so no schema-version bump is needed.
This is deliberately NOT a fresh data/*.json store (STORAGE.md anti-pattern) —
it joins an existing storage system, and it is NOT db-primary because the user's
"Brain" domain is file-primary with its own federation pipeline and songs should
sync across machines like every other brain record.
- Records persist to
data/brain/songs.json({ records: { id: record } }). - Seed file:
data.reference/brain/songs.jsonwith{ "records": {} }. - All writes go through brainStorage's generic API (
create/update/remove/getAll/getById) — never write the JSON directly. Deletes are tombstones (brainStorage.remove). - Attachments (PDF sheet music, images, MIDI): metadata in the synced record
(identical on all peers, so the reconcile checksum stays clean); bytes
machine-local under
data/brain/songbook/(<uuid>-<sanitized-name>). Peers that lack the file render "not on this machine".data/brain/is already covered by backup; do NOT add excludes.
Record schema (Zod in server/lib/brainValidation.js)
songStageEnum = z.enum(['new', 'learning', 'learned', 'memorized'])
songInstrumentEnum = z.enum(['guitar', 'piano', 'ukulele', 'bass', 'voice', 'other'])
songContentFormatEnum = z.enum(['chordpro', 'tab', 'plain'])
songInputSchema = {
title: z.string().trim().min(1).max(300),
artist: z.string().trim().max(300).optional().default(''),
instrument: songInstrumentEnum.optional().default('guitar'),
stage: songStageEnum.optional().default('new'),
tags: z.array(z.string().trim().min(1).max(50)).max(50).optional().default([]),
key: z.string().trim().max(20).optional().default(''),
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: '' }),
scrollDurationSec: z.number().int().min(15).max(3600).nullable().optional().default(null),
notes: z.string().max(5000).optional().default(''),
}
// songRecordSchema = input + server-managed fields:
// attachments: [{ filename, label, mime, size, sha256 }] (default [])
// + brainStorage-stamped id/createdAt/updatedAt/originInstanceId
attachments is server-managed (mutated only by the attachment endpoints) — the
PUT handler must ignore/strip client-supplied attachments.
Server API (sub-router server/routes/brainSongbook.js, mounted from the server/routes/brain.js barrel at /songbook → full paths /api/brain/songbook/...)
GET /→{ songs: [...] }(tombstones excluded — brainStorage does this)GET /:id→ record or 404 ServerErrorPOST /— validateRequest(songInputSchema) → created recordPUT /:id— validateRequest(songInputSchema.partial()), stripsattachments, → updated recordPATCH /:id/stage—{ stage: songStageEnum }→ updated record (cheap chip-flip path)DELETE /:id→{ id }(tombstone)POST /import/url—{ url: z.string().url() }→{ draft: { title, artist, content: { format, text }, sourceUrl } }Synchronous (no SSE). Serviceserver/services/brainSongbookImport.js.POST /:id/attachments—{ filename, data (base64), label? }, 50MB cap, extension allowlist (cribserver/routes/attachments.js: sanitizeFilename, isPathInsideDir,<uuid>-<name>), writes bytes + sha256, appends meta to record →{ attachment }GET /:id/attachments→[{ ...meta, present: boolean }](present = bytes exist locally)GET /:id/attachments/:filename→ serves file (nosniff; attachment disposition for risky MIME)DELETE /:id/attachments/:filename→ removes meta from record + deletes local bytes
Conventions: asyncHandler everywhere, no try/catch, ServerError for 404s,
schemas in server/lib/brainValidation.js (namespace-exported in the lib barrel —
watch the collision-detector test).
URL import service (server/services/brainSongbookImport.js)
assertPublicHttpUrl+ text fetch viaserver/lib/safeUrlFetch.js.- Extractors, first match wins:
a. Ultimate Guitar: the page embeds JSON in
<div class="js-store" data-content="...">— HTML-entity-decode, JSON.parse, readstore.page.data.tab_view.wiki_tab.content(tab text with[ch]...[/ch]/[tab]...[/tab]markers — strip markers) andstore.page.data.tab.song_name / artist_name. Defensive optional-chaining; any shape drift falls through to (b). b. Generic<pre>block: largest<pre>in the page (regex, no cheerio), entity-decoded. c. Fallback: strip tags → plain text; if the result has no chord-like or tab-like lines (server keeps a tiny line-classifier mirror or just length heuristics), still return it asformat: 'plain'. - Title/artist fallback:
<title>tag parsing ("X by Y" / "X - Y"patterns). - Never store on import — return a draft; the client shows a review/edit screen and the user saves explicitly. Emoji-prefixed single-line logs.
Client parser (client/src/lib/tabNotation.js — pure leaf, modeled on scoreNotation.js)
detectFormat(text) // → 'chordpro' | 'tab' | 'plain'
parseTabSheet(text) // → { lines: [Line], meta: { title?, artist?, key?, capo? }, errors: [] }
// Line = { type: 'section'|'chords'|'lyric'|'tabstaff'|'chordlyric'|'blank'|'text', text, chords?: [{ name, col }] }
// 'section' — [Verse 1], [Chorus], {start_of_chorus} etc.
// 'chords' — a line that is ≥~80% chord tokens/whitespace (C, Am7, F#m7b5, G/B, N.C.)
// 'tabstaff' — monospace tab staff lines (e|--3--2--| ; also B/G/D/A/E-prefixed)
// 'chordlyric'— ChordPro inline [C]lyric syntax, chords carry col offsets into the bare lyric
normalizePastedTab(text) // strip HTML remnants/entities, normalize \r\n, collapse 3+ blank lines, detab
transposeChordName(name, n) // 'Am7' + 2 → 'Bm7'; handles slash chords, prefers keys' natural spelling
transposeText(text, n) // transpose every chord token in chords/chordlyric lines, preserving column alignment where possible
CHORD_TOKEN_RE // exported for reuse/tests
Forgiving parser: never throws; unknown lines classify as 'text'; errors collect
into errors[]. Barrel + README row + colocated tests (lib tests also run in node
env in CI — vi.stubGlobal any browser API).
Client pages & wiring
client/src/services/apiSongbook.js(template:apiRounds.js; trailingoptionsparam on every helper) +export * from './apiSongbook.js'inapi.js+ README row.client/src/pages/SongBook.jsx— index at/songbook. Card grid (Rounds.jsx template), filters in URL search params (?stage=&instrument=&tag=&q=, Catalog.jsx template), stage chips with aSONG_STAGE_COLORSmap (constants inclient/src/components/songbook/constants.js), quick stage-flip on cards (PATCH + reactive local-state update), New Song / Import buttons, EmptyState when empty, useConfirmDelete + ConfirmButtonPair for delete. NOT inisFullWidth.client/src/pages/SongBookViewer.jsx—/songbook/:id, full-bleed (RoundEditor template:flex flex-col h-full, shrink-0 header,flex-1 overflow-y-autobody it owns). Modes via search params:?mode=edit(editor textareafont-mono+ live preview) vs default play view.- Play view: rendered sheet from
parseTabSheet— section headers styled, chord tokens highlighted (text-port-accent font-semibold), tab staffs in a per-blockoverflow-x-autofont-monocontainer, ChordPro chord-over-lyric rendering. Controls bar: play/pause autoscroll, speed slider, transpose ± (renderstransposeTextresult, never mutates stored text; persiststransposeoffset per song via safeStorage), font size ±, stage select, capo/key/tuning badges, attachment list (opens/serves via API; "not on this machine" state), sourceUrl link. - Autoscroll (
client/src/components/songbook/useAutoscroll.jsor hook in hooks/ with barrel+README): rAF loop advancingcontainer.scrollTopat px/s; only meaningful when content overflows. Speed slider maps to px/s; ifscrollDurationSecset, a "fit to duration" preset computes px/s from scrollHeight. Pauses at bottom; user wheel/touch drag pauses autoscroll (resume button). Keyboard viauseKeyboardShortcuts: space = play/pause,+/-= speed,[/]= transpose,0= top. NewuseWakeLockhook (navigator.wakeLock, released on unmount/visibility loss) keeps the screen on while scrolling — checkclient/eslint.config.jsbrowserGlobals if lint complains. - Not-found fallback for stale ids; delete navigates back to
/songbook.
- Play view: rendered sheet from
- Import flow —
/songbook/import(also full-bleed exempt? keep it simple: padded page, NOT in isFullWidth — use the trailing-slash regex carefully:startsWith('/songbook/')would catch/songbook/import, so viewer full-bleed must exempt import, e.g. regex like the apps pattern, or make import a mode of the index page at/songbook?import=1… Decision: import lives at/songbook/import, and the isFullWidth check is/^\/songbook\/(?!import$)[^/]+/.test(pathname), mirroring the apps-create exclusion at Layout.jsx:1208). Two tabs (TabPills): Paste (textarea + readClipboard Paste button + livedetectFormat/normalizePastedTabpreview) and From URL (input validated withisUrl, plain POST via useAsyncAction). Both produce a draft → editable title/artist/instrument/tags/stage form → Save → POST → navigate to/songbook/:id. - Routing (
App.jsx):songbook,songbook/import,songbook/:id— alllazyWithReload. - Sidebar (
Layout.jsx): Brain section child{ to: '/songbook', label: 'SongBook' }alphabetical (between Rapid Reader and Timeline), distinct lucide icon (e.g.BookAudioorListMusic— Music/Mic taken). - Nav manifest (
server/lib/navManifest.js):{ id: 'nav.brain.songbook', path: '/songbook', label: 'SongBook', section: 'Brain', aliases: ['songbook', 'song-book', 'tabs', 'chords', 'guitar-tabs'], keywords: ['guitar', 'tab', 'tablature', 'chord chart', 'lyrics', 'sheet music', 'repertoire', 'autoscroll'] }— avoidsongs/song(already aliased to nav.create.rounds; first-declared wins).
Tests
- Server:
brainSongbookroute tests (crib brain route tests — CRUD, stage patch, attachment strip on PUT, 404s),brainSongbookImport.test.js(UG js-store fixture — INVENTED fixture data, never a real scrape dump;<pre>fallback; entity decoding; title/artist fallback), brainStorage enrollment sanity (songs type appears in getSummary / sync log round-trip if cheap). - Client:
tabNotation.test.js(chord-line detection incl. false positives like the lyric "A Boy Named Sue" line starting with A; tab staff detection; ChordPro; transpose incl. slash chords and column preservation; normalize). Component tests: SongBook index (api-barrel mock, RoundEditor.test.jsx harness style), viewer render + stage flip. - Run:
cd server && npm test,cd client && npm test(worktree symlinks node_modules from the primary checkout).
Privacy
No real song data, hostnames, or live-instance records in fixtures/docs/commits — invent fixture tabs (e.g. "Example Song" by "The Placeholders").
Explicitly deferred (PLAN.md items if not done)
Practice/spaced-rep integration (Shipped in #4102 — the SM-2 core moved out ofsongProgress.js/ SM-2 in meatspacePostMemory) — stage field is manual v1.meatspacePostMemory.jsintoserver/lib/spacedRepetition.js(shared, with the service re-exporting it),server/lib/songPractice.jsholds the song semantics, andPOST /:id/practicelogs a run graded 0..5 that advances thepracticeschedule and thestage.practiceis server-managed (no write- schema key, likeattachments) and derived on READ for songs predating the feature — no backfill migration, so thedata.reference/seeds stay byte-identical across installs.Linking a song to existing Rounds/Tracks/MIDI records (cross-links field).Shipped in #4103 — songs carrylinks: [{ type, id, label }](songLinkSchemainbrainValidation.js, ≤20 entries).typeisround | track, accepted as enum-OR-short-slug likeinstrument/formatso a link kind from a newer peer stays editable. There is deliberately nomiditype: MIDI is a file (already a songbook attachment) orreferenceAudio.midiFilenameon a Round, which theroundlink reaches.labelis the target's title denormalized at link time, because Rounds and Tracks are not brain records and may be absent on a given machine. NoPORTOS_SCHEMA_VERSIONSbump —brainhas no entry (records sync raw, no receive-side re-sanitize), so no peer can strip the field and LWW the loss back.- Chord diagrams / fretboard rendering; MIDI/score preview embedding in the viewer.
- Voice/palette actions (nav entry alone gives ⌘K + voice nav).
- Brain memory-bridge/graph enrollment for songs.
Post-review amendments (2026-07-15)
Applied after the 4-angle code review of feature/songbook; the sections above
are kept as the original design record.
PATCH /:id/stageremoved. The dedicated stage endpoint (andsongStagePatchSchema/ clientpatchSongStage) duplicated what the defaults-free partialPUT /:idalready does — stage flips now go throughupdateSong(id, { stage }).scrollDurationSecdropped fromsongInputSchema. Speculative in v1 (nothing consumed it). The "fit to duration" autoscroll preset that would re-add it is parked in PLAN.md under "SongBook follow-ups". Re-added in #4100 now that a UI consumes it: the field is back onsongInputSchema(nullable,null= no target), the Edit form carries a "Scroll time (seconds)" input, and the play-view controls bar grows a Fit button (also thefkey) that callsuseAutoscroll's newfitToDuration(sec)— px/s solved from the container's scrollable travel (scrollHeight - clientHeight, not rawscrollHeight, which would finish a screenful early) at click time, clamped to the speed slider's own bounds.songAttachmentSchema/songRecordSchemadeleted — dead exports; attachment metadata stays server-managed with no client-suppliable schema.- Shared helpers extracted: entity decoding via
decodeXmlEntities(server/lib/xmlEntities.js, mirrored bytabNotation.js's private decoder), strip-tags viaserver/lib/htmlToText.js(also adopted by the Gmail sync), and the attachment upload/serve pipeline viasaveBase64Upload/serveLocalFileinserver/lib/fileUtils.jswith a curatedSONGBOOK_ATTACHMENT_EXTENSIONSallowlist. - PUT content deep-merge.
songUpdateSchema(brainValidation.js) is defaults-free down to the nestedcontentobject, and the PUT handler deep-merges a partialcontentover 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 INSIDEwithStoreWriteLock, appliesfn(record) → partial(null aborts), and persists withupdate()'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.jsonships three public-domain "House of the Rising Sun" records (guitar/piano/ukulele);scripts/migrations/190-seed-songbook-songs.jsmerges them into existing installs (setup-data only copies missing files), never overwriting an existing/edited/tombstoned id. - Dash-joined chord support.
tabNotation.jstreatsAm-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.