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
add chordShapes lib: chord name → guitar/ukulele/piano voicings
[._.]/ Adam Eivy71c3b47e6065
diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 272560e8d6..a4f42a7b62 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -108,6 +108,7 @@ grep -i "what you want to do" client/src/lib/README.md|---|---|| `audioContext.js` | `getAudioContext()` — the ONE app-wide lazy Web Audio `AudioContext` singleton every playback feature shares (`songPlayback`, `scorePlayback`, `metronome`, `midiPlayback`). Browsers cap live contexts and one context = one sample clock, so simultaneous features stay aligned. Constructor resolved lazily (`window` → `globalThis`) so node-env test runs import cleanly; tests inject a fake via `vi.stubGlobal('AudioContext', …)` before first call. || `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. |+| `chordShapes.js` | Chord-name → per-instrument voicing derivation for the SongBook viewer's instrument-view toggle (#2656). `getChordVoicing(name, instrument)` → guitar `{ frets: [6 × (-1/0/n)], baseFret, bass }`, ukulele (4-string GCEA, exact lowest-position search), or piano `{ notes: ['A','C','E'], bass }` with letter-accurate degree spelling (the 3rd of E is G#, never Ab); guitar shapes come from a curated first-position table + movable E-/A-form barre templates offset by `baseFret` (aug/dim7 exploit shape symmetry). Slash chords voice the base chord and carry `bass` separately. `parseChordName(name)`, `splitJoinedChords('Am-Am7')`, `toVoicingInstrument(songInstrument)`, `VOICING_INSTRUMENTS`. Reuses `tabNotation.js`'s `CHORD_TOKEN_RE`/`NOTE_TO_PC`/`spellPitchClass` (exported from there for this module) instead of duplicating the tables. Unknown/unparseable chords → null, never throws. || `canvasRoll.js` | Shared canvas helpers for the two piano-roll renderers (`<PianoRoll>` falling-note + `<MidiPianoRoll>` DAW-style, #2477). `layerColor(index)` — the per-layer/track palette (8 hues, wraps both directions) used by note bars, keyboards, and legends; `roundRect(ctx, x, y, w, h, r)` — rounded-rect path with `ctx.roundRect` feature-detect and arcTo fallback; `rollPalette()` — resolves the theme-following `{ bg, accent, accentRgb }` from `--port-accent` via `getComputedStyle` (canvas can't read CSS vars); `ROLL_BG` — the shared near-black bg literal. Pure canvas math/palette, no React. || `colorMatch.js` | Pure grading core for the song system's color-match training mode: `buildColorMatchTimeline(score, { bpm })` → `{ notes, totalMs, msPerQuarter, bpm }` (each note's target frequency + onset/offset window in ms, keyed by the same global note index the renderer flattens, timing mirroring `scorePlayback`); `gradeNote(hz, targetHz)` classifies a sung pitch against a target into `in-tune`/`close`/`off`/`missed` (octave-folded, thresholds `MATCH_IN_TUNE_CENTS`/`MATCH_CLOSE_CENTS`); `noteAtTime(timeline, tMs, fromIdx)` finds the active note for a rAF cursor; `summarizeAccuracy(grades)` → `{ graded, counts, percentInTune, perNote }` per-take summary (`perNote` is the ordered grade list a saved take persists, mirroring the server sanitizer); `gradesFromPerNote(timeline, perNote)` is its inverse — rebuilds the noteIndex→grade map to repaint a saved take's grading on open without re-grading audio; plus `centsBetween` and the `GRADE` enum. No React, no audio — the `useColorMatch` hook drives it. || `pitchDetect.js` | Dependency-free vocal pitch-detection core for the song system (tuner / color-match / sing-to-score). `detectFrequency(frame, { sampleRate })` → `{ hz, clarity }` (McLeod NSDF; clarity gate rejects silence/noise); `frequencyToNote(hz, { a4 })` → `{ letter, accidental, octave, step, cents }` (cents ∈ [-50,+50], sharp positive; `step` reuses `scoreNotation`'s `diatonicStep` so detected notes align with the renderer); `noteToFrequency(note, { a4 })` inverse (color-match targets); `createPitchTracker(analyser, { onUpdate })` → `{ stop }` rAF/interval loop with median+EMA smoothing to kill octave jumps; `tuningQuality(cents)` → `{ level, label }` buckets a cents deviation into `in-tune`/`close`/`off`/`none` (thresholds `IN_TUNE_CENTS`/`CLOSE_CENTS`) for the tuner color readout. |@@ -131,7 +132,7 @@ grep -i "what you want to do" client/src/lib/README.md| `tribeCadence.js` | Mirror of `server/lib/tribeCadence.js` — the single authoritative Tribe care-cadence rules shared by the page, the Care dashboard widget, and the proactive alert: `cadenceStatus(entity)` → `{ state, daysRemaining, daysOverdue }`, `daysSinceDate(dateStr)`, `DEFAULT_CADENCE_DAYS`, `SOON_WINDOW_DAYS`. A cross-boundary contract test asserts it never drifts from the server copy. || `streakGlyph.js` | `streakGlyph(streak)` — the single POST streak emoji (✨ / ⚡ / 🔥 by day count) shared by the POST launcher, Morse trainer, daily widget, and dashboard streak widget. || `syncCounts.js` | Directional pending-sync counts for the Instances federation cards. `directionalCounts({ localMax, peerMax, ourCursor, peerCursorForUs })` → `{ toPull, toPush }` (each a non-negative Number, or `null` when unknown) from monotonic change-log seqs; `diffSeq(ahead, behind)` is the BigInt-safe clamp-at-zero subtraction (handles numeric strings past `MAX_SAFE_INTEGER`); `describeDirectional({ toPull, toPush })` renders the plain-language `{ state, text }` ("in sync" / "N to pull · M to push" / "checking…"). No React — `SyncStatusBadge` drives it. |-| `tabNotation.js` | Guitar-tab / chord-sheet / ChordPro text parser for SongBook (`/songbook`). `parseTabSheet(text)` → `{ lines, meta, errors }` classifying each line (`section`/`chords`/`lyric`/`tabstaff`/`chordlyric`/`blank`/`text`) with chord names + column offsets, plus ChordPro meta (`{title:}`/`{artist:}`/`{key:}`/`{capo:}`); `detectFormat(text)` → `'chordpro' \| 'tab' \| 'plain'`; `normalizePastedTab(text)` cleans HTML remnants/entities, CRLF, tabs→spaces, blank-line runs; `transposeChordName(name, n)` / `transposeText(text, n)` transpose chord symbols (slash chords, sensible sharp/flat spelling, column-preserving on chord lines); `CHORD_TOKEN_RE` exported for reuse. Forgiving — never throws, unknown lines classify as `text`. NOT the lead-sheet parser (`scoreNotation.js`). |+| `tabNotation.js` | Guitar-tab / chord-sheet / ChordPro text parser for SongBook (`/songbook`). `parseTabSheet(text)` → `{ lines, meta, errors }` classifying each line (`section`/`chords`/`lyric`/`tabstaff`/`chordlyric`/`blank`/`text`) with chord names + column offsets, plus ChordPro meta (`{title:}`/`{artist:}`/`{key:}`/`{capo:}`); `detectFormat(text)` → `'chordpro' \| 'tab' \| 'plain'`; `normalizePastedTab(text)` cleans HTML remnants/entities, CRLF, tabs→spaces, blank-line runs; `transposeChordName(name, n)` / `transposeText(text, n)` transpose chord symbols (slash chords, sensible sharp/flat spelling, column-preserving on chord lines); `CHORD_TOKEN_RE` exported for reuse, plus `NOTE_TO_PC` / `spellPitchClass` exported minimally so `chordShapes.js` derives voicings from the same pitch-class tables. Forgiving — never throws, unknown lines classify as `text`. NOT the lead-sheet parser (`scoreNotation.js`). || `terminalTheme.js` | Pure xterm.js palette builder for the Shell terminal. `buildTerminalTheme({ bg, fg, accent, card, error, success, warning }, mode)` assembles the xterm `theme` object — base ANSI colors from the active theme's CSS vars, the rest from mode-tuned literals (`ANSI_NIGHT` bright/pastel for dark backgrounds, `ANSI_DAY` darkened/saturated so colored CLI output stays legible on daytime themes). `parseCssColorToHex(raw, fallback)` normalizes both the `15 15 15` triple form and the `rgb(7 7 7 / 0.86)` function form (used by `--port-terminal-*` tokens) to `#rrggbb`, dropping alpha. No DOM reads — `Shell.jsx` resolves CSS vars and re-applies on theme switch. || `universeBuilderShared.js` | Shared constants + pure category/trunk/composite helpers for the Universe Builder page and its extracted tab/editor components (#2374): `TRUNK_TABS`/`TRUNK_BY_ID`/`TRUNK_BY_KIND`, `TAB_*` + `BUCKET_CANON`, `CATEGORY_LABELS`, `DEFAULT_RENDER_OPTS`, `COMPOSITE_BOARD_KINDS`; and helpers `groupBucketsByKind`, `normalizeCategoryKey`, `humanizeCategory`, `ensureDraftCategories`, `getCategoryKeys`, `compositeKindLabel`. No React state — safe to import from the page or any tab component without a cycle. || `universeBuilderCounts.js` | Pure prompt-count helpers for the Universe Builder render buttons (#2374), mirroring the server's compile/skip rules so inline counts match what `/render` will enqueue: `totalVariationCount`, `canonEntryHasContent`, `countCanonWithContent`, `renderPromptCount`, `scopedPromptCount`. The server `compilePrompts`/`synthesizeCanonPrompt` copy is authoritative — keep in sync. |diff --git a/client/src/lib/chordShapes.js b/client/src/lib/chordShapes.jsnew file mode 100644index 0000000000..18130efe7f--- /dev/null+++ b/client/src/lib/chordShapes.js@@ -0,0 +1,306 @@+// Chord-name → per-instrument voicing derivation for the SongBook viewer's+// instrument-view toggle (guitar / ukulele / piano). Pure and dependency-free+// (no React, no browser APIs — these tests also run in node env in CI).+//+// Reuses tabNotation.js's chord-token grammar (CHORD_TOKEN_RE) and pitch-class+// tables (NOTE_TO_PC / spellPitchClass) rather than duplicating them.+//+// API:+// parseChordName(name) → { root, rootPc, quality, bass, bassPc } | null+// getChordVoicing(name, instrument)→ instrument-shaped voicing | null+// 'guitar' → { instrument, frets: [6 × (-1 muted | 0 open | n)], baseFret, bass }+// 'ukulele' → { instrument, frets: [4 × …], baseFret, bass }+// 'piano' → { instrument, notes: ['A','C','E'], bass }+// splitJoinedChords(name) → dash-joined "Am-Am7" → ['Am', 'Am7']+// toVoicingInstrument(instrument) → song instrument → diagram instrument+// VOICING_INSTRUMENTS → ['guitar', 'ukulele', 'piano']+//+// Fret arrays run low string → high string (guitar EADGBE, ukulele GCEA).+// When baseFret > 1 the positive fret values are relative to the diagram+// window (1 = baseFret); at baseFret 1 they are absolute. Forgiving — unknown+// or unparseable chords return null, never throw.++import { CHORD_TOKEN_RE, NOTE_TO_PC, spellPitchClass } from './tabNotation.js';++export const VOICING_INSTRUMENTS = ['guitar', 'ukulele', 'piano'];++// Map a song record's `instrument` to the diagram instrument the viewer should+// default to: guitar/ukulele/piano pass through, everything else (bass, voice,+// other, unset) renders guitar shapes.+export const toVoicingInstrument = (instrument) =>+ (VOICING_INSTRUMENTS.includes(instrument) ? instrument : 'guitar');++// ---------------------------------------------------------------------------+// Chord-name parsing+// ---------------------------------------------------------------------------++// Written quality suffix → canonical quality key. Deliberately curated to the+// common set — anything else (11, maj9, alt, …) degrades to null upstream.+const QUALITY_ALIASES = {+ '': 'major', maj: 'major', M: 'major',+ m: 'minor', min: 'minor',+ 7: '7', m7: 'm7', min7: 'm7',+ maj7: 'maj7', M7: 'maj7',+ m7b5: 'm7b5', 'ø': 'm7b5', 'ø7': 'm7b5', 'm7(b5)': 'm7b5',+ dim: 'dim', '°': 'dim',+ dim7: 'dim7', '°7': 'dim7', o7: 'dim7',+ aug: 'aug', '+': 'aug',+ sus2: 'sus2',+ sus4: 'sus4', sus: 'sus4',+ add9: 'add9', '(add9)': 'add9',+ 6: '6', m6: 'm6', min6: 'm6',+ 9: '9',+};++// Canonical quality → chord tones as [degree, semitones-above-root] pairs.+// The degree drives letter-accurate piano spelling (the 3rd of E is G#, never+// Ab); the semitones drive the fretted-instrument solvers.+const QUALITY_DEGREES = {+ major: [[1, 0], [3, 4], [5, 7]],+ minor: [[1, 0], [3, 3], [5, 7]],+ 7: [[1, 0], [3, 4], [5, 7], [7, 10]],+ m7: [[1, 0], [3, 3], [5, 7], [7, 10]],+ maj7: [[1, 0], [3, 4], [5, 7], [7, 11]],+ m7b5: [[1, 0], [3, 3], [5, 6], [7, 10]],+ dim: [[1, 0], [3, 3], [5, 6]],+ dim7: [[1, 0], [3, 3], [5, 6], [7, 9]],+ aug: [[1, 0], [3, 4], [5, 8]],+ sus2: [[1, 0], [2, 2], [5, 7]],+ sus4: [[1, 0], [4, 5], [5, 7]],+ add9: [[1, 0], [3, 4], [5, 7], [9, 14]],+ 6: [[1, 0], [3, 4], [5, 7], [6, 9]],+ m6: [[1, 0], [3, 3], [5, 7], [6, 9]],+ 9: [[1, 0], [3, 4], [5, 7], [7, 10], [9, 14]],+};++// Same token gate tabNotation applies (length cap keeps the alternation-star+// from chewing on pasted garbage).+const isChordToken = (token) =>+ typeof token === 'string' && token.length > 0 && token.length <= 12 && CHORD_TOKEN_RE.test(token);++// Parse one chord symbol into { root, rootPc, quality, bass, bassPc }, or null+// when it isn't a chord token or uses a quality outside the curated set.+// "N.C." parses as a token but has no voicing → null.+export const parseChordName = (name) => {+ const raw = String(name ?? '');+ if (!isChordToken(raw) || /^N\.?C\.?$/.test(raw)) return null;+ const m = /^([A-G])([#b]?)(.*)$/.exec(raw);+ if (!m) return null;+ let suffix = m[3];+ let bass = null;+ const slash = /^(.*)\/([A-G][#b]?)$/.exec(suffix);+ if (slash) {+ suffix = slash[1];+ bass = slash[2];+ }+ const quality = QUALITY_ALIASES[suffix];+ if (!quality) return null;+ return {+ root: m[1] + m[2],+ rootPc: NOTE_TO_PC[m[1] + m[2]],+ quality,+ bass,+ bassPc: bass ? NOTE_TO_PC[bass] : null,+ };+};++// Dash-joined chord runs ("Am-Am7", a quick change written as one token) are+// several voicings. Split when EVERY dash-separated segment is itself a chord+// token — mirroring tabNotation, where bare dash runs are rhythm filler and a+// hyphenated lyric word is not a chord. Anything else returns whole.+export const splitJoinedChords = (name) => {+ const raw = String(name ?? '');+ if (!raw.includes('-')) return [raw];+ const parts = raw.split('-');+ return parts.every((p) => isChordToken(p)) ? parts : [raw];+};++// ---------------------------------------------------------------------------+// Piano voicing — interval math with letter-accurate spelling+// ---------------------------------------------------------------------------++const LETTERS = ['C', 'D', 'E', 'F', 'G', 'A', 'B'];+const LETTER_PC = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };++// Spell the note `semis` above the root that serves scale degree `deg`: pick+// the letter `deg-1` letter-steps up, then the accidental that lands on the+// target pitch class. A would-be double accidental (Ebdim's Bbb) falls back to+// the simple enharmonic spelling honoring the root's accidental preference.+const spellDegree = (root, rootPc, deg, semis) => {+ const letter = LETTERS[(LETTERS.indexOf(root[0]) + deg - 1) % 7];+ const targetPc = (rootPc + semis) % 12;+ let diff = (targetPc - LETTER_PC[letter] + 12) % 12;+ if (diff > 6) diff -= 12;+ if (diff === 0) return letter;+ if (diff === 1) return `${letter}#`;+ if (diff === -1) return `${letter}b`;+ return spellPitchClass(targetPc, root[1] || '');+};++const pianoVoicing = (parsed) => ({+ instrument: 'piano',+ notes: QUALITY_DEGREES[parsed.quality].map(([deg, semis]) =>+ spellDegree(parsed.root, parsed.rootPc, deg, semis)),+ bass: parsed.bass,+});++// ---------------------------------------------------------------------------+// Guitar voicing — curated opens + movable E-form / A-form templates+// ---------------------------------------------------------------------------++// Movable shape templates: fret offsets from the ROOT fret per string (low E →+// high e), null = muted. At root fret 0 these ARE the open E-/A-root chords+// (E-form major at 0 = 022100, A-form m7 at 0 = x02010), so only non-E/A-root+// open classics need curating.+const E_FORM = {+ major: [0, 2, 2, 1, 0, 0],+ minor: [0, 2, 2, 0, 0, 0],+ 7: [0, 2, 0, 1, 0, 0],+ m7: [0, 2, 0, 0, 0, 0],+ maj7: [0, 2, 1, 1, 0, 0],+ sus4: [0, 2, 2, 2, 0, 0],+ add9: [0, 2, 2, 1, 0, 2],+ 6: [0, 2, 2, 1, 2, 0],+ 9: [0, 2, 0, 1, 0, 2],+ aug: [0, 3, 2, 1, 1, null],+};+const A_FORM = {+ major: [null, 0, 2, 2, 2, 0],+ minor: [null, 0, 2, 2, 1, 0],+ 7: [null, 0, 2, 0, 2, 0],+ m7: [null, 0, 2, 0, 1, 0],+ maj7: [null, 0, 2, 1, 2, 0],+ sus2: [null, 0, 2, 2, 0, 0],+ sus4: [null, 0, 2, 2, 3, 0],+ m7b5: [null, 0, 1, 0, 1, null],+ dim: [null, 0, 1, 2, 1, null],+ dim7: [null, 0, 1, 2, 1, 2],+ aug: null, // no comfortable A-form — E-form covers it+ add9: [null, 0, 2, 4, 2, 0],+ 6: [null, 0, 2, 2, 2, 2],+ m6: [null, 0, 2, 2, 1, 2],+ 9: [null, 0, -1, 0, 0, 0],+};+const GUITAR_FORMS = [+ { openPc: 4, shapes: E_FORM }, // root on string 6 (low E)+ { openPc: 9, shapes: A_FORM }, // root on string 5 (A)+];++// First-position classics that beat the barre-derived shape, keyed+// `${rootPc}:${quality}` (absolute frets, -1 muted).+const GUITAR_OPEN_SHAPES = {+ '0:major': [-1, 3, 2, 0, 1, 0], // C+ '0:maj7': [-1, 3, 2, 0, 0, 0],+ '0:7': [-1, 3, 2, 3, 1, 0],+ '0:add9': [-1, 3, 2, 0, 3, 0],+ '0:6': [-1, 3, 2, 2, 1, 0],+ '0:sus4': [-1, 3, 3, 0, 1, 1],+ '2:major': [-1, -1, 0, 2, 3, 2], // D+ '2:minor': [-1, -1, 0, 2, 3, 1],+ '2:7': [-1, -1, 0, 2, 1, 2],+ '2:m7': [-1, -1, 0, 2, 1, 1],+ '2:maj7': [-1, -1, 0, 2, 2, 2],+ '2:sus2': [-1, -1, 0, 2, 3, 0],+ '2:sus4': [-1, -1, 0, 2, 3, 3],+ '2:6': [-1, -1, 0, 2, 0, 2],+ '5:maj7': [-1, -1, 3, 2, 1, 0], // Fmaj7+ '7:major': [3, 2, 0, 0, 0, 3], // G+ '7:7': [3, 2, 0, 0, 0, 1],+ '7:maj7': [3, -1, 0, 0, 0, 2],+ '7:6': [3, 2, 0, 0, 0, 0],+ '11:7': [-1, 2, 1, 2, 0, 2], // B7+};++// Absolute frets → { frets, baseFret } diagram window: low shapes stay+// absolute at baseFret 1; higher shapes re-base so 1 = baseFret.+const toDiagramWindow = (absFrets) => {+ const fretted = absFrets.filter((f) => f > 0);+ const maxFret = fretted.length ? Math.max(...fretted) : 0;+ if (maxFret <= 4) return { frets: absFrets, baseFret: 1 };+ const baseFret = Math.min(...fretted);+ return { frets: absFrets.map((f) => (f > 0 ? f - baseFret + 1 : f)), baseFret };+};++// Symmetric chords repeat their shape every N frets (any inversion is the+// same pitch-class set), so the root fret can drop toward the nut.+const SHAPE_SYMMETRY = { aug: 4, dim7: 3 };++const guitarVoicing = (parsed) => {+ const open = GUITAR_OPEN_SHAPES[`${parsed.rootPc}:${parsed.quality}`];+ if (open) return { instrument: 'guitar', ...toDiagramWindow(open), bass: parsed.bass };+ let best = null;+ for (const { openPc, shapes } of GUITAR_FORMS) {+ const offsets = shapes[parsed.quality];+ if (!offsets) continue;+ let rootFret = (parsed.rootPc - openPc + 12) % 12;+ if (SHAPE_SYMMETRY[parsed.quality]) rootFret %= SHAPE_SYMMETRY[parsed.quality];+ const minOffset = Math.min(...offsets.filter((o) => o != null));+ if (rootFret + minOffset < 0) rootFret += 12;+ const frets = offsets.map((o) => (o == null ? -1 : rootFret + o));+ const maxFret = Math.max(...frets);+ if (!best || maxFret < best.maxFret) best = { frets, maxFret };+ }+ if (!best) return null;+ return { instrument: 'guitar', ...toDiagramWindow(best.frets), bass: parsed.bass };+};++// ---------------------------------------------------------------------------+// Ukulele voicing — small exact search over GCEA+// ---------------------------------------------------------------------------++const UKE_OPEN_PCS = [7, 0, 4, 9]; // G C E A (re-entrant high-G)++// Find the lowest playable 4-string fingering: every string sounds a chord+// tone, all required tones are covered (the perfect 5th is droppable when the+// chord has more tones than strings), fingers stay inside a 4-fret window+// (open strings always allowed). Scans windows bottom-up, so the first hits+// are the canonical first-position shapes (C=0003, Am=2000, G7=0212, …).+const solveUkulele = (parsed) => {+ const intervals = QUALITY_DEGREES[parsed.quality].map(([, semis]) => semis % 12);+ const allowed = new Set(intervals.map((s) => (parsed.rootPc + s) % 12));+ const requiredIntervals = intervals.length > UKE_OPEN_PCS.length+ ? intervals.filter((s) => s !== 7)+ : intervals;+ const required = [...new Set(requiredIntervals.map((s) => (parsed.rootPc + s) % 12))];+ if (required.length > UKE_OPEN_PCS.length) return null;++ for (let base = 0; base <= 9; base += 1) {+ const perString = UKE_OPEN_PCS.map((openPc) => {+ const options = base === 0 ? [0, 1, 2, 3] : [0, base, base + 1, base + 2, base + 3];+ return [...new Set(options)].filter((f) => allowed.has((openPc + f) % 12));+ });+ if (perString.some((opts) => opts.length === 0)) continue;+ let best = null;+ for (const f0 of perString[0]) for (const f1 of perString[1]) {+ for (const f2 of perString[2]) for (const f3 of perString[3]) {+ const frets = [f0, f1, f2, f3];+ const sounded = new Set(frets.map((f, i) => (UKE_OPEN_PCS[i] + f) % 12));+ if (!required.every((pc) => sounded.has(pc))) continue;+ const sum = f0 + f1 + f2 + f3;+ const max = Math.max(f0, f1, f2, f3);+ if (!best || max < best.max || (max === best.max && sum < best.sum)) {+ best = { frets, sum, max };+ }+ }+ }+ if (best) return { instrument: 'ukulele', ...toDiagramWindow(best.frets), bass: parsed.bass };+ }+ return null;+};++// ---------------------------------------------------------------------------+// Public voicing API+// ---------------------------------------------------------------------------++// Chord name + instrument → voicing (see module header for shapes). Slash+// chords voice the base chord and carry the bass note name in `bass` (piano+// prepends it; string instruments render it as a "/G bass" hint). Returns+// null for unknown/unparseable chords or unsupported instruments.+export const getChordVoicing = (name, instrument) => {+ const parsed = parseChordName(name);+ if (!parsed) return null;+ if (instrument === 'piano') return pianoVoicing(parsed);+ if (instrument === 'guitar') return guitarVoicing(parsed);+ if (instrument === 'ukulele') return solveUkulele(parsed);+ return null;+};diff --git a/client/src/lib/chordShapes.test.js b/client/src/lib/chordShapes.test.jsnew file mode 100644index 0000000000..0806380c1e--- /dev/null+++ b/client/src/lib/chordShapes.test.js@@ -0,0 +1,229 @@+// Node-env-safe (no browser APIs) — this suite also runs in the server CI job.+import { describe, it, expect } from 'vitest';+import {+ parseChordName,+ getChordVoicing,+ splitJoinedChords,+ toVoicingInstrument,+ VOICING_INSTRUMENTS,+} from './chordShapes.js';+import { transposeChordName, NOTE_TO_PC } from './tabNotation.js';++const QUALITIES = [+ 'major', 'minor', '7', 'm7', 'maj7', 'm7b5', 'dim', 'dim7', 'aug',+ 'sus2', 'sus4', 'add9', '6', 'm6', '9',+];+const QUALITY_SUFFIX = {+ major: '', minor: 'm', 7: '7', m7: 'm7', maj7: 'maj7', m7b5: 'm7b5',+ dim: 'dim', dim7: 'dim7', aug: 'aug', sus2: 'sus2', sus4: 'sus4',+ add9: 'add9', 6: '6', m6: 'm6', 9: '9',+};+const ROOTS = ['C', 'C#', 'Db', 'D', 'D#', 'Eb', 'E', 'F', 'F#', 'Gb', 'G', 'G#', 'Ab', 'A', 'A#', 'Bb', 'B'];++describe('parseChordName', () => {+ it('parses root, quality, and slash bass', () => {+ expect(parseChordName('Am7')).toEqual({ root: 'A', rootPc: 9, quality: 'm7', bass: null, bassPc: null });+ expect(parseChordName('F#m7b5')).toMatchObject({ root: 'F#', rootPc: 6, quality: 'm7b5' });+ expect(parseChordName('Bb/D')).toMatchObject({ root: 'Bb', rootPc: 10, quality: 'major', bass: 'D', bassPc: 2 });+ expect(parseChordName('C/G')).toMatchObject({ quality: 'major', bass: 'G' });+ });++ it('normalizes quality aliases', () => {+ expect(parseChordName('Cmaj').quality).toBe('major');+ expect(parseChordName('CM7').quality).toBe('maj7');+ expect(parseChordName('Cmin7').quality).toBe('m7');+ expect(parseChordName('C+').quality).toBe('aug');+ expect(parseChordName('C°').quality).toBe('dim');+ expect(parseChordName('Co7').quality).toBe('dim7');+ expect(parseChordName('Csus').quality).toBe('sus4');+ expect(parseChordName('Cm7(b5)').quality).toBe('m7b5');+ });++ it('rejects non-chords, N.C., and qualities outside the curated set', () => {+ expect(parseChordName('N.C.')).toBeNull();+ expect(parseChordName('NC')).toBeNull();+ expect(parseChordName('Hm')).toBeNull();+ expect(parseChordName('lyric')).toBeNull();+ expect(parseChordName('C13')).toBeNull(); // valid token, uncurated quality+ expect(parseChordName('C6/9')).toBeNull();+ expect(parseChordName('')).toBeNull();+ expect(parseChordName(null)).toBeNull();+ expect(parseChordName(undefined)).toBeNull();+ });+});++describe('splitJoinedChords', () => {+ it('splits dash-joined chord runs when every segment is a chord', () => {+ expect(splitJoinedChords('Am-Am7')).toEqual(['Am', 'Am7']);+ expect(splitJoinedChords('C-G/B-Am')).toEqual(['C', 'G/B', 'Am']);+ });++ it('leaves hyphenated words and partial runs whole (tabNotation dash rules)', () => {+ expect(splitJoinedChords('well-known')).toEqual(['well-known']);+ expect(splitJoinedChords('Am-')).toEqual(['Am-']);+ expect(splitJoinedChords('-Am')).toEqual(['-Am']);+ expect(splitJoinedChords('C')).toEqual(['C']);+ expect(splitJoinedChords(null)).toEqual(['']);+ });+});++describe('toVoicingInstrument', () => {+ it('passes through the three diagram instruments and maps the rest to guitar', () => {+ expect(toVoicingInstrument('guitar')).toBe('guitar');+ expect(toVoicingInstrument('ukulele')).toBe('ukulele');+ expect(toVoicingInstrument('piano')).toBe('piano');+ expect(toVoicingInstrument('bass')).toBe('guitar');+ expect(toVoicingInstrument('voice')).toBe('guitar');+ expect(toVoicingInstrument('other')).toBe('guitar');+ expect(toVoicingInstrument(undefined)).toBe('guitar');+ });+});++describe('getChordVoicing — guitar', () => {+ it('returns the classic open shapes', () => {+ expect(getChordVoicing('Am', 'guitar')).toMatchObject({ frets: [-1, 0, 2, 2, 1, 0], baseFret: 1 });+ expect(getChordVoicing('C', 'guitar')).toMatchObject({ frets: [-1, 3, 2, 0, 1, 0], baseFret: 1 });+ expect(getChordVoicing('E', 'guitar')).toMatchObject({ frets: [0, 2, 2, 1, 0, 0], baseFret: 1 });+ expect(getChordVoicing('G', 'guitar')).toMatchObject({ frets: [3, 2, 0, 0, 0, 3], baseFret: 1 });+ expect(getChordVoicing('D', 'guitar')).toMatchObject({ frets: [-1, -1, 0, 2, 3, 2], baseFret: 1 });+ expect(getChordVoicing('A7', 'guitar')).toMatchObject({ frets: [-1, 0, 2, 0, 2, 0], baseFret: 1 });+ expect(getChordVoicing('Em7', 'guitar')).toMatchObject({ frets: [0, 2, 0, 0, 0, 0], baseFret: 1 });+ expect(getChordVoicing('B7', 'guitar')).toMatchObject({ frets: [-1, 2, 1, 2, 0, 2], baseFret: 1 });+ expect(getChordVoicing('Dsus4', 'guitar')).toMatchObject({ frets: [-1, -1, 0, 2, 3, 3], baseFret: 1 });+ expect(getChordVoicing('Cadd9', 'guitar')).toMatchObject({ frets: [-1, 3, 2, 0, 3, 0], baseFret: 1 });+ });++ it('derives barre shapes with a baseFret window', () => {+ // F = E-form barre at fret 1 (window stays absolute).+ expect(getChordVoicing('F', 'guitar')).toMatchObject({ frets: [1, 3, 3, 2, 1, 1], baseFret: 1 });+ // Bm = A-form barre at fret 2.+ expect(getChordVoicing('Bm', 'guitar')).toMatchObject({ frets: [-1, 2, 4, 4, 3, 2], baseFret: 1 });+ // C#m7 = A-form barre at fret 4 → re-based window.+ expect(getChordVoicing('C#m7', 'guitar')).toMatchObject({ frets: [-1, 1, 3, 1, 2, 1], baseFret: 4 });+ // Enharmonic spellings share the pitch class → same shape.+ expect(getChordVoicing('Dbm7', 'guitar')).toEqual(getChordVoicing('C#m7', 'guitar'));+ });++ it('keeps symmetric chords (aug, dim7) near the nut', () => {+ // aug repeats every 4 frets, dim7 every 3 — the root fret drops toward+ // the nut instead of stranding D aug at fret 10.+ const daug = getChordVoicing('Daug', 'guitar');+ expect(Math.max(...daug.frets.filter((f) => f > 0)) + (daug.baseFret - 1)).toBeLessThanOrEqual(5);+ const gdim7 = getChordVoicing('Gdim7', 'guitar');+ expect(Math.max(...gdim7.frets.filter((f) => f > 0)) + (gdim7.baseFret - 1)).toBeLessThanOrEqual(6);+ });++ it('voices the base chord of a slash chord and reports the bass separately', () => {+ const v = getChordVoicing('G/B', 'guitar');+ expect(v.frets).toEqual([3, 2, 0, 0, 0, 3]);+ expect(v.bass).toBe('B');+ });+});++describe('getChordVoicing — ukulele', () => {+ it('finds the canonical first-position GCEA shapes', () => {+ expect(getChordVoicing('C', 'ukulele')).toMatchObject({ frets: [0, 0, 0, 3], baseFret: 1 });+ expect(getChordVoicing('Am', 'ukulele')).toMatchObject({ frets: [2, 0, 0, 0], baseFret: 1 });+ expect(getChordVoicing('F', 'ukulele')).toMatchObject({ frets: [2, 0, 1, 0], baseFret: 1 });+ expect(getChordVoicing('G', 'ukulele')).toMatchObject({ frets: [0, 2, 3, 2], baseFret: 1 });+ expect(getChordVoicing('G7', 'ukulele')).toMatchObject({ frets: [0, 2, 1, 2], baseFret: 1 });+ expect(getChordVoicing('C7', 'ukulele')).toMatchObject({ frets: [0, 0, 0, 1], baseFret: 1 });+ // Em: the search prefers the lower-sum 0402 alternate over the 0432 grip+ // — same pitch classes, both standard fingerings.+ expect(getChordVoicing('Em', 'ukulele')).toMatchObject({ frets: [0, 4, 0, 2], baseFret: 1 });+ });++ it('only sounds chord tones and covers the required ones', () => {+ const UKE_OPEN = [7, 0, 4, 9];+ for (const name of ['Bb', 'F#m', 'Ebmaj7', 'C#9', 'Gdim7', 'Aadd9']) {+ const v = getChordVoicing(name, 'ukulele');+ expect(v, name).not.toBeNull();+ const abs = v.frets.map((f) => (f > 0 ? f + v.baseFret - 1 : f));+ const sounded = abs.map((f, i) => (UKE_OPEN[i] + Math.max(f, 0)) % 12);+ // Chord-tone pitch classes via the piano voicing (same interval source).+ const { notes } = getChordVoicing(name, 'piano');+ const tonePcs = new Set(notes.map((n) => NOTE_TO_PC[n]));+ for (const pc of sounded) expect(tonePcs.has(pc), `${name}: pc ${pc}`).toBe(true);+ // All tones covered — except the droppable perfect 5th on >4-tone chords.+ const { rootPc } = parseChordName(name);+ const required = [...tonePcs].filter((pc) => tonePcs.size <= 4 || pc !== (rootPc + 7) % 12);+ for (const pc of required) expect(sounded.includes(pc), `${name}: missing pc ${pc}`).toBe(true);+ }+ });+});++describe('getChordVoicing — piano', () => {+ const notes = (name) => getChordVoicing(name, 'piano').notes;++ it('spells common chords in root position', () => {+ expect(notes('C')).toEqual(['C', 'E', 'G']);+ expect(notes('Am')).toEqual(['A', 'C', 'E']);+ expect(notes('Am7')).toEqual(['A', 'C', 'E', 'G']);+ expect(notes('G7')).toEqual(['G', 'B', 'D', 'F']);+ expect(notes('Cmaj7')).toEqual(['C', 'E', 'G', 'B']);+ expect(notes('Csus2')).toEqual(['C', 'D', 'G']);+ expect(notes('Gsus4')).toEqual(['G', 'C', 'D']);+ expect(notes('Cadd9')).toEqual(['C', 'E', 'G', 'D']);+ expect(notes('C6')).toEqual(['C', 'E', 'G', 'A']);+ expect(notes('D9')).toEqual(['D', 'F#', 'A', 'C', 'E']);+ });++ it('spells sharps and flats letter-accurately from the root', () => {+ expect(notes('E')).toEqual(['E', 'G#', 'B']); // never Ab+ expect(notes('Eb')).toEqual(['Eb', 'G', 'Bb']);+ expect(notes('F#m7b5')).toEqual(['F#', 'A', 'C', 'E']);+ expect(notes('Abm')).toEqual(['Ab', 'Cb', 'Eb']); // minor 3rd of Ab is Cb+ expect(notes('D#m')).toEqual(['D#', 'F#', 'A#']);+ expect(notes('Bb6')).toEqual(['Bb', 'D', 'F', 'G']);+ expect(notes('Caug')).toEqual(['C', 'E', 'G#']);+ expect(notes('Cdim')).toEqual(['C', 'Eb', 'Gb']);+ });++ it('simplifies would-be double accidentals to enharmonic names', () => {+ // Ebdim's diminished 5th is Bbb — rendered as the simple enharmonic A.+ expect(notes('Ebdim')).toEqual(['Eb', 'Gb', 'A']);+ });++ it('carries the slash bass for prepending', () => {+ expect(getChordVoicing('Am/G', 'piano')).toMatchObject({ notes: ['A', 'C', 'E'], bass: 'G' });+ expect(getChordVoicing('C', 'piano').bass).toBeNull();+ });+});++describe('getChordVoicing — coverage and degradation', () => {+ it('voices every curated quality for every root on all three instruments', () => {+ for (const root of ROOTS) {+ for (const quality of QUALITIES) {+ const name = root + QUALITY_SUFFIX[quality];+ for (const instrument of VOICING_INSTRUMENTS) {+ const v = getChordVoicing(name, instrument);+ expect(v, `${name} on ${instrument}`).not.toBeNull();+ if (instrument === 'piano') {+ expect(v.notes.length).toBeGreaterThanOrEqual(3);+ } else {+ expect(v.frets).toHaveLength(instrument === 'guitar' ? 6 : 4);+ expect(v.baseFret).toBeGreaterThanOrEqual(1);+ expect(v.frets.some((f) => f >= 0)).toBe(true);+ }+ }+ }+ }+ });++ it('degrades to null for unknown chords and instruments — never throws', () => {+ expect(getChordVoicing('xyz', 'guitar')).toBeNull();+ expect(getChordVoicing('N.C.', 'ukulele')).toBeNull();+ expect(getChordVoicing('Cmaj9', 'piano')).toBeNull();+ expect(getChordVoicing('C', 'banjo')).toBeNull();+ expect(getChordVoicing(null, 'guitar')).toBeNull();+ expect(getChordVoicing(undefined, 'piano')).toBeNull();+ expect(getChordVoicing('A'.repeat(40), 'guitar')).toBeNull();+ });++ it('follows transposed chord names (transpose → voicing round-trip)', () => {+ const transposed = transposeChordName('Am7', 2); // Bm7+ expect(transposed).toBe('Bm7');+ expect(getChordVoicing(transposed, 'guitar')).toMatchObject({ frets: [-1, 2, 4, 2, 3, 2], baseFret: 1 });+ expect(getChordVoicing(transposeChordName('C/G', 7), 'piano')).toMatchObject({ notes: ['G', 'B', 'D'], bass: 'D' });+ });+});diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex e18b79d375..a6a5ee36c6 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -79,6 +79,7 @@ export * from './voiceLabel.js';export * from './audioContext.js';export * from './cityPlaybackFrame.js';export * from './canvasRoll.js';+export * from './chordShapes.js';export * from './colorMatch.js';export * from './editorialChecks.js';export * from './editorialHealth.js';diff --git a/client/src/lib/tabNotation.js b/client/src/lib/tabNotation.jsindex bb0f75abb4..de7169e174 100644--- a/client/src/lib/tabNotation.js+++ b/client/src/lib/tabNotation.js@@ -326,7 +326,10 @@ export const normalizePastedTab = (text) => {// Transposition// ----------------------------------------------------------------------------const NOTE_TO_PC = {+// NOTE_TO_PC and spellPitchClass are exported (minimally) for chordShapes.js,+// which reuses this module's pitch-class math for chord-voicing derivation+// rather than duplicating the tables.+export const NOTE_TO_PC = {C: 0, 'C#': 1, Db: 1, D: 2, 'D#': 3, Eb: 3, E: 4, Fb: 4, 'E#': 5, F: 5,'F#': 6, Gb: 6, G: 7, 'G#': 8, Ab: 8, A: 9, 'A#': 10, Bb: 10, B: 11, Cb: 11, 'B#': 0,};@@ -336,7 +339,9 @@ const FLAT_NAMES = ['C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb',// the names guitarists actually write (C# D Eb E F F# G Ab A Bb B).const DEFAULT_NAMES = ['C', 'C#', 'D', 'Eb', 'E', 'F', 'F#', 'G', 'Ab', 'A', 'Bb', 'B'];-const spellPitchClass = (pc, pref) =>+// Spell a pitch class (0–11) honoring an accidental preference: 'b' → flat+// names, '#' → sharp names, anything else → the conventional mixed table.+export const spellPitchClass = (pc, pref) =>(pref === 'b' ? FLAT_NAMES : pref === '#' ? SHARP_NAMES : DEFAULT_NAMES)[pc];// Transpose one chord symbol by n semitones (wraps mod 12; negative fine).