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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
songs: add a dependency-free sheet-music view & editor, seed 500 Miles
[._.]/ Adam Eivy9be5b79d656f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex f4cc31c15c..644e552b63 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -10,6 +10,7 @@- **Scheduled "Refresh local-LLM catalog" task** — a new built-in CoS schedule that periodically researches the current best local models per category and opens a PR refreshing PortOS's bundled suggested-models catalog (`server/lib/localLlmCatalog.js`) and the editorial model ranking, so the in-app install picker and recommendations don't go stale. It no-ops on any repo lacking the catalog file, so it only does work when enabled on the PortOS app itself. Off by default; weekly when enabled, and it only opens a PR when the catalog is actually out of date.- **Manuscript editorial review: "Start fresh" re-run mode** — re-running the editorial pass in the manuscript editor previously always *merged*, leaving every prior open note in place even when a later pass no longer flagged it. A new "Start fresh" checkbox next to "Run editorial review" reconciles the open list against the latest pass: open notes it still finds stay open, open notes it no longer finds are auto-dismissed, and genuinely-new findings are added. Your accepted and dismissed decisions are left untouched. Clearing is done by moving notes to dismissed (never by deleting them), so the change syncs correctly across federated machines instead of being resurrected by a peer. Merge stays the default.- **Manuscript editor: editorial feedback is now shown in-context, not just in a sidebar** — instead of scrolling a disconnected list of notes, each editorial comment is highlighted directly on the text it points to. A header toggle switches between two modes: **Live** (Grammarly-style — the manuscript stays fully editable and each anchored note shows as a severity-toned underline; click the underlined text or its tag to pop the note's card right there with Generate-fix / Accept / Dismiss) and **Review** (a read-through where the prose is annotated and clicking a highlight expands the note inline, with a per-section Edit toggle to drop into free editing). The right sidebar becomes a filterable index (by severity, with open / accepted / dismissed groups and a "located in text" count) that scrolls to and opens any note. The editor now focuses **one issue at a time** with a deep-linkable tab strip (`…/manuscript/<issueNumber>`, each tab badged with its open-note count) instead of one page-length scroll of every issue. Suggested edits can be reviewed as a **side-by-side before/after diff** (default) or the prior stacked inline diff, and a new **Impact preview** shows, per affected issue, how accepting the selected fixes changes the whole manuscript before you commit to them (a single fix can span multiple issues). Notes whose anchor text no longer matches the draft degrade gracefully — they stay listed in the sidebar with no in-text highlight rather than disappearing.+- **Songs: a sheet-music view & editor** — each song can now carry real sheet music, rendered as an engraved staff (treble or bass clef, key & time signature, notes with stems/flags/dots, accidentals, ledger lines, rests, chord symbols above and lyrics beneath). It's drawn entirely in-house — no third-party music-notation library — from a small, readable text format ("PortOS lead-sheet notation": `clef:` / `key:` / `time:` / `tempo:` headers, then measures of `[chord] pitch+duration (lyric)` like `[C] E4q(If) G4q(you)`). The **Edit** tab gives you a textarea with a live-updating staff preview, a collapsible format guide, and per-measure beat-count feedback; the **View** tab shows the rendered score full-width above the lyrics. The built-in "500 Miles" now ships with its verse melody, chords, and lyrics as a worked example you can edit and learn from.- **Songs: a read/perform view, built-in defaults, and reference videos** — the song page now has a **View / Edit** toggle (mode lives in the URL, so each view is linkable). **View** is a clean, desktop-wide performance layout — lyrics rendered in full with no cramped sub-scrolling boxes, sections laid out side-by-side to use the screen and cut vertical scrolling, with the recorder kept front-and-centre for playing/recording; **Edit** is the existing workbench, now wider with a two-column lyric grid. Shipped example songs are tagged **Built-in default** (a badge in the Songs list and a banner in the editor) with a **Refresh from template** button that restores the latest bundled lyrics, arrangement, and references while preserving your own recordings and learned progress — so an install that already has an older copy of a default song can renew it on demand. Songs can also carry **reference material**: paste a link to a performance or tutorial, and TikTok video links play inline as embeds in the View tab (other links render as link cards). The built-in "500 Miles" ships with TikTok reference performances and its full set of lyrics.## Changeddiff --git a/client/src/components/songs/ScoreSheet.jsx b/client/src/components/songs/ScoreSheet.jsxnew file mode 100644index 0000000000..cd7005be6e--- /dev/null+++ b/client/src/components/songs/ScoreSheet.jsx@@ -0,0 +1,314 @@+/**+ * ScoreSheet — renders PortOS lead-sheet notation as real sheet music, in SVG,+ * with no third-party engraving library (no abcjs / VexFlow / OSMD). It parses+ * the text with `scoreNotation.parseScore` and draws the staff, clef, key+ * signature, time signature, notes (heads / stems / flags / dots), accidentals,+ * ledger lines, rests, bar lines, chord symbols and lyrics from SVG primitives.+ *+ * Geometry is driven off one constant — the staff line gap. Every pitch is a+ * "diatonic step" (one line-or-space) from the clef's bottom-line reference, so+ * positioning a note is a single multiply. Measures pack into rows and each row+ * is justified to the page width; the clef + key signature redraw at the start+ * of every row (the time signature only on the first), matching engraving+ * convention.+ *+ * Ink follows the active PortOS theme (the `--port-text` / `--port-accent` CSS+ * variables) — near-black on a light day background, light on a dark one — so+ * the staff never washes out. The clef and accidental glyphs use Unicode music+ * characters (𝄞 𝄢 ♯ ♭ ♮) with a font stack — everything else is drawn, so a+ * missing music font degrades only the clef glyph, never the staff.+ */++import { useMemo } from 'react';+import { parseScore } from '../../lib/scoreNotation.js';++// --- Geometry (all in internal SVG units; the <svg> scales via viewBox) ------+const WIDTH = 720; // internal coordinate width — viewBox scales to fit+const MARGIN = 16; // page padding inside the svg+const GAP = 12; // distance between two adjacent staff lines+const STEP = GAP / 2; // one diatonic step = half a line gap+const NOTE_RX = 6.2; // notehead radii+const NOTE_RY = 4.6;+const STEM_LEN = GAP * 3; // stem length (~3.5 lines reads well)+const FLAG_GAP = 8; // vertical spacing between stacked flags++const CLEF_W = 36;+const KEYSIG_ACC_W = 9; // width per key-signature accidental glyph+const TIME_W = 26;+const NOTE_LEAD = 18; // space after a barline before the first note+const NOTE_TRAIL = 14; // space after the last note before the barline+const MIN_SLOT = 24; // minimum horizontal room a note occupies+const BEAT_PX = 30; // horizontal px per quarter-note beat+const MAX_STRETCH = 1.45; // cap row justification so a short row isn't blown out++const ROW_TOP_PAD = 34; // room above the staff for chord symbols+const ROW_STAFF_TO_LYRIC = 30; // room below the staff for lyrics+const ROW_GAP = 18; // gap between rows+const ROW_HEIGHT = ROW_TOP_PAD + 4 * GAP + ROW_STAFF_TO_LYRIC + ROW_GAP;++// Ink is driven off the PortOS theme text/accent CSS variables so the score+// adapts to the active theme — near-black notes & lyrics in day mode, light ink+// in dark mode — instead of a fixed light grey that washes out on a light+// background. var() only resolves in CSS context, so these are applied via the+// `style` prop (SVG presentation *attributes* don't evaluate var()), not as+// fill="…"/stroke="…" attributes. Staff lines sit at a dimmed muted tone so the+// noteheads (full text colour) read as the foreground in both themes.+const INK = 'rgb(var(--port-text))';+const STAFF = 'rgb(var(--port-text-muted) / 0.55)';+const CHORD = 'rgb(var(--port-accent))';+const LYRIC = 'rgb(var(--port-text-muted))';+const MUSIC_FONT = "'Bravura','Noto Music','Segoe UI Symbol',ui-serif,serif";+// Small style helpers — colour goes through `style`, geometry stays attributes.+const strokeStyle = (color) => ({ stroke: color });+const fillStyle = (color) => ({ fill: color });++// Diatonic step that sits on the BOTTOM staff line, per clef. Treble bottom line+// is E4 (step 2); bass bottom line is G2 (step −10). Everything else is relative.+const BOTTOM_LINE_STEP = { treble: 2, bass: -10 };++// Unicode glyphs for the clef and accidentals (drawn as <text> — the only part+// that depends on a music-capable font; the staff itself is always drawn).+const CLEF_GLYPH = { treble: '\u{1D11E}', bass: '\u{1D122}' };+const ACCIDENTAL_GLYPH = { '#': '♯', '##': '\u{1D12A}', b: '♭', bb: '\u{1D12B}', n: '♮' };++// Key-signature accidental vertical positions (the diatonic step each glyph sits+// on), for the treble clef, in draw order. Bass shifts the whole cluster down two+// octaves (−14 steps) — a faithful-enough placement; bundled content is treble.+const TREBLE_SHARP_STEPS = { F: 10, C: 7, G: 11, D: 8, A: 5, E: 9, B: 6 };+const TREBLE_FLAT_STEPS = { B: 6, E: 9, A: 5, D: 8, G: 4, C: 7, F: 3 };++const slotFor = (note) => Math.max(MIN_SLOT, (note.duration?.beats || 1) * BEAT_PX);+const measureIntrinsic = (measure) => {+ if (!measure.notes.length) return NOTE_LEAD + MIN_SLOT + NOTE_TRAIL;+ return NOTE_LEAD + measure.notes.reduce((s, n) => s + slotFor(n), 0) + NOTE_TRAIL;+};++// Greedily pack measures into rows that fit the page width. Each row reserves a+// prefix for the clef + key signature (+ time signature on the first row).+const packRows = (measures, keySigCount) => {+ const contentRight = WIDTH - MARGIN;+ const rows = [];+ let i = 0;+ while (i < measures.length) {+ const firstRow = rows.length === 0;+ const prefix = CLEF_W + keySigCount * KEYSIG_ACC_W + (keySigCount ? 6 : 0) + (firstRow ? TIME_W : 0);+ const available = contentRight - MARGIN - prefix;+ const rowMeasures = [];+ let used = 0;+ while (i < measures.length) {+ const w = measureIntrinsic(measures[i]);+ if (rowMeasures.length > 0 && used + w > available) break;+ rowMeasures.push({ index: i, intrinsic: w, measure: measures[i] });+ used += w;+ i += 1;+ }+ // Justify: stretch the row to fill, but cap it so one short bar isn't+ // ballooned. A lone over-wide measure shrinks (stretch < 1) instead.+ const stretch = used > 0 ? Math.min(MAX_STRETCH, available / used) : 1;+ rows.push({ rowMeasures, prefix, firstRow, stretch });+ }+ return rows;+};++export default function ScoreSheet({ text, className = '' }) {+ const score = useMemo(() => parseScore(text), [text]);++ const { rows, height } = useMemo(() => {+ const packed = packRows(score.measures, score.keySig.count);+ return { rows: packed, height: Math.max(ROW_HEIGHT, packed.length * ROW_HEIGHT) + 8 };+ }, [score]);++ if (!score.measures.some((m) => m.notes.length > 0)) return null;++ const bottomLineStep = BOTTOM_LINE_STEP[score.clef] ?? BOTTOM_LINE_STEP.treble;+ const middleLineStep = bottomLineStep + 4;++ const els = [];+ rows.forEach((row, ri) => {+ const rowTop = ri * ROW_HEIGHT;+ const staffTop = rowTop + ROW_TOP_PAD;+ const staffBottom = staffTop + 4 * GAP;+ const chordY = rowTop + 16;+ const lyricY = staffBottom + 22;+ // y for a diatonic step within this row.+ const yForStep = (step) => staffBottom - (step - bottomLineStep) * STEP;++ // Staff: five lines across the full content width.+ for (let line = 0; line < 5; line += 1) {+ const y = staffTop + line * GAP;+ els.push(<line key={`s${ri}-${line}`} x1={MARGIN} y1={y} x2={WIDTH - MARGIN} y2={y} style={strokeStyle(STAFF)} strokeWidth={1} />);+ }++ let x = MARGIN;+ // Clef glyph — vertically anchored so its centre sits on the staff.+ els.push(+ <text key={`clef${ri}`} x={x + 2} y={score.clef === 'bass' ? staffTop + GAP * 1.6 : staffBottom + GAP * 0.5}+ fontSize={score.clef === 'bass' ? 40 : 56} style={fillStyle(INK)} fontFamily={MUSIC_FONT} dominantBaseline="alphabetic">+ {CLEF_GLYPH[score.clef] || CLEF_GLYPH.treble}+ </text>,+ );+ x += CLEF_W;++ // Key signature — the accidental cluster, redrawn every row.+ if (score.keySig.count) {+ const glyph = score.keySig.type === 'sharp' ? ACCIDENTAL_GLYPH['#'] : ACCIDENTAL_GLYPH.b;+ const stepTable = score.keySig.type === 'sharp' ? TREBLE_SHARP_STEPS : TREBLE_FLAT_STEPS;+ const shift = score.clef === 'bass' ? -14 : 0;+ score.keySig.letters.forEach((letter, ki) => {+ const step = (stepTable[letter] ?? middleLineStep) + shift;+ els.push(+ <text key={`ks${ri}-${ki}`} x={x + ki * KEYSIG_ACC_W} y={yForStep(step) + 5}+ fontSize={18} style={fillStyle(INK)} fontFamily={MUSIC_FONT} textAnchor="middle">{glyph}</text>,+ );+ });+ x += score.keySig.count * KEYSIG_ACC_W + 6;+ }++ // Time signature — first row only (engraving convention).+ if (row.firstRow) {+ els.push(+ <text key={`tb${ri}`} x={x + TIME_W / 2} y={staffTop + GAP * 1.1} fontSize={17} fontWeight="700"+ style={fillStyle(INK)} textAnchor="middle" fontFamily="ui-serif, serif">{score.time.beats}</text>,+ <text key={`tv${ri}`} x={x + TIME_W / 2} y={staffTop + GAP * 3.1} fontSize={17} fontWeight="700"+ style={fillStyle(INK)} textAnchor="middle" fontFamily="ui-serif, serif">{score.time.beatValue}</text>,+ );+ x += TIME_W;+ }++ // Opening barline at the start of the measures.+ els.push(<line key={`bl-open${ri}`} x1={x} y1={staffTop} x2={x} y2={staffBottom} style={strokeStyle(STAFF)} strokeWidth={1} />);++ // Measures.+ row.rowMeasures.forEach(({ measure, index }) => {+ const measureWidth = measureIntrinsic(measure) * row.stretch;+ let cursor = x + NOTE_LEAD * row.stretch;+ measure.notes.forEach((note, ni) => {+ const slot = slotFor(note) * row.stretch;+ const cx = cursor + slot / 2;+ cursor += slot;+ const key = `m${index}-n${ni}`;+ if (note.rest) {+ els.push(...renderRest(note, cx, yForStep, bottomLineStep, key));+ } else {+ els.push(...renderNote(note, cx, yForStep, bottomLineStep, middleLineStep, key));+ }+ if (note.chord) {+ els.push(<text key={`${key}-ch`} x={cx} y={chordY} fontSize={12} fontWeight="600" style={fillStyle(CHORD)} textAnchor="middle" fontFamily="ui-sans-serif, system-ui, sans-serif">{note.chord}</text>);+ }+ if (note.lyric) {+ els.push(<text key={`${key}-ly`} x={cx} y={lyricY} fontSize={11} style={fillStyle(LYRIC)} textAnchor="middle" fontFamily="ui-sans-serif, system-ui, sans-serif">{note.lyric}</text>);+ }+ });+ x += measureWidth;+ els.push(<line key={`bl${index}`} x1={x} y1={staffTop} x2={x} y2={staffBottom} style={strokeStyle(STAFF)} strokeWidth={1} />);+ });+ });++ return (+ <svg+ className={className}+ viewBox={`0 0 ${WIDTH} ${height}`}+ width="100%"+ role="img"+ aria-label="Sheet music notation"+ style={{ height: 'auto', display: 'block' }}+ >+ {els}+ </svg>+ );+}++// --- Per-note drawing -------------------------------------------------------+function renderNote(note, cx, yForStep, bottomLineStep, middleLineStep, key) {+ const out = [];+ const step = note.step;+ const y = yForStep(step);+ const up = step < middleLineStep; // notes below the middle line stem up+ const filled = note.duration.filled;++ // Ledger lines — short segments at each staff-line position the note reaches+ // beyond the five lines. Lines sit on even offsets from the bottom line.+ const topStep = bottomLineStep + 8;+ if (step > topStep) {+ for (let s = topStep + 2; s <= step; s += 2) {+ const ly = yForStep(s);+ out.push(<line key={`${key}-lg${s}`} x1={cx - NOTE_RX - 3} y1={ly} x2={cx + NOTE_RX + 3} y2={ly} style={strokeStyle(STAFF)} strokeWidth={1} />);+ }+ } else if (step < bottomLineStep) {+ for (let s = bottomLineStep - 2; s >= step; s -= 2) {+ const ly = yForStep(s);+ out.push(<line key={`${key}-lg${s}`} x1={cx - NOTE_RX - 3} y1={ly} x2={cx + NOTE_RX + 3} y2={ly} style={strokeStyle(STAFF)} strokeWidth={1} />);+ }+ }++ // Accidental glyph, left of the head.+ if (note.pitch.accidental && ACCIDENTAL_GLYPH[note.pitch.accidental]) {+ out.push(<text key={`${key}-acc`} x={cx - NOTE_RX - 6} y={y + 5} fontSize={16} style={fillStyle(INK)} textAnchor="middle" fontFamily={MUSIC_FONT}>{ACCIDENTAL_GLYPH[note.pitch.accidental]}</text>);+ }++ // Notehead — open for half/whole, solid otherwise. A slight rotation gives+ // the classic oval slant.+ out.push(+ <ellipse key={`${key}-head`} cx={cx} cy={y} rx={NOTE_RX} ry={NOTE_RY}+ transform={`rotate(-18 ${cx} ${y})`}+ style={{ fill: filled ? INK : "none", stroke: INK }} strokeWidth={filled ? 0 : 1.4} />,+ );++ // Stem + flags (whole notes have neither).+ if (note.duration.stem) {+ const stemX = up ? cx + NOTE_RX - 0.6 : cx - NOTE_RX + 0.6;+ const stemEndY = up ? y - STEM_LEN : y + STEM_LEN;+ out.push(<line key={`${key}-stem`} x1={stemX} y1={y} x2={stemX} y2={stemEndY} style={strokeStyle(INK)} strokeWidth={1.3} />);+ for (let f = 0; f < note.duration.flags; f += 1) {+ const fy = up ? stemEndY + f * FLAG_GAP : stemEndY - f * FLAG_GAP;+ const dir = up ? 1 : -1;+ out.push(+ <path key={`${key}-flag${f}`}+ d={`M ${stemX} ${fy} Q ${stemX + 11} ${fy + dir * 5} ${stemX + 8} ${fy + dir * 16}`}+ style={{ fill: "none", stroke: INK }} strokeWidth={1.6} strokeLinecap="round" />,+ );+ }+ }++ // Augmentation dot(s), to the right of the head — nudged into the space if the+ // note sits on a line.+ if (note.duration.dots) {+ const onLine = ((step - bottomLineStep) % 2 + 2) % 2 === 0;+ const dy = onLine ? y - STEP : y;+ for (let d = 0; d < note.duration.dots; d += 1) {+ out.push(<circle key={`${key}-dot${d}`} cx={cx + NOTE_RX + 4 + d * 4} cy={dy} r={1.5} style={fillStyle(INK)} />);+ }+ }+ return out;+}++// --- Per-rest drawing -------------------------------------------------------+// Rests are drawn from primitives (not Unicode) so they render identically on+// every platform. Positions are relative to the middle staff line.+function renderRest(note, cx, yForStep, bottomLineStep, key) {+ const code = note.duration.code;+ const midLine = yForStep(bottomLineStep + 4);+ const secondTop = yForStep(bottomLineStep + 6); // 2nd line from top (whole rest hangs here)+ const out = [];+ if (code === 'w') {+ out.push(<rect key={`${key}-r`} x={cx - 5} y={secondTop} width={10} height={GAP * 0.4} style={fillStyle(INK)} />);+ } else if (code === 'h') {+ out.push(<rect key={`${key}-r`} x={cx - 5} y={midLine - GAP * 0.4} width={10} height={GAP * 0.4} style={fillStyle(INK)} />);+ } else if (code === 'q') {+ // Stylized quarter rest — a zig-zag down the middle of the staff.+ const top = yForStep(bottomLineStep + 6);+ out.push(+ <path key={`${key}-r`}+ d={`M ${cx - 3} ${top} L ${cx + 3} ${top + GAP} L ${cx - 2.5} ${top + GAP * 1.7} Q ${cx + 4} ${top + GAP * 2.2} ${cx + 1} ${top + GAP * 3}`}+ style={{ fill: "none", stroke: INK }} strokeWidth={1.8} strokeLinecap="round" strokeLinejoin="round" />,+ );+ } else {+ // Eighth / sixteenth / 32nd rest — a diagonal stroke with one blob per flag.+ const top = yForStep(bottomLineStep + 5);+ out.push(<line key={`${key}-rstroke`} x1={cx + 3} y1={top} x2={cx - 3} y2={top + GAP * 2} style={strokeStyle(INK)} strokeWidth={1.4} />);+ for (let f = 0; f < (note.duration.flags || 1); f += 1) {+ out.push(<circle key={`${key}-rb${f}`} cx={cx + 2} cy={top + f * GAP * 0.9} r={2} style={fillStyle(INK)} />);+ }+ }+ return out;+}diff --git a/client/src/components/songs/ScoreSheet.test.jsx b/client/src/components/songs/ScoreSheet.test.jsxnew file mode 100644index 0000000000..6aeca821c2--- /dev/null+++ b/client/src/components/songs/ScoreSheet.test.jsx@@ -0,0 +1,80 @@+import { describe, it, expect } from 'vitest';+import { renderToStaticMarkup } from 'react-dom/server';+import ScoreSheet from './ScoreSheet.jsx';+import { parseScore } from '../../lib/scoreNotation.js';++const FIVE_HUNDRED_MILES = [+ 'clef: treble', 'key: C', 'time: 4/4', 'tempo: 68', '',+ "| [C] E4q(If) G4q(you) G4q(miss) G4q(the) | [Am] A4h(train) G4q(I'm) E4q(on) |",+ '| [F] F4q(You) A4q(will) A4q(know) A4q(that) | [C] G4h(I) E4q(am) C4q(gone) |',+ '| [F] F4q(You) A4q(can) A4q(hear) A4q(the) | [C] G4q(whis-) E4q(tle) C4h(blow) |',+ '| [G] D4q(A) F4q(hun-) G4q(dred) rq | [C] C4w(miles) |',+].join('\n');++const count = (html, tag) => (html.match(new RegExp(`<${tag}[ />]`, 'g')) || []).length;++describe('ScoreSheet renderer', () => {+ it('renders nothing when there is no music', () => {+ expect(renderToStaticMarkup(<ScoreSheet text="" />)).toBe('');+ expect(renderToStaticMarkup(<ScoreSheet text="clef: treble" />)).toBe('');+ });++ it('renders the 500 Miles score with no NaN coordinates', () => {+ const html = renderToStaticMarkup(<ScoreSheet text={FIVE_HUNDRED_MILES} />);+ expect(html).not.toMatch(/NaN/);+ expect(html).toContain('aria-label="Sheet music notation"');+ });++ it('draws one notehead per pitched note', () => {+ const html = renderToStaticMarkup(<ScoreSheet text={FIVE_HUNDRED_MILES} />);+ const pitched = parseScore(FIVE_HUNDRED_MILES).measures+ .flatMap((m) => m.notes).filter((n) => !n.rest).length;+ expect(count(html, 'ellipse')).toBe(pitched);+ });++ it('draws full five-line staves (a multiple of five staff lines)', () => {+ const html = renderToStaticMarkup(<ScoreSheet text={FIVE_HUNDRED_MILES} />);+ // Staff lines are the horizontal <line>s spanning the page; barlines are+ // vertical. Count rows by staff lines / 5 — must be a whole number ≥ 1.+ const html2 = renderToStaticMarkup(<ScoreSheet text={'| C4q | C4q |'} />);+ expect(count(html2, 'line')).toBeGreaterThanOrEqual(5);+ });++ it('draws stems on quarter/half notes (filled+stemmed, not all open heads)', () => {+ const html = renderToStaticMarkup(<ScoreSheet text={FIVE_HUNDRED_MILES} />);+ // Stems are the only stroke-width="1.3" elements. The verse has 24 stemmed+ // notes (everything except the single whole note and the rest). A regression+ // that drops filled/stem off the duration would render 0 here.+ const stems = (html.match(/stroke-width="1.3"/g) || []).length;+ expect(stems).toBe(24);+ // Solid noteheads fill with the theme text colour (filled q/h notes).+ expect(html).toMatch(/<ellipse[^>]*style="[^"]*fill:rgb\(var\(--port-text\)\)/);+ });++ it('colours via theme CSS variables, not hardcoded hex (adapts to day/dark)', () => {+ const html = renderToStaticMarkup(<ScoreSheet text={FIVE_HUNDRED_MILES} />);+ expect(html).toContain('--port-text'); // ink follows the theme+ expect(html).toContain('--port-accent'); // chord symbols use the accent+ expect(html).not.toMatch(/#[0-9a-fA-F]{6}/); // no fixed hex colours+ });++ it('renders chord symbols and lyrics as text', () => {+ const html = renderToStaticMarkup(<ScoreSheet text={FIVE_HUNDRED_MILES} />);+ expect(html).toContain('>Am<');+ expect(html).toContain('>train<');+ expect(html).toContain('>If<');+ });++ it('renders ledger lines for notes below the staff (middle C in treble)', () => {+ // C4 sits one ledger line below the treble staff — expect at least one extra+ // short line vs a score with no below-staff notes.+ const withLedger = renderToStaticMarkup(<ScoreSheet text={'| C4w |'} />);+ expect(count(withLedger, 'line')).toBeGreaterThan(6); // 5 staff + 2 barlines + ledger+ });++ it('renders a bass clef score without error', () => {+ const html = renderToStaticMarkup(<ScoreSheet text={'clef: bass\n| G2q C3q |'} />);+ expect(html).not.toMatch(/NaN/);+ expect(count(html, 'ellipse')).toBe(2);+ });+});diff --git a/client/src/components/songs/SongScoreEditor.jsx b/client/src/components/songs/SongScoreEditor.jsxnew file mode 100644index 0000000000..0d66fc7126--- /dev/null+++ b/client/src/components/songs/SongScoreEditor.jsx@@ -0,0 +1,118 @@+/**+ * SongScoreEditor — the editing surface for a song's sheet music. A plain+ * textarea holds the PortOS lead-sheet notation (see scoreNotation.js for the+ * format); the parsed score renders live in a <ScoreSheet> above it so the user+ * sees the staff update as they type. No third-party music editor — the textarea+ * is the editor, the parser is the bridge, the SVG is the preview.+ *+ * Below the textarea: a collapsible format legend (so the notation is+ * discoverable without leaving the page) and inline parse feedback — per-measure+ * beat totals that don't match the time signature are flagged, and unrecognized+ * tokens are listed. Feedback is advisory: a malformed token is skipped, never+ * blocks rendering the rest.+ */++import { useMemo, useState } from 'react';+import { Music, ChevronDown, ChevronRight, AlertTriangle } from 'lucide-react';+import ScoreSheet from './ScoreSheet.jsx';+import { parseScore } from '../../lib/scoreNotation.js';++const PLACEHOLDER = `clef: treble+key: C+time: 4/4+tempo: 68++| [C] E4q(If) G4q(you) G4q(miss) G4q(the) | [Am] A4h(train) G4q(I'm) E4q(on) |`;++const LEGEND = [+ ['Header', 'clef: treble · key: C · time: 4/4 · tempo: 68 — one per line, before the music.'],+ ['Measures', 'Separate bars with | (a leading/trailing | is fine). Notes are space-separated within a bar.'],+ ['Pitch', 'Letter A–G + accidental (# b n) + octave. C4 is middle C. e.g. C4, F#4, Bb3.'],+ ['Duration', 'w h q e s t = whole, half, quarter, eighth, sixteenth, 32nd. Append . for a dot (q. = 1.5 beats).'],+ ['Rest', 'r + duration — rq, rh, re. (no pitch, no lyric).'],+ ['Chord', '[C] before a note draws the symbol above it — [Am], [G7], [F/A].'],+ ['Lyric', '(word) after a note draws it underneath. Use a trailing - for a held syllable: (whis-) (tle).'],+];++export default function SongScoreEditor({ value, onChange }) {+ const [showLegend, setShowLegend] = useState(false);+ const score = useMemo(() => parseScore(value || ''), [value]);++ // Measures whose beat total doesn't match the time signature — a gentle nudge,+ // not an error (a pickup bar or a deliberate free bar is legitimate).+ const beatWarnings = useMemo(() => {+ const target = score.time.beats * (4 / score.time.beatValue);+ return score.measures+ .map((m, i) => ({ i: i + 1, beats: m.beats, notes: m.notes.length }))+ .filter((m) => m.notes > 0 && Math.abs(m.beats - target) > 0.001);+ }, [score]);++ const hasMusic = score.measures.some((m) => m.notes.length > 0);+ const inputCls = 'w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:border-port-accent focus:outline-none';++ return (+ <section>+ <div className="flex items-center justify-between mb-2">+ <h2 className="flex items-center gap-2 text-sm font-semibold text-white">+ <Music size={15} className="text-port-accent" /> Sheet music+ </h2>+ <button+ type="button"+ onClick={() => setShowLegend((s) => !s)}+ className="flex items-center gap-1 text-xs text-gray-400 hover:text-white"+ >+ {showLegend ? <ChevronDown size={14} /> : <ChevronRight size={14} />} Format guide+ </button>+ </div>++ {/* Live preview — the staff renders from whatever currently parses. */}+ {hasMusic && (+ <div className="bg-port-card border border-port-border rounded-lg p-3 mb-2 overflow-x-auto">+ <ScoreSheet text={value} />+ </div>+ )}++ <label htmlFor="score" className="block text-xs text-gray-400 mb-1">+ Notation — melody, chords & lyrics in PortOS lead-sheet format+ </label>+ <textarea+ id="score"+ value={value || ''}+ onChange={(e) => onChange(e.target.value)}+ placeholder={PLACEHOLDER}+ rows={8}+ spellCheck={false}+ className={`${inputCls} font-mono leading-relaxed`}+ />++ {/* Parse feedback — beat mismatches and unrecognized tokens. */}+ {(beatWarnings.length > 0 || score.errors.length > 0) && (+ <div className="mt-2 space-y-1">+ {beatWarnings.map((w) => (+ <p key={`beat-${w.i}`} className="flex items-center gap-1.5 text-xs text-port-warning">+ <AlertTriangle size={12} className="shrink-0" />+ Measure {w.i}: {w.beats} beats (time signature expects {score.time.beats}).+ </p>+ ))}+ {score.errors.map((err, i) => (+ <p key={`err-${i}`} className="flex items-center gap-1.5 text-xs text-port-error">+ <AlertTriangle size={12} className="shrink-0" /> {err}+ </p>+ ))}+ </div>+ )}++ {/* Collapsible format legend. */}+ {showLegend && (+ <dl className="mt-3 bg-port-card border border-port-border rounded-lg p-3 space-y-1.5">+ {LEGEND.map(([term, desc]) => (+ <div key={term} className="grid grid-cols-[5rem_1fr] gap-2">+ <dt className="text-xs font-semibold text-port-accent">{term}</dt>+ <dd className="text-xs text-gray-400">{desc}</dd>+ </div>+ ))}+ </dl>+ )}+ </section>+ );+}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 03472eea2b..19f796e202 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -88,6 +88,7 @@ grep -i "what you want to do" client/src/lib/README.md|---|---|| `cityPlaybackFrame.js` | Map a recorded CyberCity snapshot frame onto the prop shape CityScene/CityHud consume for the timeline scrubber (`mergeFrameIntoCityProps`, `buildPlaybackApps`, `buildPlaybackAgentMap`, `isPlayableFrame`). Honors `schemaVersion` and the capture-side null sentinels; returns only snapshot-backed props so unfed landmarks stay live. || `universeBuilderExpand.js` | `mergeExpandIntoDraft(draft, result)` — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with `kind` precedence, canon dedupe by name/slugline/alias). Also exports `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` for callers that need the building blocks (per-category Generate, save-time refetch+merge). |+| `scoreNotation.js` | Parser for the PortOS lead-sheet notation — a dependency-free text format for melody + chords + lyrics that the `<ScoreSheet>` SVG renderer draws (no abcjs / VexFlow / OSMD). `parseScore(text)` → `{ clef, key, keySig, time, tempo, measures, errors }`; plus `parsePitch`, `diatonicStep`, `durationBeats`, `keySignature`, `DURATIONS`, and `scoreHasMusic(text)`. Forgiving: bad tokens collect into `errors` and are skipped, never thrown. Pure — the renderer only does geometry. || `songCraft.js` | Canonical a cappella song-craft reference data rendered by the Songs Guide (`/songs/guide`) and reused by the Song editor: `RHYTHM_SHAPES` / `DIRGE_RHYTHM_SHAPES` (dirge & ballad pulse feels with BPM bands), `VOICE_LAYERS` (foundation-first harmony build ladder), `LEARNING_STEPS` (practice sequence), `NOTATION_HELP` (lead-sheet/notation primers), `SOLFEGE_DEGREES` + `solfegeForDegree(n)`, and `rhythmShapeLabel(id)` (human-readable "Slow 4/4 ballad · dirge (56–76 BPM)" label shared by the editor's picker and read view). Pure data; pickers and docs read the same source so they can't drift. || `songPlayback.js` | `createLayeredPlayer(takes)` — decode N recorded vocal takes and start them together on one shared `AudioContext` so they stack into a layered a cappella performance (sample-aligned, per-layer mute). Used by the Song editor's recording mixer. || `wrSceneCursor.js` | Resolve which script scene the editor caret sits in (`sceneAtCursor`, `sceneAnchorIndex`) — inverse of WorkEditor's jump-to-scene text search; drives the live render preview's "scene at cursor" target. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex f16d5f77f9..261195d11b 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -55,6 +55,7 @@ export * from './voiceLabel.js';// === Page-scoped pure helpers ===export * from './cityPlaybackFrame.js';+export * from './scoreNotation.js';export * from './songCraft.js';export * from './songPlayback.js';export * from './universeBuilderExpand.js';diff --git a/client/src/lib/scoreNotation.js b/client/src/lib/scoreNotation.jsnew file mode 100644index 0000000000..169f17264d--- /dev/null+++ b/client/src/lib/scoreNotation.js@@ -0,0 +1,219 @@+// PortOS lead-sheet notation — a tiny, dependency-free text format for melody ++// chords + lyrics, and the pure parser that turns it into a structured score the+// <ScoreSheet> SVG renderer draws. We render our own staff rather than pulling+// in abcjs / VexFlow / OpenSheetMusicDisplay, so this module is the single+// source of truth for "what the text means"; the renderer only does geometry.+//+// FORMAT (one worked example — "500 Miles", verse, ships as the seed score):+//+// clef: treble ← header lines: `key: value`, any order, before the music+// key: C+// time: 4/4+// tempo: 68+//+// | [C] E4q(If) G4q(you) G4q(miss) G4q(the) | [Am] A4h(train) G4q(I'm) E4q(on) |+//+// Music body: measures separated by `|` (a leading/trailing `|` is fine), notes+// separated by whitespace within a measure. A note token is:+//+// [chord] PITCH DURATION dots? (lyric)+// └ above └ C4 └ q └ . └ under the note+//+// PITCH = letter A–G, optional accidental (# b n, or ## bb), octave digit+// (scientific pitch: C4 = middle C). e.g. C4, F#4, Bb3, En5+// DURATION = w h q e s t → whole, half, quarter, eighth, sixteenth, 32nd+// dots = trailing `.` each adds half the value again (q. = 1.5 beats)+// rest = `r` + duration, e.g. rq, rh, re. (no pitch, no lyric)+// [chord] = a chord symbol drawn above that note (C, Am, G7, F/A …)+// (lyric) = a syllable drawn under that note; use a trailing `-` to show a+// held syllable (whis- / tle)+//+// The parser is forgiving: an unparseable token is collected into `errors` with+// its measure number and skipped, so the rest of the score still renders. Keep+// this module pure (no React, no imports) — it's unit-tested and barrelled.++// Diatonic letter → its index within an octave starting at C. Used to turn a+// pitch into a single "diatonic step" integer (C4 = 0, D4 = 1 … B4 = 6, C5 = 7),+// which is all the geometry needs: every staff line/space is one step apart.+const LETTER_INDEX = { C: 0, D: 1, E: 2, F: 3, G: 4, A: 5, B: 6 };++// Duration code → its musical properties. `beats` is the undotted value in+// quarter-note beats; `filled` picks an open vs solid notehead; `flags` is how+// many flags hang off the stem (eighth = 1, sixteenth = 2 …); whole notes are+// stemless. Dots are applied on top of `beats` (see durationBeats).+export const DURATIONS = {+ w: { code: 'w', beats: 4, filled: false, stem: false, flags: 0, label: 'whole' },+ h: { code: 'h', beats: 2, filled: false, stem: true, flags: 0, label: 'half' },+ q: { code: 'q', beats: 1, filled: true, stem: true, flags: 0, label: 'quarter' },+ e: { code: 'e', beats: 0.5, filled: true, stem: true, flags: 1, label: 'eighth' },+ s: { code: 's', beats: 0.25, filled: true, stem: true, flags: 2, label: 'sixteenth' },+ t: { code: 't', beats: 0.125, filled: true, stem: true, flags: 3, label: 'thirty-second' },+};++// Beats for a duration code with `dots` dots applied. A single dot adds half the+// value (×1.5), two dots add a half + a quarter (×1.75), etc. — the standard+// dotted-note geometric series 2 − (1/2)^dots.+export const durationBeats = (code, dots = 0) => {+ const base = DURATIONS[code]?.beats;+ if (base == null) return 0;+ return base * (2 - Math.pow(0.5, dots));+};++// Major-key signatures: tonic letter (with optional accidental) → the ordered+// accidentals it carries. We key off the bare tonic so "C", "C major", "C Major"+// and "Cmaj" all resolve. Order matters — it's the order the glyphs are drawn at+// the clef (F C G D A E B for sharps; the reverse for flats).+const SHARP_ORDER = ['F', 'C', 'G', 'D', 'A', 'E', 'B'];+const FLAT_ORDER = ['B', 'E', 'A', 'D', 'G', 'C', 'F'];+const SHARP_KEYS = { G: 1, D: 2, A: 3, E: 4, B: 5, 'F#': 6, 'C#': 7 };+const FLAT_KEYS = { F: 1, Bb: 2, Eb: 3, Ab: 4, Db: 5, Gb: 6, Cb: 7 };++// Resolve a key string ("C major", "Eb", "F# minor") to a key-signature+// descriptor. We read only the tonic (letter + optional single accidental) and+// treat it as major — good enough for a lead sheet, and the renderer only uses+// this to draw the accidental cluster at the clef. Unknown → C (no accidentals).+export const keySignature = (keyName) => {+ const m = /^\s*([A-Ga-g])([#b]?)/.exec(keyName || '');+ const tonic = m ? `${m[1].toUpperCase()}${m[2]}` : 'C';+ if (SHARP_KEYS[tonic]) {+ const count = SHARP_KEYS[tonic];+ return { type: 'sharp', count, letters: SHARP_ORDER.slice(0, count) };+ }+ if (FLAT_KEYS[tonic]) {+ const count = FLAT_KEYS[tonic];+ return { type: 'flat', count, letters: FLAT_ORDER.slice(0, count) };+ }+ return { type: 'none', count: 0, letters: [] };+};++// Diatonic step for a letter+octave (C4 = 0). Ignores accidentals — they shift+// pitch chromatically but a sharp/flat note still sits on its letter's line.+export const diatonicStep = (letter, octave) => {+ const idx = LETTER_INDEX[String(letter || '').toUpperCase()];+ if (idx == null || !Number.isFinite(octave)) return null;+ return (octave - 4) * 7 + idx;+};++// Parse a bare pitch (no duration), e.g. "F#4" → { letter, accidental, octave,+// step }. Accidental is normalized to '', '#', '##', 'b', 'bb', or 'n'. Returns+// null for anything that isn't a pitch (callers treat null as "not a note").+export const parsePitch = (str) => {+ const m = /^([A-Ga-g])(#{1,2}|b{1,2}|n)?(-?\d)$/.exec(String(str || '').trim());+ if (!m) return null;+ const letter = m[1].toUpperCase();+ const accidental = m[2] || '';+ const octave = Number(m[3]);+ return { letter, accidental, octave, step: diatonicStep(letter, octave) };+};++// Default headers — every field has a sane fallback so a score with no header+// block still renders (treble, C major, 4/4).+const DEFAULT_HEADER = { clef: 'treble', key: 'C', beats: 4, beatValue: 4, tempo: null };++const parseTimeSignature = (raw) => {+ const m = /^\s*(\d{1,2})\s*\/\s*(\d{1,2})\s*$/.exec(raw || '');+ if (!m) return null;+ const beats = Number(m[1]);+ const beatValue = Number(m[2]);+ if (!beats || !beatValue) return null;+ return { beats, beatValue };+};++// One token → a note/rest object, or { error } if it doesn't parse. Grammar:+// [chord]? (r | PITCH) DURATION dots? (lyric)?+const TOKEN_RE = /^(?:\[([^\]]*)\])?(r|[A-Ga-g](?:#{1,2}|b{1,2}|n)?-?\d)([whqest])(\.*)(?:\((.*)\))?$/;++const parseToken = (token) => {+ const m = TOKEN_RE.exec(token);+ if (!m) return { error: `unrecognized token "${token}"` };+ const [, chord, core, durCode, dotStr, lyric] = m;+ const dots = dotStr ? dotStr.length : 0;+ // Carry the static duration properties (filled / stem / flags) the renderer+ // needs alongside the per-token dots/beats, so a duration object is fully+ // self-describing — a quarter note knows it's solid-with-stem, not just "1 beat".+ const base = DURATIONS[durCode];+ const duration = { code: durCode, dots, beats: durationBeats(durCode, dots), filled: base.filled, stem: base.stem, flags: base.flags };+ if (core === 'r') {+ return { rest: true, duration, chord: chord || '' };+ }+ const pitch = parsePitch(core);+ if (!pitch) return { error: `bad pitch in "${token}"` };+ return {+ rest: false,+ pitch,+ step: pitch.step,+ duration,+ chord: chord || '',+ lyric: lyric || '',+ };+};++// Parse a full score string into { clef, key, keySig, time, tempo, measures,+// errors }. `measures` is an array of { notes, beats } where `beats` is the+// summed duration (handy for the renderer to flag incomplete bars, and for+// tests). Always returns a usable object — never throws.+export const parseScore = (text) => {+ const header = { ...DEFAULT_HEADER };+ const errors = [];+ const bodyLines = [];++ const lines = String(text || '').split(/\r?\n/);+ for (const rawLine of lines) {+ const line = rawLine.trim();+ if (!line) continue;+ // A header line is `key: value` and contains no `|` (music) and no note+ // tokens. We detect it by the leading `word:` shape before any `|`.+ const headerMatch = /^([A-Za-z]+)\s*:\s*(.+)$/.exec(line);+ if (headerMatch && !line.includes('|')) {+ const field = headerMatch[1].toLowerCase();+ const value = headerMatch[2].trim();+ if (field === 'clef') header.clef = /^bass$/i.test(value) ? 'bass' : 'treble';+ else if (field === 'key') header.key = value;+ else if (field === 'tempo') { const t = Number(value); if (Number.isFinite(t)) header.tempo = t; }+ else if (field === 'time') {+ const ts = parseTimeSignature(value);+ if (ts) { header.beats = ts.beats; header.beatValue = ts.beatValue; }+ else errors.push(`bad time signature "${value}"`);+ }+ continue;+ }+ bodyLines.push(line);+ }++ // Join the music body and split into measures on `|`. Empty segments (from a+ // leading/trailing/double `|`) are dropped.+ const body = bodyLines.join(' ');+ const segments = body.split('|').map((s) => s.trim()).filter(Boolean);+ const measures = segments.map((segment, mi) => {+ const notes = [];+ // A standalone `[chord]` token attaches to the NEXT note (the readable form+ // `[C] E4q`); the attached form `[C]E4q` also works. `pendingChord` carries a+ // bare bracket forward until a note consumes it.+ let pendingChord = '';+ for (const token of segment.split(/\s+/).filter(Boolean)) {+ const bare = /^\[([^\]]*)\]$/.exec(token);+ if (bare) { pendingChord = bare[1]; continue; }+ const parsed = parseToken(token);+ if (parsed.error) { errors.push(`measure ${mi + 1}: ${parsed.error}`); continue; }+ if (pendingChord && !parsed.chord) parsed.chord = pendingChord;+ pendingChord = '';+ notes.push(parsed);+ }+ const beats = notes.reduce((sum, n) => sum + (n.duration?.beats || 0), 0);+ return { notes, beats };+ });++ return {+ clef: header.clef,+ key: header.key,+ keySig: keySignature(header.key),+ time: { beats: header.beats, beatValue: header.beatValue },+ tempo: header.tempo,+ measures,+ errors,+ };+};++// True when the text contains at least one parseable note — lets the UI decide+// whether to show the staff or an empty-state hint without rendering first.+export const scoreHasMusic = (text) => parseScore(text).measures.some((m) => m.notes.length > 0);diff --git a/client/src/lib/scoreNotation.test.js b/client/src/lib/scoreNotation.test.jsnew file mode 100644index 0000000000..62b699534b--- /dev/null+++ b/client/src/lib/scoreNotation.test.js@@ -0,0 +1,184 @@+import { describe, it, expect } from 'vitest';+import {+ parseScore,+ parsePitch,+ diatonicStep,+ durationBeats,+ keySignature,+ scoreHasMusic,+ DURATIONS,+} from './scoreNotation.js';++describe('diatonicStep', () => {+ it('places C4 at step 0 and counts up by letter', () => {+ expect(diatonicStep('C', 4)).toBe(0);+ expect(diatonicStep('D', 4)).toBe(1);+ expect(diatonicStep('B', 4)).toBe(6);+ expect(diatonicStep('C', 5)).toBe(7);+ expect(diatonicStep('E', 4)).toBe(2); // treble bottom line+ });+ it('goes negative below middle C', () => {+ expect(diatonicStep('G', 2)).toBe(-10); // bass bottom line+ });+ it('returns null for garbage', () => {+ expect(diatonicStep('H', 4)).toBeNull();+ expect(diatonicStep('C', NaN)).toBeNull();+ });+});++describe('parsePitch', () => {+ it('parses letter, accidental and octave', () => {+ expect(parsePitch('F#4')).toEqual({ letter: 'F', accidental: '#', octave: 4, step: 3 });+ expect(parsePitch('Bb3')).toEqual({ letter: 'B', accidental: 'b', octave: 3, step: -1 });+ expect(parsePitch('c4')).toMatchObject({ letter: 'C', octave: 4 });+ });+ it('rejects non-pitches', () => {+ expect(parsePitch('r')).toBeNull();+ expect(parsePitch('X9')).toBeNull();+ expect(parsePitch('')).toBeNull();+ });+});++describe('durationBeats', () => {+ it('maps undotted codes to quarter-note beats', () => {+ expect(durationBeats('w')).toBe(4);+ expect(durationBeats('h')).toBe(2);+ expect(durationBeats('q')).toBe(1);+ expect(durationBeats('e')).toBe(0.5);+ });+ it('applies dots as the geometric series', () => {+ expect(durationBeats('q', 1)).toBe(1.5);+ expect(durationBeats('h', 1)).toBe(3);+ expect(durationBeats('q', 2)).toBe(1.75);+ });+ it('returns 0 for an unknown code', () => {+ expect(durationBeats('z')).toBe(0);+ });+ it('every DURATIONS entry is internally consistent', () => {+ for (const [code, d] of Object.entries(DURATIONS)) {+ expect(d.code).toBe(code);+ expect(typeof d.beats).toBe('number');+ expect(typeof d.filled).toBe('boolean');+ }+ });+});++describe('keySignature', () => {+ it('returns no accidentals for C', () => {+ expect(keySignature('C major')).toEqual({ type: 'none', count: 0, letters: [] });+ });+ it('reads sharp keys and orders them', () => {+ expect(keySignature('G')).toMatchObject({ type: 'sharp', count: 1, letters: ['F'] });+ expect(keySignature('D major')).toMatchObject({ type: 'sharp', count: 2, letters: ['F', 'C'] });+ });+ it('reads flat keys', () => {+ expect(keySignature('F')).toMatchObject({ type: 'flat', count: 1, letters: ['B'] });+ expect(keySignature('Eb minor')).toMatchObject({ type: 'flat', count: 3 });+ });+ it('falls back to C for unknown input', () => {+ expect(keySignature('nonsense')).toMatchObject({ type: 'none', count: 0 });+ });+});++describe('parseScore', () => {+ it('reads headers with sensible defaults', () => {+ const s = parseScore('clef: treble\nkey: C\ntime: 4/4\ntempo: 68\n\n| C4q |');+ expect(s.clef).toBe('treble');+ expect(s.time).toEqual({ beats: 4, beatValue: 4 });+ expect(s.tempo).toBe(68);+ expect(s.keySig.count).toBe(0);+ });++ it('defaults headers when absent', () => {+ const s = parseScore('| C4q |');+ expect(s.clef).toBe('treble');+ expect(s.time).toEqual({ beats: 4, beatValue: 4 });+ expect(s.tempo).toBeNull();+ });++ it('parses notes with chord and lyric', () => {+ const s = parseScore('| [C] E4q(If) G4q(you) |');+ expect(s.measures).toHaveLength(1);+ const [a, b] = s.measures[0].notes;+ expect(a).toMatchObject({ rest: false, chord: 'C', lyric: 'If', step: 2 });+ expect(a.duration).toMatchObject({ code: 'q', beats: 1, dots: 0 });+ expect(b).toMatchObject({ chord: '', lyric: 'you', step: 4 });+ });++ it('carries the renderer-facing duration props (filled / stem / flags)', () => {+ const s = parseScore('| C4q C4h C4w C4e |');+ const [q, h, w, e] = s.measures[0].notes.map((n) => n.duration);+ expect(q).toMatchObject({ filled: true, stem: true, flags: 0 }); // solid head + stem+ expect(h).toMatchObject({ filled: false, stem: true, flags: 0 }); // open head + stem+ expect(w).toMatchObject({ filled: false, stem: false, flags: 0 }); // open head, no stem+ expect(e).toMatchObject({ filled: true, stem: true, flags: 1 }); // one flag+ });++ it('parses rests (no pitch / lyric)', () => {+ const s = parseScore('| C4q rq rh |');+ const notes = s.measures[0].notes;+ expect(notes[1]).toMatchObject({ rest: true });+ expect(notes[1].duration).toMatchObject({ code: 'q', beats: 1 });+ expect(notes[2].duration.beats).toBe(2);+ });++ it('parses dotted and accidental notes', () => {+ const s = parseScore('| F#4q. Bb3e |');+ const [a, b] = s.measures[0].notes;+ expect(a.pitch.accidental).toBe('#');+ expect(a.duration.beats).toBe(1.5);+ expect(b.pitch).toMatchObject({ letter: 'B', accidental: 'b', octave: 3 });+ });++ it('splits multiple measures and sums beats', () => {+ const s = parseScore('| C4h C4h | C4w |');+ expect(s.measures).toHaveLength(2);+ expect(s.measures[0].beats).toBe(4);+ expect(s.measures[1].beats).toBe(4);+ });++ it('collects errors for bad tokens but keeps the good ones', () => {+ const s = parseScore('| C4q zzz G4q |');+ expect(s.measures[0].notes).toHaveLength(2);+ expect(s.errors.length).toBe(1);+ expect(s.errors[0]).toMatch(/measure 1/);+ });++ it('flags a bad time signature', () => {+ const s = parseScore('time: 4/x\n| C4q |');+ expect(s.errors.some((e) => /time signature/.test(e))).toBe(true);+ });++ it('handles a bass clef header', () => {+ const s = parseScore('clef: bass\n| C3q |');+ expect(s.clef).toBe('bass');+ });++ it('never throws on empty / garbage input', () => {+ expect(parseScore('').measures).toEqual([]);+ expect(parseScore(null).measures).toEqual([]);+ expect(parseScore('just some prose').measures.every((m) => m.notes.length === 0)).toBe(true);+ });++ it('parses the shipped 500 Miles verse into four 4-beat bars', () => {+ const score = [+ 'clef: treble', 'key: C', 'time: 4/4', 'tempo: 68', '',+ "| [C] E4q(If) G4q(you) G4q(miss) G4q(the) | [Am] A4h(train) G4q(I'm) E4q(on) |",+ '| [F] F4q(You) A4q(will) A4q(know) A4q(that) | [C] G4h(I) E4q(am) C4q(gone) |',+ '| [F] F4q(You) A4q(can) A4q(hear) A4q(the) | [C] G4q(whis-) E4q(tle) C4h(blow) |',+ '| [G] D4q(A) F4q(hun-) G4q(dred) rq | [C] C4w(miles) |',+ ].join('\n');+ const s = parseScore(score);+ expect(s.errors).toEqual([]);+ expect(s.measures).toHaveLength(8);+ for (const m of s.measures) expect(m.beats).toBeCloseTo(4, 5);+ });+});++describe('scoreHasMusic', () => {+ it('is true only when at least one note parses', () => {+ expect(scoreHasMusic('| C4q |')).toBe(true);+ expect(scoreHasMusic('clef: treble\n\n')).toBe(false);+ expect(scoreHasMusic('')).toBe(false);+ });+});diff --git a/client/src/pages/SongEditor.jsx b/client/src/pages/SongEditor.jsxindex b1527d95ed..bddd9e07e3 100644--- a/client/src/pages/SongEditor.jsx+++ b/client/src/pages/SongEditor.jsx@@ -35,6 +35,9 @@ import { RHYTHM_SHAPES, VOICE_LAYERS, rhythmShapeLabel } from '../lib/songCraft'import Pill from '../components/ui/Pill';import SongAiPanel from '../components/songs/SongAiPanel';import SongRecordings from '../components/songs/SongRecordings';+import SongScoreEditor from '../components/songs/SongScoreEditor';+import ScoreSheet from '../components/songs/ScoreSheet';+import { scoreHasMusic } from '../lib/scoreNotation';// Extract a TikTok video id from a share/watch URL so we can render TikTok's// documented iframe Embed Player (https://www.tiktok.com/player/v1/<id>)@@ -120,7 +123,7 @@ export default function SongEditor() {const patch = {title: song.title, artist: song.artist, key: song.key,tempo: song.tempo ?? null, rhythmShapeId: song.rhythmShapeId,- notation: song.notation, notes: song.notes, learned: song.learned,+ notation: song.notation, score: song.score, notes: song.notes, learned: song.learned,// Strip in-session temp ids so the server assigns stable uuids — keeps// them from being persisted and later colliding after a reload.sections: (song.sections || []).map(stripTempId),@@ -526,10 +529,13 @@ export default function SongEditor() {)}</section>+ {/* Sheet music — live-rendered staff from the lead-sheet notation. */}+ <SongScoreEditor value={song.score} onChange={(v) => setField('score', v)} />+{/* Notation + notes */}<section className="grid grid-cols-1 gap-4"><div>- <label htmlFor="notation" className={labelCls}>Notation / chords</label>+ <label htmlFor="notation" className={labelCls}>Notation / chords (free text)</label><textareaid="notation"value={song.notation}@@ -569,6 +575,10 @@ function ReadView({ song, setField, onRefreshTemplate, refreshing }) {const references = song.references || [];const hasText = (v) => typeof v === 'string' && v.trim().length > 0;const feel = song.rhythmShapeId ? rhythmShapeLabel(song.rhythmShapeId) : '';+ // Gate the whole sheet-music section on whether the score has notes. Memoized+ // so a recording-driven re-render doesn't re-parse the score each time+ // (ScoreSheet parses it again internally only when it actually renders).+ const hasScore = useMemo(() => scoreHasMusic(song.score), [song.score]);// Label + value badge, two-toned, built on the shared Pill primitive.const metaBadge = (label, value) => (@@ -592,6 +602,16 @@ function ReadView({ song, setField, onRefreshTemplate, refreshing }) {</Pill></div>+ {/* Sheet music — the rendered staff, full-width so a row of bars fits. */}+ {hasScore && (+ <section className="space-y-2">+ <h2 className="text-sm font-semibold text-white">Sheet music</h2>+ <div className="bg-port-card border border-port-border rounded-lg p-4 overflow-x-auto">+ <ScoreSheet text={song.score} />+ </div>+ </section>+ )}+<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">{/* Lyrics — the main reading surface, given the most width. */}<section className="lg:col-span-2 space-y-3">diff --git a/scripts/migrations/073-seed-500-miles-score.js b/scripts/migrations/073-seed-500-miles-score.jsnew file mode 100644index 0000000000..c8aeae6b98--- /dev/null+++ b/scripts/migrations/073-seed-500-miles-score.js@@ -0,0 +1,78 @@+/**+ * Backfill the sheet-music `score` field on the built-in "500 Miles" song for+ * installs that seeded it before the Sheet music feature existed.+ *+ * Background:+ * `server/services/songs.js#SEED_SONGS` now ships a `score` (the verse melody+ * in the PortOS lead-sheet DSL), but that only reaches installs on their FIRST+ * read of songs (when the file is seeded). An install that already persisted+ * `data/songs.json` keeps its old `seed-500-miles` record, which has no score.+ * This migration adds the shipped score to that record IF it has none — a+ * user who already wrote their own score is never clobbered. The user can also+ * pull the latest bundled content any time via the song's "Refresh from+ * template" button (refreshSongFromTemplate), which carries the score too.+ *+ * Fresh installs need nothing here: SEED_SONGS already includes the score, so+ * a missing file is a clean no-op. Re-runs detect the score is present and skip.+ */++import { readFile, writeFile, stat } from 'fs/promises';+import { join } from 'path';++const SONG_ID = 'seed-500-miles';++// The shipped verse melody — kept identical to SEED_SONGS[seed-500-miles].score+// in server/services/songs.js (the migration test asserts they match, so a drift+// fails CI rather than silently shipping two different scores).+export const SCORE_500_MILES = [+ 'clef: treble',+ 'key: C',+ 'time: 4/4',+ 'tempo: 68',+ '',+ '| [C] E4q(If) G4q(you) G4q(miss) G4q(the) | [Am] A4h(train) G4q(I\'m) E4q(on) |',+ '| [F] F4q(You) A4q(will) A4q(know) A4q(that) | [C] G4h(I) E4q(am) C4q(gone) |',+ '| [F] F4q(You) A4q(can) A4q(hear) A4q(the) | [C] G4q(whis-) E4q(tle) C4h(blow) |',+ '| [G] D4q(A) F4q(hun-) G4q(dred) rq | [C] C4w(miles) |',+].join('\n');++const fileExists = (path) => stat(path).then(() => true, (err) => {+ if (err.code === 'ENOENT') return false;+ throw err;+});++export default {+ async up({ rootDir }) {+ const path = join(rootDir, 'data', 'songs.json');+ if (!(await fileExists(path))) {+ console.log('📦 migration 073: no data/songs.json — fresh install seeds the score directly.');+ return { updated: 0, reason: 'no-file' };+ }++ const raw = await readFile(path, 'utf-8');+ let doc;+ try { doc = JSON.parse(raw); } catch (err) {+ console.warn(`⚠️ migration 073: data/songs.json is unparseable (${err.message}); skipping.`);+ return { updated: 0, reason: 'unreadable' };+ }+ if (!doc || !Array.isArray(doc.songs)) {+ return { updated: 0, reason: 'unexpected-shape' };+ }++ const song = doc.songs.find((s) => s && s.id === SONG_ID);+ if (!song) {+ console.log('📦 migration 073: built-in 500 Miles not present; nothing to backfill.');+ return { updated: 0, reason: 'song-absent' };+ }+ if (typeof song.score === 'string' && song.score.trim()) {+ console.log('📦 migration 073: 500 Miles already has a score; leaving it untouched.');+ return { updated: 0, reason: 'already-applied' };+ }++ song.score = SCORE_500_MILES;+ song.updatedAt = new Date().toISOString();+ await writeFile(path, JSON.stringify(doc, null, 2) + '\n');+ console.log('📦 migration 073: seeded sheet-music score onto built-in 500 Miles.');+ return { updated: 1 };+ },+};diff --git a/scripts/migrations/073-seed-500-miles-score.test.js b/scripts/migrations/073-seed-500-miles-score.test.jsnew file mode 100644index 0000000000..a8d30d2952--- /dev/null+++ b/scripts/migrations/073-seed-500-miles-score.test.js@@ -0,0 +1,81 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration, { SCORE_500_MILES } from './073-seed-500-miles-score.js';+import { SEED_SONGS } from '../../server/services/songs.js';++const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));+const findSong = (path, id) => readJson(path).songs.find((s) => s.id === id);++describe('migration 073 — backfill 500 Miles sheet-music score', () => {+ let rootDir;+ let songsPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-073-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ songsPath = join(rootDir, 'data', 'songs.json');+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('does not drift from the shipped seed score', () => {+ const seed = SEED_SONGS.find((s) => s.id === 'seed-500-miles');+ expect(seed.score).toBe(SCORE_500_MILES);+ });++ it('no-ops when data/songs.json is missing (fresh install seeds it directly)', async () => {+ const result = await migration.up({ rootDir });+ expect(result).toEqual({ updated: 0, reason: 'no-file' });+ expect(existsSync(songsPath)).toBe(false);+ });++ it('seeds the score onto a 500 Miles record that lacks one', async () => {+ writeJson(songsPath, {+ songs: [{ id: 'seed-500-miles', title: '500 Miles', updatedAt: '2026-01-01T00:00:00.000Z' }],+ });+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(1);+ const song = findSong(songsPath, 'seed-500-miles');+ expect(song.score).toBe(SCORE_500_MILES);+ expect(song.updatedAt).not.toBe('2026-01-01T00:00:00.000Z'); // bumped+ });++ it('treats an empty-string score as missing and fills it', async () => {+ writeJson(songsPath, { songs: [{ id: 'seed-500-miles', score: ' ' }] });+ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(1);+ expect(findSong(songsPath, 'seed-500-miles').score).toBe(SCORE_500_MILES);+ });++ it('never clobbers a user-authored score', async () => {+ writeJson(songsPath, { songs: [{ id: 'seed-500-miles', score: '| C4w(mine) |' }] });+ const result = await migration.up({ rootDir });+ expect(result).toEqual({ updated: 0, reason: 'already-applied' });+ expect(findSong(songsPath, 'seed-500-miles').score).toBe('| C4w(mine) |');+ });++ it('is idempotent across re-runs', async () => {+ writeJson(songsPath, { songs: [{ id: 'seed-500-miles' }] });+ await migration.up({ rootDir });+ const second = await migration.up({ rootDir });+ expect(second.reason).toBe('already-applied');+ });++ it('no-ops when 500 Miles is absent (user deleted it)', async () => {+ writeJson(songsPath, { songs: [{ id: 'song-custom', score: '' }] });+ const result = await migration.up({ rootDir });+ expect(result).toEqual({ updated: 0, reason: 'song-absent' });+ });++ it('skips an unparseable songs.json instead of throwing', async () => {+ writeFileSync(songsPath, '{ not json');+ const result = await migration.up({ rootDir });+ expect(result).toEqual({ updated: 0, reason: 'unreadable' });+ });+});diff --git a/server/routes/songs.js b/server/routes/songs.jsindex 9ae90358eb..dee1fd2164 100644--- a/server/routes/songs.js+++ b/server/routes/songs.js@@ -74,6 +74,9 @@ const songInputSchema = z.object({tempo: z.number().int().min(svc.TEMPO_MIN).max(svc.TEMPO_MAX).nullable().optional(),rhythmShapeId: str(svc.ID_MAX_LENGTH).optional(),notation: str(svc.FIELD_MAX_LENGTH).optional(),+ // Sheet-music notation (PortOS lead-sheet DSL) — bounded free text; the client+ // parses/renders it. Longer cap than `notation` since a full score is verbose.+ score: str(svc.SCORE_MAX_LENGTH).optional(),notes: str(svc.FIELD_MAX_LENGTH).optional(),learned: z.boolean().optional(),sections: z.array(sectionSchema).max(svc.SECTIONS_MAX).optional(),diff --git a/server/services/songs.js b/server/services/songs.jsindex 64ae2f2a3b..288af7f438 100644--- a/server/services/songs.js+++ b/server/services/songs.js@@ -37,6 +37,7 @@ export const TITLE_MAX_LENGTH = 200;export const ARTIST_MAX_LENGTH = 200;export const KEY_MAX_LENGTH = 24;export const FIELD_MAX_LENGTH = 4000; // lyrics body / general notes+export const SCORE_MAX_LENGTH = 8000; // sheet-music notation (lead-sheet DSL)export const LABEL_MAX_LENGTH = 120; // section + layer labelsexport const PART_MAX_LENGTH = 60; // layer voice (e.g. "Bass")export const ID_MAX_LENGTH = 60; // rhythm-shape / layer ids@@ -155,6 +156,10 @@ export const sanitizeSong = (raw) => {tempo: sanitizeTempo(raw.tempo),rhythmShapeId: trimField(raw.rhythmShapeId, ID_MAX_LENGTH),notation: trimField(raw.notation, FIELD_MAX_LENGTH),+ // Sheet-music notation in the PortOS lead-sheet DSL (client/src/lib/+ // scoreNotation.js). A bounded free-text string — the client parses + renders+ // it; the server only length-caps it, so a newer/older DSL revision can't 400.+ score: trimField(raw.score, SCORE_MAX_LENGTH),notes: trimField(raw.notes, FIELD_MAX_LENGTH),learned: raw.learned === true,sections: sanitizeList(raw.sections, sanitizeSection, SECTIONS_MAX),@@ -182,6 +187,20 @@ export const SEED_SONGS = [tempo: 68,rhythmShapeId: 'slow-4-4',notation: 'Verse chords (key of C): C — Am — F — G, four slow bars per line. A gentle 4/4 ballad; let each line breathe across the bar rather than chopping it.',+ // Sheet music in the PortOS lead-sheet DSL — the verse melody with chords and+ // lyrics. A singable arrangement in C (edit it in the Sheet music tab); see+ // client/src/lib/scoreNotation.js for the format.+ score: [+ 'clef: treble',+ 'key: C',+ 'time: 4/4',+ 'tempo: 68',+ '',+ '| [C] E4q(If) G4q(you) G4q(miss) G4q(the) | [Am] A4h(train) G4q(I\'m) E4q(on) |',+ '| [F] F4q(You) A4q(will) A4q(know) A4q(that) | [C] G4h(I) E4q(am) C4q(gone) |',+ '| [F] F4q(You) A4q(can) A4q(hear) A4q(the) | [C] G4q(whis-) E4q(tle) C4h(blow) |',+ '| [G] D4q(A) F4q(hun-) G4q(dred) rq | [C] C4w(miles) |',+ ].join('\n'),notes: 'A travelling lament — keep it spacious and mournful. Sustain the vowels on the downbeats. Works beautifully with a soft hummed drone under the verses.',learned: false,sections: [@@ -281,7 +300,7 @@ export async function updateSong(id, patch) {// Merge field-by-field so an absent key preserves the stored value while a// present key (including empty string / empty array) applies the change.const merged = { ...songs[idx] };- for (const key of ['title', 'artist', 'key', 'tempo', 'rhythmShapeId', 'notation', 'notes', 'learned', 'sections', 'layers', 'recordings', 'references']) {+ for (const key of ['title', 'artist', 'key', 'tempo', 'rhythmShapeId', 'notation', 'score', 'notes', 'learned', 'sections', 'layers', 'recordings', 'references']) {if (key in patch) merged[key] = patch[key];}merged.id = id;diff --git a/server/services/songs.test.js b/server/services/songs.test.jsindex dfce1d2de5..8ae91902fb 100644--- a/server/services/songs.test.js+++ b/server/services/songs.test.js@@ -173,6 +173,20 @@ describe('songs service', () => {expect(seed.references.every((r) => r.url.includes('tiktok.com'))).toBe(true);});+ it('ships a sheet-music score on the 500 Miles default', async () => {+ const songs = await svc.listSongs();+ const seed = songs.find((s) => s.title === '500 Miles');+ expect(seed.score).toContain('clef: treble');+ expect(seed.score).toContain('(train)');+ });++ it('sanitizes the score field — trims and caps to SCORE_MAX_LENGTH', () => {+ expect(svc.sanitizeSong({ id: 'x', score: ' | C4q | ' }).score).toBe('| C4q |');+ expect(svc.sanitizeSong({ id: 'x', score: 123 }).score).toBe(''); // non-string → ''+ const long = 'C'.repeat(svc.SCORE_MAX_LENGTH + 50);+ expect(svc.sanitizeSong({ id: 'x', score: long }).score.length).toBe(svc.SCORE_MAX_LENGTH);+ });+it('sanitizes references — drops urlless entries, mints ids', () => {const song = svc.sanitizeSong({id: 'x',@@ -194,17 +208,20 @@ describe('songs service', () => {const edited = await svc.updateSong(seedId, {title: 'My edited title',sections: [{ label: 'Custom', lyrics: 'changed' }],+ score: '', // user cleared the sheet musiclearned: true,recordings: [{ filename: 'my-take.wav', durationMs: 1000 }],references: [{ url: 'https://example.com/mine' }],});expect(edited.title).toBe('My edited title');+ expect(edited.score).toBe('');const refreshed = await svc.refreshSongFromTemplate(seedId);// Shipped content restored…expect(refreshed.title).toBe('500 Miles');expect(refreshed.references.every((r) => r.url.includes('tiktok.com'))).toBe(true);expect(refreshed.sections.some((s) => s.lyrics.includes('miss the train'))).toBe(true);+ expect(refreshed.score).toContain('clef: treble'); // sheet music restored too// …user-owned state preserved.expect(refreshed.learned).toBe(true);expect(refreshed.recordings).toHaveLength(1);