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

17.1 KB
Raw Blame

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.json with { "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 ServerError
  • POST / — validateRequest(songInputSchema) → created record
  • PUT /:id — validateRequest(songInputSchema.partial()), strips attachments, → updated record
  • PATCH /: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). Service server/services/brainSongbookImport.js.
  • POST /:id/attachments — { filename, data (base64), label? }, 50MB cap, extension allowlist (crib server/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)

  1. assertPublicHttpUrl + text fetch via server/lib/safeUrlFetch.js.
  2. Extractors, first match wins: a. Ultimate Guitar: the page embeds JSON in <div class="js-store" data-content="..."> — HTML-entity-decode, JSON.parse, read store.page.data.tab_view.wiki_tab.content (tab text with [ch]...[/ch] / [tab]...[/tab] markers — strip markers) and store.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 as format: 'plain'.
  3. Title/artist fallback: <title> tag parsing ("X by Y" / "X - Y" patterns).
  4. 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; trailing options param on every helper) + export * from './apiSongbook.js' in api.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 a SONG_STAGE_COLORS map (constants in client/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 in isFullWidth.
  • client/src/pages/SongBookViewer.jsx — /songbook/:id, full-bleed (RoundEditor template: flex flex-col h-full, shrink-0 header, flex-1 overflow-y-auto body it owns). Modes via search params: ?mode=edit (editor textarea font-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-block overflow-x-auto font-mono container, ChordPro chord-over-lyric rendering. Controls bar: play/pause autoscroll, speed slider, transpose ± (renders transposeText result, never mutates stored text; persists transpose offset 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.js or hook in hooks/ with barrel+README): rAF loop advancing container.scrollTop at px/s; only meaningful when content overflows. Speed slider maps to px/s; if scrollDurationSec set, a "fit to duration" preset computes px/s from scrollHeight. Pauses at bottom; user wheel/touch drag pauses autoscroll (resume button). Keyboard via useKeyboardShortcuts: space = play/pause, +/- = speed, [/] = transpose, 0 = top. New useWakeLock hook (navigator.wakeLock, released on unmount/visibility loss) keeps the screen on while scrolling — check client/eslint.config.js browserGlobals if lint complains.
    • Not-found fallback for stale ids; delete navigates back to /songbook.
  • 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 + live detectFormat/normalizePastedTab preview) and From URL (input validated with isUrl, 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 — all lazyWithReload.
  • Sidebar (Layout.jsx): Brain section child { to: '/songbook', label: 'SongBook' } alphabetical (between Rapid Reader and Timeline), distinct lucide icon (e.g. BookAudio or ListMusic — 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'] } — avoid songs/song (already aliased to nav.create.rounds; first-declared wins).

Tests

  • Server: brainSongbook route 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 (songProgress.js / SM-2 in meatspacePostMemory) — stage field is manual v1. Shipped in #4102 — the SM-2 core moved out of meatspacePostMemory.js into server/lib/spacedRepetition.js (shared, with the service re-exporting it), server/lib/songPractice.js holds the song semantics, and POST /:id/practice logs a run graded 0..5 that advances the practice schedule and the stage. practice is server-managed (no write- schema key, like attachments) and derived on READ for songs predating the feature — no backfill migration, so the data.reference/ seeds stay byte-identical across installs.
  • Linking a song to existing Rounds/Tracks/MIDI records (cross-links field). Shipped in #4103 — songs carry links: [{ type, id, label }] (songLinkSchema in brainValidation.js, ≤20 entries). type is round | track, accepted as enum-OR-short-slug like instrument/format so a link kind from a newer peer stays editable. There is deliberately no midi type: MIDI is a file (already a songbook attachment) or referenceAudio.midiFilename on a Round, which the round link reaches. label is the target's title denormalized at link time, because Rounds and Tracks are not brain records and may be absent on a given machine. No PORTOS_SCHEMA_VERSIONS bump — brain has 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/stage removed. The dedicated stage endpoint (and songStagePatchSchema / client patchSongStage) duplicated what the defaults-free partial PUT /:id already does — stage flips now go through updateSong(id, { stage }).
  • scrollDurationSec dropped from songInputSchema. 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 on songInputSchema (nullable, null = no target), the Edit form carries a "Scroll time (seconds)" input, and the play-view controls bar grows a Fit button (also the f key) that calls useAutoscroll's new fitToDuration(sec) — px/s solved from the container's scrollable travel (scrollHeight - clientHeight, not raw scrollHeight, which would finish a screenful early) at click time, clamped to the speed slider's own bounds.
  • songAttachmentSchema / songRecordSchema deleted — dead exports; attachment metadata stays server-managed with no client-suppliable schema.
  • Shared helpers extracted: entity decoding via decodeXmlEntities (server/lib/xmlEntities.js, mirrored by tabNotation.js's private decoder), strip-tags via server/lib/htmlToText.js (also adopted by the 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.