180 Commits

Author SHA1 Message Date
itsamejms 436522f3b4 Merge branch 'sprint-jamguide-piano' 2026-07-13 21:51:24 +01:00
itsamejms 077925f1d7 merging from sprint-jamguide-piano 2026-07-13 21:49:45 +01:00
vadimwit 072920ff0e docs+config: never-delete policy — CLAUDE.md hard rule + .claude/settings.json deny list
Claude must never execute destructive/irreversible commands (rm, git branch
-d/-D, git push --delete, reset --hard, force-push, DROP, etc.) — it proposes
them for the user to run. Enforced behaviorally in CLAUDE.md (authoritative)
and as permissions.deny rules in .claude/settings.json (defense-in-depth).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 21:36:02 +01:00
vadimwit 8ebdc73958 ledger: L-77 done (9415daf) — hybrid loop+history voicings rail, pushed both remotes
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 19:01:54 +01:00
vadimwit 9415daf4a0 feat(rail): hybrid voicings rail — highlight the loop + other recent chords underneath (task L-77)
The suggested-voicings rail no longer restricts to loop chords or collapses
to a single heard-live chord. It now shows TWO groups: the LOOP group (the
canonical GlanceRail, byte-unchanged — KB order, moving "now" playhead,
voice-leading chips) under a "the loop" caption, and an "also played" group
of the other recently-played DISTINCT chords (most-recent-first, each
expanded to its full voicing gallery, no chips / no playhead). With no loop
the "also played" group IS the rail, replacing the old single-chord
fallback. At least 4 chords show as soon as history exists (RAIL_TOTAL_CAP
top-up; only chords actually played, never fabricated).

GlanceRail gains an optional showTransitions prop (default true = the loop
caller is byte-unchanged); the history group passes false, which suppresses
the voice-leading chips + "next" tag AND switches the section framing off
the loop/playhead language, and renders non-focusable static row headers
(no inert focus button / misleading tooltip on history rows). App.jsx
untouched — chordHistory already flowed in. Verified build + validate-KB +
smoke 903/903 green.

User directive 2026-07-13: "highlight the loop chords when it finds a loop
but also add the other chords underneath ... at least 4 or more."

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 19:01:00 +01:00
vadimwit 7561566ceb ledger: L-78 done (d543b98, direct push); L-77 re-scoped to hybrid loop+history rail (>=4)
L-78 pushed on user request ("push everything now") — build+validate+smoke
903/903, full Critic gate waived. L-77 re-scoped same day: highlight loop
chords + list other recent chords underneath, >=4 total once history exists.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 18:47:37 +01:00
vadimwit d543b986dc feat(trythis): 3x3 ways-to-play — up to 3 guitar grips / 1 piano per suggestion (task L-78)
Try-this now fills its space: each of up to 3 substitutions renders as a
row with a left identity block (chord chip -> modal, category tag, why)
and a right "ways to play it" block that follows the global instrument —
guitar shows up to 3 genuinely different grips (getGuitarVoicings), piano
one MiniPiano, bass a root caption. A FIXED 3-slot frame reserves height
for all three rows (present -> SubRow, absent -> dashed EmptySlot) so
suggestions #1/#2 never shift when a chord yields 2 vs 3 subs (the
anti-jump ask). Honest: add9's 2-shape roots show 2 grips, not padded
fakes. Pure parseChordName/subsForChord/pickSubject preserved (per-chord
reactivity intact). Design tokens only. Verified: build + validate-KB +
smoke 903/903 green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 18:46:10 +01:00
vadimwit ede3f2e372 docs(design): related-area v2 (task D-76) — multi-chord rail + try-this 3x3; returned once (add9 shape count), fixed 2026-07-13 16:57:30 +01:00
vadimwit dc503807ef ledger: D-76/L-77/L-78 — related-area v2 (rail always-multi-chord most-recent-first; try-this 3-cap stable 3x3 guitar) 2026-07-13 16:42:19 +01:00
vadimwit 8c018d697d ledger: L-75/L-76 done (side-by-side try-this + 2x2 related, combined-gate PASS) 2026-07-13 16:32:35 +01:00
vadimwit e6957160f6 feat(related): 2x2 grid for suggested progressions (task L-76)
The suggested-progressions panel lays its entries out as a 2x2 grid
(grid-cols-1 sm:grid-cols-2) instead of a vertical list, using the
left-column width and halving the block height. Layout-only: a grid
class + a render-time slice(0,4); the ranker, scoring, cap
(RELATED_MAX_ENTRIES=5), and every entry's chips/labels are untouched,
so the C-50 ranking pins stay green. Idle/empty states stay
single-column. Critic PASS (combined gate).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 16:31:54 +01:00
vadimwit 957ce88fd6 feat(trythis): side-by-side suggestions with per-chord instrument diagrams (task L-75)
Try this now shows all of the current chord's valid substitutions at
once (no more rotation), each as a card with the chord name, a mini
diagram of how to play it in the selected instrument (guitar
ChordDiagram 4-across, piano MiniPiano keyboards in a 2x2, bass a root
caption), and the plain why. Still follows the live playhead so the
set refreshes per chord as the progression evolves; honest-empty
without a key/loop; the rolled-jam visibility fallback preserved.
App.jsx change is the single instrument prop, contract-clean. Critic
PASS (combined gate: diagrams resolve, root badge correct, reactivity
verified).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 16:31:54 +01:00
vadimwit 51c2be90cc docs(design): related-area layout — side-by-side try-this with per-sub diagrams, 2x2 suggested progressions (task D-75) 2026-07-13 16:15:38 +01:00
vadimwit 2905a4b979 ledger(backlog): Try-this vs Suggested-progressions should be two distinct features (user direction, revise later) 2026-07-13 16:11:06 +01:00
vadimwit c62cd60595 ledger: D-75/L-75/L-76 — related-area space layout (side-by-side try-this + diagrams, 2x2 related) 2026-07-13 15:55:28 +01:00
vadimwit 89b3e323ea ledger: L-70/L-71/L-74b done (combined-gate PASS) — rail/licks polish live 2026-07-13 12:59:39 +01:00
vadimwit 6885fc3ce1 fix(dashboard): Try-this card visible for any detected/rolled loop, not only live input (task L-74b)
The rotating Try-this card was gated on a live-detected currentChord,
so a rolled Jam Roulette (which locks a key + loop but leaves the
history empty until you play) showed nothing. TryThis now falls back
to the first loop chord that yields a substitution, so the card is
visible whenever a loop is on screen in a locked key; the live-playing
path is unchanged and honest-empty (no key / no loop) is preserved.
Critic PASS (combined gate: renders for the rolled-jam case, no
infinite render).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 12:58:40 +01:00
vadimwit 19b1a4ff91 feat(licks): dashboard licks strip — uniform compact cards following the instrument (task L-71)
The dashboard licks strip now follows the global GUITAR/PIANO/BASS
selector: guitar shows LickCard tabs, piano shows the PianoLickCard
piano-roll (jazz/blues/gospel/rnb), bass shows an honest empty line.
Every strip card is a uniform compact 220x150 box (tab/roll normalized
to a 104px-tall panel) so the licks stop hogging space. Play buttons
removed from the strip. Knowledge Center LicksSection + LickCard left
byte-identical. .dark-scroll applied to the rail/strip scrollers.
Critic PASS (combined gate).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 12:58:40 +01:00
vadimwit aae69e8a7b feat(rail): voicings rail polish — 4 guitar shapes, 2x2 mini piano, no play buttons, dark scrollbars (task L-70)
Dashboard voicings rail: guitar galleries capped to 4 shapes
(recommended-first, then open, then movable by base fret; prop-gated so
the Knowledge Center and chord modal keep all shapes); piano voicings
render as a 2x2 grid of size="mini" (scale 0.60) keyboards under the
rail's dense path only. Play buttons removed globally from
VoicingBrowser per the user ("leave them off, better not") — the
Knowledge Center + modal render byte-identical minus the buttons.
A scoped .dark-scroll utility (thin, #2a2a2a on transparent) dresses
the dashboard scrollers. Critic PASS (combined gate: byte-identity
proven, zero play buttons everywhere, contract intact).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 12:58:39 +01:00
vadimwit c16e9f1827 ledger: L-74b done (TryThis loop-fallback visibility); batch-gate plan for rail/licks 2026-07-13 12:40:48 +01:00
vadimwit 9e21df127c ledger: D-70 accepted; L-70/L-71 claimed (rail/licks build); play buttons global per user 2026-07-13 12:34:15 +01:00
vadimwit 3fdc72ebd4 docs(design): dashboard-polish concept (task D-70) — rail/licks optimizations, accepted to unblock the build 2026-07-13 12:33:37 +01:00
vadimwit 245d9f6fb2 ledger: L-74 done (rotating Try-this card); duplicate-name-loop rotation caveat backlogged 2026-07-13 12:23:42 +01:00
vadimwit 038fdfafc8 feat(dashboard): rotating Try-this card — one fresh substitution per loop pass (task L-74)
A compact TryThis card follows the playhead chord and shows ONE
suggestion at a time, cycling to the next valid substitution each time
the loop completes a pass (playhead wraps to a lower station). Over
Am-C-F the F cycles Dm -> Fm -> Fmaj7 -> E7 across passes, so the app
keeps offering a new idea and eventually teaches every honest move,
never a wrong one. Chip taps into ChordDetailModal; 0 subs -> no card,
1 sub -> static. Mounted App.jsx-only above RelatedProgressions in the
related slot; audio contract grep-clean; rotation logic exported pure
and StrictMode-safe. Critic PASS (2-pass rotation trace verified).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 12:23:18 +01:00
vadimwit 3469bafa0d feat(theory): suggestSubstitutions engine for the Try-this feature (task L-73)
Additive suggestSubstitutions({rootPc,quality}, keyInfo, opts) returns
up to 4 honest, correctly-spelled chord alternatives in the detected
key: relative/diatonic-third, borrowed-minor iv (flat-spelled b6),
diatonic extension colour, and the secondary dominant of the next
chord — each with a plain teaching why. A sabotage-proven smoke
truth-table pins the tables (Am-C-F both readings, the Rule-D blues
moves). Critic returned once (Rule C self-suggested the sounding chord
on 7th inputs: Dm7->Dm7, plus a latent add9-on-minor mis-spelling),
fixed (skip self-quality extension; omit category C when nothing new
to add), PASS on scoped re-gate. Smoke 903/903; theory.js purely
additive.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 12:04:34 +01:00
vadimwit 0b75ebdce1 ledger: L-73 returned (Rule C self-suggestion); L-74 = vary/rotate display (user decision) 2026-07-13 11:58:37 +01:00
vadimwit a311895d50 feat(related): same-style-first variations when a style is active (task L-72)
When the loop matches a KB style (rolled or live-detected),
RelatedProgressions leads with that style's other progressions under a
"Try these in {style}" header, labelled by data-derived character
(minor version / shorter form / extended form / reharmonized) computed
from mode/bars/qualities — no cross-style jumping. The role phrase is
suppressed unless the sibling is genuinely related (same changes or a
shared transition), so no false "variation" claim. When no style is
locked, today's cross-style list is preserved byte-for-byte. Smoke
893/893: §8 re-pinned (scores stable 92/156, labels moved) plus two
gate-added durable assertions (finding-B suppression + no-match
fallback). Critic PASS.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 11:37:37 +01:00
vadimwit a95ad147f7 ledger: D-73 done (try-this design PASS after 3 copy fixes) 2026-07-13 11:31:37 +01:00
vadimwit c2207ef7b6 docs(design): Try this chord-substitution feature — 4 curated moves with plain why-copy (task D-73)
For a loop chord in the detected key, suggest up to 4 alternatives:
relative/diatonic-third sub, borrowed-minor iv colour, extension
colour, and the secondary dominant of the next chord — each with a
one-line teaching why, ranked softest to boldest. Worked through the
Am-C-F case under both the A-minor and C-major readings; circle-of-
fifths tie-in kept honest (relative + secondary-dominant are circle
moves, borrowed + extension are not). Mounts as a compact TryThis card
above RelatedProgressions in App's relatedSlot (file-disjoint). Critic
returned once (chordRootPC circular-import trap, sharp-spelled b6, one
wrong mediant claim — all copy/plumbing, rules verified correct),
fixed, re-gate waived (gate-prescribed fixes verified directly).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 11:31:18 +01:00
vadimwit a13c8fecc0 ledger: no song forms; L-72 unblocked (findings A/B resolved); new Try-this substitution feature (D-73/L-73/L-74) 2026-07-13 11:15:54 +01:00
vadimwit bb802db2b6 ledger: D-72 done (design PASS); L-72 held pending user song-forms decision + finding-A/B
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 11:08:11 +01:00
vadimwit 952d8076df docs(design): same-style related-progressions — variations by structural difference (task D-72)
When a style is active (rolled or detected), RelatedProgressions leads
with same-style siblings reframed by data-derived character (minor
version / shorter form / extended form / reharmonized), computed from
mode/bars/qualities — no new KB content, no matcher change. Cross-style
same-changes entries demoted to a secondary section. Critic PASS (role
labels recomputed honest for blues + jazz; smoke-pin shift is
label-only). Deliberately avoids verse/chorus/bridge labels the KB has
no data for.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 11:07:32 +01:00
vadimwit c6c6427f50 ledger: user answer folded — related-progressions = reuse existing KB same-style siblings; D-72 unblocked, runs parallel
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 10:52:15 +01:00
vadimwit 4d562d758e ledger: seed sprint-dashboard-polish (M-08) — 4-guitar cap, 2x2 piano, no play buttons, dark scrollbars, licks follow instrument, same-style related
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 10:48:16 +01:00
itsamejms b8c955570e updating to make it more mobile optimized, making it a pwa, and testing it out on a phone 2026-07-12 20:38:58 +01:00
vadimwit 2072f3674e ledger: BOTH SPRINTS COMPLETE — one-screen + roulette-kb; L-60/C-61 done; combined PR summary
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 19:57:11 +01:00
vadimwit 1df6fe8e9e feat(app): Jam Roulette — one-click genre + key + progression to jam over (task L-60, 2/2)
The 🎲 button opens a genre popover (Surprise me + the 10 KB styles);
rollJam seeds a random key + an interesting round-trip-safe
progression as a committed loop, so the whole dashboard fills exactly
as if detection found it — banner chips, voicing rail, licks, related
progressions. Three commit-layer guards keep the seed alive until the
band takes over: the null-clear skips seeded loops (a seed would
otherwise die one commit before the earliest possible confirmation),
the agreement branch confirms it, replacement swaps once real playing
is consistent, New Song clears it. An amber "rolled · style · name ·
bars — play it!" provenance chip flips to the normal loop marker on
first agreeing detection. Audio contract grep: zero hits. Critic PASS
(seed timeline hand-traced; §3.5 invariant verified at every write).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 19:48:14 +01:00
vadimwit 8d74e54f5a fix(match): index collapsed loop forms — real 12-bar blues now matches its KB entry (task L-60, 1/2)
buildLoopIndex additionally indexes each progression's collapsed form
(adjacent (degree,suffix) dedup + wrap), appended after raw entries so
every prior matcher winner is preserved except the enumerated
country-145 self-attribution. Repairs a pre-existing LIVE-detection
bug: a real 12-bar or 8-bar blues stream collapses to fewer names than
the raw KB degrees, so it matched NOTHING and the Jam Guide sat empty.
JamGuide reads authored plays through the collapsed station's
sourceIndex (all four guitar/piano/bass paths). Adds seedableLoop +
the round-trip roulette pool (smoke sweep: 4 failures / pool 52).
theory.js canonicalize exported. Critic PASS (fix-(a) additivity
proven registry-wide; pool reproduced from the spec; bass sourceIndex
station 5 -> raw 10 hand-checked).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 19:48:14 +01:00
vadimwit 4b64c41417 ledger: one-screen COMPLETE (L-50/D-51/L-51/C-50); L-60 re-dispatched on Opus after Fable spend-limit
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 19:11:42 +01:00
vadimwit 4deba7e443 test(sweep): one-screen sprint-end sweep — ranking pins + registry id uniqueness (task C-50)
Smoke 886/886: RelatedProgressions ranking pinned (blues-12bar 152,
jazz-251-minor 156, no-collapse counterfactual 39 — replica grounded
against the live component; the 12-bar pin deliberately goes red when
D-62's collapsed indexing lands, message says re-pin). Validator:
registry-level progression-id uniqueness (the file walk missed
registry wiring dups — sabotage-proven with exactly one named error).
Whole-sprint App.jsx audio contract: zero hits since the seed.
Full-App SSR 60/60 across instrument x {normal, jam view}.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 18:27:20 +01:00
vadimwit 6e8d8f40fc feat(related): RelatedProgressions — loop-relative suggestions replace the generic table (task L-51)
KB-sourced ranking per the one-screen spec: same canonical degree
shape +100 (with the mandatory collapse of consecutive equal
degree/quality pairs — a real detector-produced 12-bar fires its blues
relatives despite the raw-index matcher bug), same style +40, shared
transitions +12 capped 36, degree-set Jaccard, length penalty; floor
24, max 5, never padded; entries render name/style/level/annotation +
the chord chain realized in the live key as real buttons ->
ChordDetailModal. match.js: additive exports only. Ride-along: dead
currentChord prop dropped from the banner mount. Critic PASS (both
hand-verified scores recomputed independently; full entry lists
byte-matched on three scenarios; collapse counterfactual = 39).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 16:52:52 +01:00
vadimwit d5a45f433a feat(rail): 500px-column adaptation — margin-hardened cells, wrap-safe basis (task D-51)
Chrome shave (rail p-2, rows p-1.5, dense cells p-1.5) so the
284+160 piano pair fits with real margin even under a classic Windows
scrollbar (was a genuine break: 452 > 439 at old paddings); gallery
basis 300->320 so a piano recommended cell can never share line one
(prominence for free) while guitar keeps 4 cells per line;
recommended-cell border strengthened to full accent. Playhead
highlight-only contract proven intact; non-dense mounts byte-identical
(28/28 at the gate). Critic PASS (arithmetic recomputed from source
AND the built CSS; flex-basis override confirmed in dist).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 16:51:09 +01:00
vadimwit e58a7a624c feat(app): one-screen jam dashboard + jam view (task L-50, commit 2/2)
Two-column grid: LEFT compact instrument view (natural-scale caps
674/562/674, non-compact renders byte-identical) + licks strip +
related-progressions slot (L-51 fills); RIGHT the 500px suggested-
voicings rail, height-bounded with internal scroll (not sticky).
ProgressionSuggestions unmounted (file kept). Jam view: one button,
two layers — CSS h-screen lock with everything below the grid
unmounted, plus best-effort Promise-caught requestFullscreen; Escape
and fullscreenchange stay in sync. Audio contract grep: zero hits.
Critic PASS (SSR 73/73; gate applied a one-class legend restoration
for non-compact byte-identity, re-verified green).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 16:28:25 +01:00
vadimwit 800fd43778 feat(banner): slim loop strip — big Now Playing chord removed (task L-50, commit 1/2)
Key chip + last-5 history + loop chips on one wrapping row; the
playhead loop chip and the enlarged current history chip are the
"now"; p-2 chrome trim. The text-6xl Now Playing column, its divider,
and the dead currentRN computation are gone — the loop shows once.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 16:28:25 +01:00
vadimwit 8e7a648660 ledger: roulette-kb 8/10 done, one-screen D-50 done + L-50 building; iteration log updated
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 16:02:44 +01:00
vadimwit 2c18c71598 feat(kb): piano licks pack #2 — gospel + rnb (task P-61)
8 licks (39 total): the gospel-scale run with the b3->3 crush, shout
run-up, harmonized sixths walk (the m6 falling exactly where the major
scale demands), diminished roll over the passing #iv dim7; the nine
sigh, quartal slip (grace-brushed fourths, all Dorian), the Dilla
lazy chromatic drop (derived approaches), pentatonic turn onto the 9.
Critic returned once (one interval claim said "each move a step" —
actually skip-then-step), fixed with the gate's own prescribed
wording, verified against its computed -3/-2 motion. 42/43 first-pass
checks; quality-context honesty verified against the styles' real
progressions.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 16:02:15 +01:00
vadimwit e87b2bbdcc docs(design): jam roulette spec — seed mechanism, matcher collapse fix, empirical roll pool (task D-62)
Two-click flow (button -> style -> instant seed) writing lockedKey +
detectedProgression + a seeded committed-vote so the whole dashboard
fills as if detected and live playing continues from it; three
commit-layer guards specced (every unguarded seed dies exactly one
commit before earliest confirmation); fix (a): match.js additionally
indexes collapsed forms — repairing the pre-existing live bug where
10 progressions (incl. blues-12bar) never match detection, plus
country-145 misattribution; roll pool = steady-state all-offsets
round-trip passers (52/56); sourceIndex remap covers guitar, piano
AND bass play lookups. Returned twice, PASS on round-3 re-gate (a
literal implementation of the sweep protocol reproduced the pinned
numbers with zero interpretation gaps).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 15:54:43 +01:00
vadimwit a7dbd6a8b1 feat(licks): PianoLickCard — piano-roll lick renderer with playback (task D-60)
Pitch-timeline thumb (beat-proportional columns, note-name pills,
contour line, dashed root gutter, amber approaches, technique glyphs);
size=full adds an order-badged keyboard view + chordContext/tips;
exported pure realizePianoLick (deg via the shared resolveDegree,
approaches derived from the next deg, null on malformed); playback
mirrors BassPatternCard (sequential playVoicing, one sequence,
unmount silence). Activates the dormant C-60 vocab guard (smoke
880/880). Component only — LicksStrip wiring deferred behind the
one-screen restructure. Critic PASS (41/41 realization audit at
hand-derived expectations, 87/87 SSR, no third resolveDegree copy).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 15:48:31 +01:00
vadimwit d24bf352e1 docs(design): one-screen jam dashboard concept + jam view (task D-50)
Slim loop strip (76px trimmed banner, big Now Playing chord removed),
two-column grid: compact instrument view (natural-scale cap 674/562px)
+ licks + related-progressions LEFT, height-bounded voicings rail
RIGHT (500px, internal scroll — honestly NOT sticky: zero travel in
the flex row); jam view = CSS h-screen lock + best-effort
requestFullscreen (Promise-caught), hiding everything below;
related-progressions ranking spec'd with the collapse rule
coordinated with D-62's matcher fix. Critic returned once (strip
height, inert sticky, double-counted padding, raw-vs-collapsed
ranking), fixed, PASS on scoped re-gate (all budgets recomputed).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 15:48:31 +01:00
vadimwit 70263e221e feat(kb): piano licks pack #1 — jazz + blues, the KB's first piano licks (task P-60)
8 licks (31 total): bebop enclosure into the b3, Baker's 3-5-b7-b9
dim-flip over the V7, Powell ascent to the 9th, Garland-lane dominant
thirds fall; the b3->3 crush, pentatonic turnaround fall (verified
survives over a minor blues), Spann hammer dyads, the cry-and-melt
7#9 fill. All realized before prose was written. Critic PASS (35/35
prose claims recomputed in two keys; idioms verified to match their
names, not just cite them; dom7-heavy blues coverage accepted as
musically right).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 15:42:23 +01:00
vadimwit c999c958cb feat(explore): circle of fifths — live key wedge, safe-neighbour tiers, modal parent-major hub (task D-61)
SVG circle in the Knowledge Center Explore section: 12 majors outer
ring with key-signature glyphs, relative minors inner, live/locked key
solid accent with subdominant/dominant/relative soft-tiered; diatonic
chord chips inline (tap -> ChordDetailModal); wedge tap = local
preview only, app key state never touched; modal keys light the
correct ring and the hub teaches the parent-major relationship
("1# - G major's notes" for A dorian; 72/72 mode x root uniqueness
proven). Critic returned once (hub showed the wedge signature, not
the mode's), fixed, PASS on scoped re-gate.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 15:42:22 +01:00
vadimwit ffc1bb1d18 feat(kb): pop piano cell + 8 guitar shapes for thin qualities (task P-62)
Pop piano: 5 progressions x 2 plays (182 total) — triads/inversions
only, one sourced add9 shimmer; ballad rolls vs voice-led pillars,
doo-wop triplets vs one-finger walks, Pachelbel inversion stair,
tonic-drone pads, octave drive. Shapes: dim7/half_dim/aug/maj6/min6
each reach >=3 placeable grips, add9 gains a movable A-shape; dim
honestly left at 2. Audit also surfaced two WRONG pre-existing shapes
(half_dim E-Barre spells {0,3,6,7}; "Open Dadd9" is Dsus2) -> backlog.
Critic PASS (~110 independent checks; all additions pc-spelled in two
keys; strictly additive diff).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 15:34:29 +01:00
vadimwit 5f4e2b715d feat(kb): piano lick schema — degree-based melodic lines with derived approaches (task C-60)
Piano licks live in <style>/piano.js licks arrays: required quality
(machine truth), deg XOR approach targeting the NEXT deg note
(enclosures fall out as idiom; same-type consecutive approaches
rejected), octave 0-2 with a 25-semitone cap proven one-semitone tight
against MiniPiano's 37-key window, 4-word piano technique vocab
(grace-note added; bend/vibrato impossible on keys), plus a dormant
smoke guard that activates when PianoLickCard.jsx exists. Smoke
879/879. Critic PASS (18 fresh sabotage cases, enclosure arithmetic
hand-verified, dormant guard proven to fire).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 15:24:19 +01:00
vadimwit b753b58f70 ledger: seed sprint-roulette-kb (M-07) — piano licks, voicings, circle of fifths, jam roulette; hourly x12 loop
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 15:05:26 +01:00
vadimwit 272f88a7b4 ledger: seed sprint-one-screen (M-06) — dashboard redesign, kill big chord, voicings right, loop-relative suggestions
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 14:38:02 +01:00
vadimwit acb178e8d8 ledger: iteration 4 — SPRINT sprint-integrated-glance COMPLETE (all 11 tasks green)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 20:20:03 +01:00
vadimwit 218c0ba4ca test(smoke): drift guard now sweeps BOTH resolveDegree copies (task C-42)
JamGuide resolveDegree imported directly (exported by the L-40
ride-along) via a .jsx resolve-retry hook; 17 new checks (export pin +
16 per-degree JamGuide sweeps) -> smoke 866/866. Sabotage-proven: a
perturbed JamGuide cell turns smoke red naming the exact drift.
Authored by the C-42 sweep agent pre-termination; verified and
sabotage-tested by Maestro (spend-limit fallback).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 20:18:59 +01:00
vadimwit af7c3cc0a7 feat(bass): BassPatternCard — authored basslines render as 4-string tab in the band (task L-42)
Realizes SCHEMA bass patterns per station (root at lowest playable
position, degs via the shared resolveDegree, typed approaches derived
from the next station with the open-E octave-displacement rule), lays
them out as compact E-A-D-G tab cards (lick-tab visual idiom), all
plays side by side, each with sequential playback through chordAudio
(negative notes documented-legal; one sequence at a time). Computed
root-fifth-approach line remains the fallback for pack-less styles.
BASS is now real end-to-end. Critic PASS (independent re-realization
of all 912 placements exact; untouched instrument paths byte-identical;
import cycle proven safe in both load orders).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 19:31:21 +01:00
vadimwit 4650494f0d ledger: integrated-glance iteration 3 — D-41 done (gate notes logged); L-42 in flight
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 19:17:15 +01:00
vadimwit 677d7b99d1 feat(rail): all stations expanded, playhead highlights only (task D-41)
Every loop chord is a permanently expanded vertical row: education
header (solo-scale label, guide-tone aim dots with honest 5th
fallback, voice-leading chip incl. the wrap-around loop rail) + the
full voicing gallery for the global instrument; galleries flex-wrap,
zero row-level horizontal scroll; playhead adds highlight classes only
(rows proven byte-equal modulo highlight artifacts); pin simplified to
a focus toggle (onFocusChord contract byte-compatible with L-40).
VoicingBrowser: show='bass' now renders an honest one-liner instead of
falling through to both galleries; dense drops section chrome
(non-dense proven byte-identical across 336 SSR combos). Critic PASS.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 19:03:48 +01:00
vadimwit 7d6fe8ad50 ledger: integrated-glance iteration 2 — P-41/L-40 done (gate notes logged); D-41 in flight
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 18:47:14 +01:00
vadimwit c899132b94 feat(app): Jam Guide band promoted below the main module — one loop display, one instrument selector (task L-40)
The always-open zero-chrome band (GlanceRail + licks strip +
heard-live fallback) replaces CurrentJamPanel right below the
instrument view; the four-section dock becomes KnowledgeDock at the
bottom; RoadmapTrack unmounted (banner is the single loop display);
JamGuide's internal instrument/style tabs die — App's global
GUITAR/PIANO/BASS selector drives everything incl. the dock's
VoicingsSection; honest bass state (computed root-fifth-approach rows
+ notice, no galleries/licks); GlanceRail's scrollIntoView effect
deleted same-commit (would yank the document in page flow).
Ride-along: JamGuide resolveDegree exported (logic byte-identical) for
the C-40 drift guard. Critic PASS (SSR 22/22, audio-contract grep
zero hits, deletion sweep clean).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 18:38:30 +01:00
vadimwit 01a7c32f55 feat(kb): blues bass cell — the KB first bass pack, 8 plays over 5 progressions (task P-41)
Boogie walkups, 8th-note ramble, Jimmy Reed R-5-6-5 shuffle, 12/8
root-fifth-octave slow burn, minor box riff (quality-resolved 3rd
self-majorizes on bVI7/V7), walking turnaround + two-beat kicks. The
maj-7 climb authored as a typed chrom-below approach (pitch derived,
offset 11 never written). KB now 172 plays. Critic PASS first try
(all 76 patterns machine-realized in C AND A; 12 prose identities
recomputed, all hold key-agnostically).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 18:32:41 +01:00
vadimwit 2450318d42 ledger: integrated-glance iteration 1 — M-05/P-40/C-40/D-40/C-41 done; L-40/P-41 in flight
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 18:17:18 +01:00
vadimwit 996218f39c feat(kb): bass play schema — degree-based patterns with typed approach notes (task C-41)
Key-agnostic bass plays (piano-recipe language): deg XOR typed
approach (chrom-below/above, fifth-of-next — pitch derived from the
next station, never authored), octave 0-1 with a 19-semitone cap
(exactly fret 15 on E-A-D-G), root rule, terminal approaches,
non-decreasing beats, MIN_PLAYS_BASS=1. Legacy BASS_TOKENS stub
replaced (zero references). Smoke 849/849 with 13 new checks;
sabotage-proven twice (author + gate, different malformations).
Ride-along: SCHEMA documents the resolveDegree 7-on-6-chords quirk.
Critic PASS.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 18:11:02 +01:00
vadimwit 7d1f64c718 docs(design): integrated-glance concept — band below the module, one loop display, one selector (task D-40)
Zero-chrome always-open band replaces CurrentJamPanel below the
instrument row; ProgressionBanner survives as the single loop display
(RoadmapTrack retires, education folds into rail row headers); App
instrument state threads everywhere (JamGuide internal tabs die);
vertical rows, all stations expanded, playhead highlights; honest
wrap-based math (worst piano gallery 1,178px). Critic returned once
(Dm7-specific worst case + 3 factual fixes incl. the interim
page-yank), fixed, PASS on scoped re-gate (pixel-exact recompute).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 18:08:26 +01:00
vadimwit 090d3a9cbf test(smoke): drift guards for resolveDegree + technique vocab (task C-40)
Smoke 836/836: a literal 16x14 degree truth table (all 224 cells
independently recomputed at the gate) pins the validator resolveDegree
behaviourally via span-probe recipes; technique vocab set-equality
between validate-kb LICK_TECHNIQUES and LickCard TECHNIQUE_VOCAB via a
scoped .jsx esbuild load hook. Both guards sabotage-proven twice
(author + gate, different perturbations). Ride-along: loop-fixtures
header line-ref fixed to App.jsx:363-365. Critic PASS.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 17:53:41 +01:00
vadimwit 6f59add11b docs(kb): backlog refreshed to reality — 14 cells done, licks tracked, bass column activated (task P-40)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 17:47:02 +01:00
vadimwit facf6c8cc3 ledger: seed sprint-integrated-glance (M-05) — promote guide up top, single loop display, one instrument selector, all-expanded voicings
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 17:37:51 +01:00
vadimwit 9772e951b7 ledger: iteration 4 — SPRINT sprint-glance-and-loop COMPLETE (P-31/C-31 done; all 11 tasks green)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 10:10:20 +01:00
vadimwit 81cd230a4c feat(kb): blues piano cell — 5 progressions x 2 authored plays (task P-31)
Guide-tone/tritone dyad system with the parallel half- and whole-step
laws, 7#9 as the codified blue note, the bVI7->V7 five-voice plane,
VI7b9 turnaround hinge, RH sixths; solo two-fisted vs rootless-band
contrasts per play. KB now 164 plays. Critic returned once (turnaround
jump-kicks bars 3-4 dyad orientations flipped + 2 prose rewordings),
fixed, PASS on scoped re-gate (stepwise lap chain recomputed from
scratch; "only leap" now provably unavoidable, not just chosen).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 09:58:41 +01:00
vadimwit 0b982f9514 ledger: iteration 3 reconciled — L-33/L-31 done (gate notes logged); P-31 gating; C-31 ready
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 09:47:20 +01:00
vadimwit ce24d5490f fix(app): progression commit-layer tuning — survive fills, replace on evidence (task L-31)
COMMIT_VOTES=2 (unchanged, ~one bar), REPLACE_VOTES=3 (a transient or
flapping detection can never displace a committed loop; section change
replaces one commit later), NULL_CLEAR=6 (post-L-30, nulls only start
~28 commits after the loop last played — traced exactly). Vote ref now
{committedKey, candidateKey, candidateCount}; agreement resets rivals.
Diff = one hunk in the progression useEffect; audio-contract grep
clean. Ride-along: theory.js docstring overclaim softened (L-30 gate
finding b), comment-only. Critic PASS (independent re-trace of all
five scenarios + 3 hostile traces; REPLACE_VOTES=3 proven load-bearing).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 09:28:52 +01:00
vadimwit c78baf4943 feat(jamguide): glance mode — the playhead accordion (task L-33)
The station under the playhead auto-expands to the full voicing
gallery (VoicingBrowser dense) and advances with the music; other
stations keep their recommended thumb; level-filtered licks strip
below with token-boundary context sort and strip-owned "fits — now"
chrome; pin replaces tap-to-enlarge with identical onFocusChord
semantics; auto-follow never emits focus or audio; heard-live fallback
shows the live chord gallery. App.jsx and all renderers untouched.
Critic PASS (SSR 37/37, matcher proven on hostile cases, dense-less
render byte-identical to 0945a08).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 09:28:51 +01:00
vadimwit 5e9b4c5925 ledger: iteration 2 reconciled — P-30/L-30 done (gate notes logged); L-31/L-33 in flight; P-31 claimed
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 09:17:30 +01:00
vadimwit 4cc0009983 feat(theory): noise-tolerant loop detection rewrite (task L-30)
detectRepeatingProgression redesigned: consecutive-dup collapse,
weak-period candidate rejection (kills self-overlap ghosts
structurally), lengths 2-8, <=1 substitution/insertion per cycle with
a >=2-exact-occurrences evidence gate, recency-weighted linear
coverage scoring. All 17 C-30 fixtures pass plain (smoke 817/817,
expectedFail markers removed). Critic PASS: 15 novel generalization
probes correct or data-faithful, 0.2-0.7 ms/call, diff confined to the
repeating-progression section, fixture contract untouched.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 09:10:28 +01:00
vadimwit b51daa1339 feat(kb): neo-soul/rnb piano cell — 7 progressions x 2 authored plays (task P-30)
Signature comp voicings over the computed fallback: m9 spreads, So What
quartal planing, Stevie 9sus cadence, m6/9 borrowed iv, 13sus, one 7#9
per loop; 3 comping cells + 5 improv rows. KB now 154 plays. Critic
PASS first try (independent arithmetic on 11 prose claims, spans <=11,
all 12 keys render in the 36-key window).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 09:06:53 +01:00
vadimwit 7926783778 ledger: iteration 1 reconciled — D-30/C-30/D-31 done; L-30/P-30 resumed; L-33 claimed
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 08:57:07 +01:00
vadimwit 6c7a1a7828 docs(design): glance-mode concept — the playhead accordion (task D-31)
Knowledge Center behaviour while a jam plays, zero clicks: the station
under the playhead auto-expands to the full D-30 voicing gallery and
advances with the music; level-filtered licks strip below with
context-first sort; pin gesture inherits onFocusChord semantics;
auto-follow never emits focus or auto-plays audio. Honest space math
(piano rail scrolls as normal state), 5-commit migration order for
L-33, four rejected alternatives. Critic returned once (piano gallery
width understated ~45%), fixed, PASS on scoped re-gate.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 01:00:16 +01:00
vadimwit fdd93c7158 test(loop): truth fixtures for detectRepeatingProgression + smoke wiring (task C-30)
17 fixtures (9 regression guards, 8 annotated expectedFail) pinning the
current detector failure map: len^2 self-overlap artifact on 2-chord
vamps, ghost 4-patterns under substituted/inserted misdetections,
duplicate-commit safety, 7/8-loop length cap, stale-section recency.
Stale expectedFail markers turn smoke red, forcing L-30 to flip them.
Critic PASS (arithmetic recomputed, sabotage x3 proven to bite).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 00:55:27 +01:00
vadimwit 0945a08497 feat(voicings): VoicingBrowser gallery — every shape and piano style side by side, no chips (task D-30)
All placeable guitar shapes and all four pianoVoicing styles render
simultaneously, each cell with its own play button; one-at-a-time
playback and the show prop semantics preserved. Critic PASS (SSR-verified
cell counts, zero aria-pressed, rootPc badge guard intact).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 00:50:33 +01:00
vadimwit 401d9d1f17 ledger: seed sprint-glance-and-loop (M-04) — gallery voicings, loop-detection redesign, glance mode
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 00:38:49 +01:00
vadimwit 3077ae2ac0 fix(dev): allow 127.0.0.1 HMR websocket in the CSP
Follow-up to the 127.0.0.1 bind: connect-src only whitelisted the
localhost variants, silently blocking Vite's HMR socket on the new
origin.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 23:41:56 +01:00
vadimwit fab385a612 fix(dev): pin dev server, wait-on gate, and Electron loadURL to 127.0.0.1
With plain localhost, node >=17 can bind the Vite dev server to ::1
only; on this machine IPv4/IPv6 loopback mismatch made the browser,
wait-on, and the Electron window all see connection-refused while Vite
reported ready. Explicit 127.0.0.1 on all three ends fixes dev startup
(user-verified: electron:dev window now opens).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 23:40:44 +01:00
vadimwit b5073353ef ledger: sprint-knowledge-center COMPLETE — PR #3 opened; loop closed
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 01:45:20 +01:00
vadimwit 0f24c757a1 ledger: C-21 done (sprint sweep PASS); prune shipped backlog entries
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 01:39:43 +01:00
vadimwit 72c6d457b0 ledger: iterations 6-7/24 — L-24/L-25/C-22/P-23 done; C-21 claimed; log
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 01:28:54 +01:00
vadimwit 2165bb571c feat(jamguide): stations render authored piano packs when a style has one (task L-24)
Piano branch prefers kb[style].instruments.piano.plays[prog][0],
resolving recipe degrees via a validator-mirrored resolveDegree +
strict-ascending stacking into MiniPiano's [0,36] space; per-station
fallback to computed pianoVoicingChain (reachable: 4 wide gospel
stations in key B); pack-less styles byte-identical to the computed
path. Critic PASS (0 drift cells vs the validator's resolveDegree;
390-cell sweep; key-B fallback confirmed rendering, not dead).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 01:28:22 +01:00
vadimwit 564a9e0a3a feat(kb): gospel piano cell — 14 plays across all 7 progressions (task P-23)
Church pillars vs rootless, hymn 12/8 vs octave-6/9, passing-dim walks
vs praise clusters, worship pads vs anticipated stabs; gospel comping
cells distinct from jazz's. KB: 140 plays. Critic returned once (one
improv-row scale claim false for vi7/iii7 — split into arithmetic-exact
rows), PASS on re-gate; 39/40 first-pass claims held.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 00:55:45 +01:00
vadimwit b4e8f12539 feat(kb): validator enforces the piano hand-span rule (task C-22)
checkPianoRecipe stacks each hand low-to-high (nearest strictly above,
repeated pc -> octave up) and fails any hand spanning > 15 semitones
(minor 10th, SCHEMA rule 3); errors name style/prog/play/chord/hand/
span; refactored to a pure exported checker surfacing all errors per
recipe. Smoke +6 checks -> 799. Independent gate PASS (injection
surfaces 10 named errors exit 1; weakened gate caught behaviorally).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 00:27:25 +01:00
vadimwit e24aa4b6ed feat(jamguide): chord modal tabs show only their instrument's voicings (task L-25)
GuitarTab/PianoTab pass show=guitar/show=piano to VoicingBrowser
(D-23 prop); Knowledge Center + station-enlarge keep both rows by
design. Critic PASS (SSR: each tab renders only its row, legacy
content intact below).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 00:25:13 +01:00
vadimwit ee009a708d ledger: iteration 5/24 — D-23/D-24/P-24 done (Critic PASS x3); log
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 00:00:42 +01:00
vadimwit 0f9c87c1e8 feat(kb): licks pack #2 — 11 licks for rock, country, reggae guitar (task P-24)
Berry double-stops, unison bend, Mixolydian rail, pentatonic cascade;
Flatt G-run, chicken-pickin' 3rds, pedal-steel bend, forward roll
(first techniques:[] lick); skank-answer dyads, bass-doubling riddim,
chromatic walk into the one drop. KB: 23 licks across 6 styles.
Critic PASS (every note independently pitch-verified; conventions
script-checked; empty-techniques branch verified in the validator).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 00:00:42 +01:00
vadimwit e2110ae21f feat(design): MiniPiano voicing thumbs crop to the voicing's octave span (task D-24)
Thumb window = whole octaves from the octave-C at-or-below the lowest
note (+ closing high C): shell thumbs 266px -> 142px, level with guitar
diagram thumbs. size=full and the legacy lh/rh path byte-identical.
Critic PASS (SVG geometry decoded back to absolute notes incl. the
octave-2 offset case; 793/793 smoke).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 23:58:23 +01:00
vadimwit db397f6ceb feat(design): VoicingBrowser show prop + LickCard stack-guard hardening (task D-23)
show='guitar'|'piano'|'both' (default both — 50/50 SSR renders
byte-identical for existing mounts); LickCard double-stop collision
guard now checks all same-column notes. Critic PASS (subsumption
proven; 13/13 lick layouts unchanged; adversarial overlap dead).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 23:56:22 +01:00
vadimwit ee81326db0 ledger: iteration 4/24 — P-21/P-22/L-22 done; promote L-24/C-22/P-23; log
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 23:53:35 +01:00
vadimwit 9e2567cf20 feat(kb): jazz piano cell — the KB's first authored piano pack (task P-22)
14 plays (7 progressions x 2): Bud Powell shells, rootless Type A/B,
guide-tone comps; comping rhythms; piano-angled improv. Hand spans
<= a 10th throughout. Critic returned once (6 prose voice-leading
overclaims on fifths-apart dominant alternation), fixed, PASS on
re-gate (all 6 corrected sentences arithmetic-verified both
directions); ride-along one-word polish per gate suggestion.
Rendering the authored pack in the Jam Guide is task L-24.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 23:52:23 +01:00
vadimwit 78706ce5ba feat(jamguide): Knowledge Center shell — four-section dock with level filter (task L-22)
Jam Guide (live, verbatim Roadmap move) / Explore (KB browser + famous
progressions, filter-exempt) / Voicings (picker follows live chord ->
VoicingBrowser) / Licks & Techniques (LickCard grids + one legend,
honest empty states). Shared foundation/intermediate filter chips;
ExplorePanel refactored to named exports (was orphaned, now imported).
App.jsx: exactly one additive prop (onChordClick). Critic PASS (48/48
SSR checks; audio contract grep clean; Roadmap hunks byte-identical).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 23:38:28 +01:00
vadimwit 6ea1089295 feat(kb): licks pack #1 — 12 licks for blues, jazz, funk guitar (task P-21)
4 per style using the C-20 lick schema: B.B. box, turnaround, slow-blues
curl, IV9 tritone slide; The Lick, ii-V-I enclosure, bebop dominant
descent, guide-tone rails; 9th riff, chromatic snapback, Dorian stabs
and 6-line. Every note hand-verified against its chordContext; sources
hedged. Critic PASS (independent pitch computation of all 12; validator
12 licks green; double-stop/slide glyph ordering render-checked).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 23:32:18 +01:00
vadimwit 432a238c15 ledger: iterations 2-3/24 — D-21/D-22/P-20/L-21/L-23 done; narrow P-21 lock; log
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 22:57:36 +01:00
vadimwit c08b334bad feat(kb): intermediate progressions + level tags for jazz, gospel, rnb (task P-20)
6 new level:'intermediate' progressions (tritone sub, rhythm-changes
bridge, gospel passing-dim walk-up, tonicized amen w/ borrowed iv,
Just-the-Two-of-Us loop, Sir Duke chromatic vi) x 2 guitar plays each;
all progressions in the three styles now carry explicit level. KB:
56 progressions / 112 plays. Critic returned once (3 caption theory
misstatements), fixed, PASS on re-gate (voice-leading arithmetic
hand-verified from shape constants).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 22:56:58 +01:00
vadimwit 951d5440e1 feat(jamguide): playable VoicingBrowser in chord modal + enlarged stations (task L-21)
ChordDetailModal Guitar/Piano tabs mount VoicingBrowser on top with
legacy grips/technique reference preserved below; Jam Guide enlarged
station view gains the browser on both instrument tabs; parse-null
never mounts a wrong-chord fallback. App.jsx untouched. Critic PASS
(SSR-verified both entry points; onFocusChord effects byte-untouched).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 22:55:42 +01:00
vadimwit f4e0ac67e0 fix(voicings): correct movable-shape base-fret indexing in getGuitarVoicings (task L-23)
strIdx = rootStr-1 read OPEN [s6..s1] backwards: every rootStr-5 shape
sat 2 frets low, every rootStr-4 shape 5 frets low (A-shape C major
labeled fret 1 instead of 3) in ChordDetailModal/ExplorePanel/
CurrentJamPanel; rootStr-6 was accidentally correct (same pc both ends).
Now uses the shared 6-rootStr convention. Also: playChord docstring
octave example corrected. Critic PASS (6 independent fret checks +
252-entry pre/post sweep, structure unchanged).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 22:54:18 +01:00
vadimwit 3c903ad1d9 feat(design): VoicingBrowser — switchable, playable voicings per chord (task D-21)
Guitar row (placeable GUITAR_SHAPES via ChordDiagram) + piano row (4
pianoVoicing styles via MiniPiano), chips + explicit play button per
voicing through chordAudio; single shared stop handle; graceful
guitar-empty cell (only add9@E across 168 quality x root cells).
voicings.js gains an export-only GUITAR_SHAPES line. Critic returned
once (rootless voicings badged lowest voice as root — rootPc now passed
through), PASS on scoped re-gate.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 22:43:21 +01:00
vadimwit 44d9c4f0e8 feat(design): LickCard — tab-style SVG lick renderer with technique glyphs (task D-22)
String 1 (high e) on top per tab convention; h/p slurs, slide, bend,
vibrato, ghost, double-stop column stacking; TechniqueLegend named
export (once per grid); layoutTab pure + testable; DEMO_LICK fixture
until P-21 lands. Critic PASS (47/47 harness checks, schema-exact).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 17:29:17 +01:00
vadimwit 0eeb308aa8 ledger: iteration 1/24 — L-11/L-20/D-20/C-20 done (Critic PASS x4); file L-23; log
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 17:08:06 +01:00
vadimwit 793e60ab05 feat(kb): schema + validator + smoke for progression levels and licks (task C-20)
Optional additive shapes: progression level (foundation|intermediate)
and per-pack licks (8-word technique vocab, tab notes string 1-6 /
fret 0-15, ids global with progressions). Validator exports checkLick
as a lib for smoke (KB_VALIDATE_AS_LIB guard); smoke 776 -> 787.
Critic PASS (independent sabotage re-proof: injected bad lick exit 1
with named errors; weakened vocab fails smoke 2/787).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 17:07:10 +01:00
vadimwit 96dda6a3ef docs(design): Knowledge Center concept — unified four-section dock (task D-20)
Jam Guide (live) / Explore / Voicings / Licks & Techniques grown from
the JamGuide dock; level filter as toggle chips; 5-commit migration
order for L-22. Audit finding: ExplorePanel + EducationPanel are
orphaned (never mounted) — migration risk far lower than assumed.
Critic PASS (orphan claim, App.jsx one-prop claim, contrast ratios all
independently verified).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 17:04:16 +01:00
vadimwit 7b669f8c11 feat(jamguide): piano tab live — per-station voice-led MiniPiano voicings (task L-11)
Piano is computed (pianoVoicingChain over canonical stations), no
authored KB needed; guitar path value-identical; tap-station guide-tone
contract intact; App.jsx untouched. Critic PASS (303/303 empirical
station checks across 3 progressions x 3 keys; voice-leading threads).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 17:01:55 +01:00
vadimwit 4b0f0c84a7 feat(audio): Web Audio voicing playback engine src/lib/chordAudio.js (task L-20)
playVoicing (piano.js absolute-note space, strummed, soft envelope),
guitarShapeToNotes (tab lists / open frets / movable rootStr+offsets via
the ChordDiagram convention), playChord pc fallback, stopAll. Dedicated
lazy AudioContext; zero coupling to the detection pipeline; mic-feedback
caveat documented. Critic PASS (19/19 independent pitch-math checks).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 17:01:40 +01:00
vadimwit 396c6ba562 ledger: seed sprint-knowledge-center (M-03) — user directive 2026-07-08
Playable voicings per chord, lick/technique cards, intermediate
progressions with level tags, Knowledge Center IA revamp; L-11 hold
lifted and carried forward; /jam-loop 30m x 24 iterations scheduled.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 16:49:07 +01:00
vadimwit 4424e8d72c ledger: D-10/C-10/L-13 done (Critic PASS); L-11 held for user review; log iteration
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-16 11:00:44 +01:00
vadimwit 4727645bb9 fix(piano): dedupe duplicate absolute notes in pianoVoicing (task L-13)
A forced rootless sus2 collided the suspended-2nd and synthesized 9th onto one key
(notes [26,26,31]). Dedupe at the single funnel point ([...new Set(placed)]); pcs/bass
derived from the deduped array. No-op on default/chain path (L-11 render unaffected).
Critic: Set merges only identical absolute integers (same key) so no needed note is lost.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-16 11:00:43 +01:00
vadimwit f98528733d test(piano): smoke coverage for the piano voicing resolver (task C-10)
+705 checks (776 total): per quality x root x style, asserts pcs subset of voicingToneSet,
real 3rd present, true-7th when hasTrueSeventh, notes in [0,36], bass==min, no duplicate
absolute note, determinism, chain pcs-preservation. Surfaced the sus2 dup-note wart (fixed
by L-13). Critic adversarially confirmed the checks bite. Derived expectations, no hardcoding.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-16 11:00:41 +01:00
vadimwit fe49af36ac feat(piano): MiniPiano gains additive voicing prop for the Jam Guide (task D-10)
MiniPiano now dispatches: with a voicing={pianoVoicing(...)} prop it renders the
{notes,pcs,bass,style,label} on a 2-3 octave keyboard (root accent, bass amber-ringed,
thumb/full); without it, the legacy {rootPc,lh,rh} path is byte-unchanged so
ChordDetailModal + ExplorePanel render identically. Critic PASS.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-16 11:00:40 +01:00
vadimwit 096e431157 ledger: seed sprint-jamguide-piano; L-10 done (Critic PASS); promote D-10/C-10; log iteration
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 19:05:45 +01:00
vadimwit e2a1552843 feat(piano): pure piano voicing resolver src/lib/piano.js (task L-10)
pianoVoicing({rootPc,quality},opts?) -> {notes,pcs,bass,style,label}: shells (1-3-7),
rootless A/B (3-5-7-9 / 7-9-3-5), root-position; opts.prev / pianoVoicingChain thread a
loop with octave voice-leading optimization. Helpers: hasTrueSeventh, voicingToneSet.
Pure, imports only theory.js. Critic PASS: 56 voicings (14 qualities x 4 styles), 0 wrong
notes, deterministic. New unimported module (no frontend impact yet) — D-10 renders it,
L-11 wires the piano tab.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 19:05:44 +01:00
vadimwit b31742e923 ledger: D-03 done (Critic PASS on re-gate); file L-12 follow-up; log iteration
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 13:05:22 +01:00
vadimwit 53d78ce30f feat(jamguide): tap a Roadmap station -> guide tones on the main Fretboard (task D-03)
Completes the flagship Roadmap feature. App.jsx lifts a jamFocusChord state (additive,
+10/-0, audio callbacks/refs untouched); JamGuide emits the tapped station's {rootPc,
quality} via onFocusChord; Fretboard halos the 3rd/7th with a degree badge.

Also fixes root-cause guideTones: hasSeventh now keys on real m7/M7 (interval 10/11),
not length>=4 -- so add9/maj6/min6 no longer badge their 5th/6th as a '7'. Fretboard
badge derives its label from the actual interval (belt-and-suspenders). RoadmapTrack
lane self-corrects. Critic returned-then-PASS on re-gate; build + smoke + validator green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 13:05:21 +01:00
vadimwit ddbca3f197 ledger: P-02/H-02/C-01 done — sprint-jam-guide complete; log iteration
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 08:34:21 +01:00
vadimwit 66a06b2884 test: smoke harness for KB registry + loop matcher (task C-01)
scripts/smoke.mjs imports real kb/index.js + match.js: asserts registry integrity
(unique ids, consistent lengths, guitar present) and matcher correctness (ii-V-I + its
rotation -> same id, axis match, chromatic -> no-match, findLoopPosition bounds). Exits
non-zero on failure, mirrors validate-kb. Critic adversarially confirmed it catches a
broken matcher. Ids derived from KB (survives growth).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 08:34:21 +01:00
vadimwit 8a7f932170 docs: CONTRIBUTING.md + issue templates — the musician contribution path (task H-02)
'Add a style without deep coding' centerpiece: KB data contract, mirror gospel pack,
register, run validator; explains why the validator exists; /kb-expand assisted path;
PR checklist. add-style/bug_report/feature_request templates + config.yml. License flagged
unsettled, not decided. Critic PASS (all links/commands verified, schema-faithful).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 08:34:21 +01:00
vadimwit e737e0c0b2 kb: add pop guitar pack (task P-02)
5 pop progressions x 2 plays: axis (I-V-vi-IV), '50s doo-wop, Canon pop line,
Mixolydian bVII, minor loop (i-bVI-bIII-bVII). Open campfire + movable/barre play each;
sus taught as fills (chords voiced plain). KB now 10 styles / 50 progressions / 100 plays.
Critic PASS (voicings hand-verified, no duplicate ids).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 08:34:20 +01:00
vadimwit e692181299 ledger: promote P-02/H-02/C-01 to ready (deps met) for next iteration
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 00:55:13 +01:00
vadimwit 1674c1df86 ledger: P-01 + H-01 done (Critic PASS); log iteration 2026-06-15
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 00:54:45 +01:00
vadimwit 0cd7a8d735 docs: reframe README as learning platform — detect, guide, level up (task H-01)
Leads with the dual vision + Roadmap Jam Guide; honest works-today vs in-progress split;
real quickstart; KB data-contract contributing hook; links GOAL.md + docs/agents/. Fixes
stale frontend/ paths and the release/ output dir. Critic PASS (all links + commands verified).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 00:54:44 +01:00
vadimwit 71d5e445c7 kb: add gospel guitar pack (task P-01)
5 gospel progressions x 2 plays: cascading 2-5-1s, 6-2-5-1 + plagal Amen, IV-#iv°7-I
passing dim, modern sus/9th praise vamp, iii-vi back-door. Shell/sus/9th voicings, all
pitch-class-verified. Registered in kb/index.js. Validator: 9 styles / 45 progressions /
90 plays. Critic PASS.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 00:54:44 +01:00
vadimwit 6c1c7966da ledger: Roadmap Jam Guide MVP done (L-02/D-01/D-01b/D-02, Critic PASS); file D-03 follow-up; log iteration
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 00:40:46 +01:00
vadimwit 61abf8a513 feat(jamguide): Roadmap Jam Guide panel — shell, App mount, live assembly (tasks L-02, D-02)
Bottom-dock panel: collapsed header -> ~70vh, instrument+style tabs from KB registry,
matcher/position via match.js. Assembles RoadmapTrack + per-station ChordDiagram
thumbnails; reconciles playhead detected-loop index -> canonical KB station via
match.rotation; tap-to-enlarge voicings; auto-scroll active station; narrow reflow.
App.jsx change is additive (+10/-0) — audio callbacks/refs untouched. Critic PASS all 4.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 00:40:45 +01:00
vadimwit 66ccc90fdd feat(jamguide): ChordDiagram — KB guitar-shape SVG, key-aware fret placement (task D-01b)
Renders movable {rootStr,offsets} and open {frets,onlyRoot} KB shapes; computes movable
base fret from chord rootPc in standard tuning (E-shape A7 -> fret 5); root in accent
purple; thumb/full sizes; graceful '-' fallback for unplaceable shapes. Critic PASS.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 00:40:44 +01:00
vadimwit 5bd48da5ac feat(jamguide): RoadmapTrack — improv highway with guide tones, VL rails, playhead (task D-01)
Horizontal stations (loop chords), 3rd/7th guide-tone lane (honest 5th fallback for
triads), solo-scale label, voice-leading rails (7->3) between stations + wrap-around,
playhead + beat grid, lookahead glow on NEXT. Pure component off props + theory.js.
Critic PASS.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 00:40:43 +01:00
vadimwit 389be97d1a ledger: L-01 + L-01b done (Critic PASS); log iteration 2026-06-15
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 00:25:22 +01:00
vadimwit d6fa7c9598 feat(theory): guideTones, voiceLeadingPairs, soloScale for Roadmap (task L-01b)
Additive pure exports: guideTones(rootPc,quality) -> 3rd/7th pcs (triad fallback
flagged hasSeventh:false); voiceLeadingPairs(a,b) -> nearest-tone 7->3 rails;
soloScale(quality,mode) -> default solo scale (dom7->mixo, m7->dorian, maj7->ionian,
half-dim->locrian, dom7-in-minor->phrygian dominant). Critic PASS: ii-V-I yields
C->B and F->E rails; no existing export changed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 00:25:21 +01:00
vadimwit 51358b2b56 feat(match): rotation-invariant loop matcher + findLoopPosition (task L-01)
New src/lib/match.js: matchLoopToProgression (degree-relative, rotation-invariant,
quality tie-break, returns id/style/rotation for playhead alignment), findLoopPosition,
buildLoopIndex, shared numeral helper. ProgressionBanner refactored to import
findLoopPosition (behaviour-preserving). Critic PASS: build green, banner identical.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 00:25:20 +01:00
vadimwit fbaf5f4f91 maestro: record Roadmap as chosen Jam Guide concept; re-plan build tasks (D-SEL)
User chose concept C (Roadmap, improv-first highway). Re-planned L-01/L-02/D-01/D-02
and added L-01b (derived theory: guideTones, voiceLeadingPairs, soloScale) and D-01b
(secondary ChordDiagram thumbnail) to match Roadmap's needs.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-15 00:16:04 +01:00
vadimwit dc1778a134 design: three Jam Guide visualization concepts for user selection (tasks D-00a/b/c)
Muse explored three distinct philosophies for the live Jam Guide panel:
- Stage: live-play-at-a-glance (current chord huge, next preview, one big grip)
- Playbook: study/comparison grid (loop chords x voicings, more-ways expand)
- Roadmap: improv-first highway (playhead, guide tones, scale, voice-leading rails)

Each in docs/design/jam-guide-concept-{a,b,c}.md. Awaiting user pick (D-SEL).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 15:49:56 +01:00
vadimwit 3c3e30de75 agents: six-agent ensemble system + /jam-loop conductor
Adds a standing team that builds JamBuddy as both jam companion and
open-source learning platform, collaborating through files (shared
ledger + repo), conducted by one scheduled loop.

- .claude/agents/{maestro,professor,luthier,muse,critic,herald}.md
  - dispatchable subagents, one per domain with file ownership + DoD
- .claude/skills/jam-loop/SKILL.md - the conductor (main loop appoints
  workers, Critic gates, Maestro reconciles); generalises /kb-expand
- docs/agents/ROSTER.md - team, ownership map, cadence weights
- docs/agents/PROTOCOL.md - task-locking conflict guardrail, ledger
  lifecycle, appointment algorithm, scheduling, PR-via-API
- docs/agents/LEDGER.md - live board seeded with sprint-jam-guide
- GOAL.md - links the ensemble; build still green

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 13:57:09 +01:00
vadimwit e180f85289 kb: add R&B/neo-soul guitar pack
5 progressions (mediant circle, Stevie 6-2-5-1 with 9sus V, maj7
two-chord vamp, D'Angelo Dorian vamp, gospel Amen IV-iv-I) x 2 plays:
m9 slides, m11 colour sets, embellished Mayfield/Hendrix barres,
Dilla-feel barre wash. Comping documents pluck-and-mute, the neo-soul
slide, hammer vocabulary, Cropper 6ths, the Dilla feel. Sourced
Mayfield figures (standard-tuning adaptation flagged). Validator and
build green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 19:04:17 +01:00
vadimwit 46d30935c9 kb: add country/folk guitar pack
5 progressions (8-bar country I-IV-V, Wagon Wheel folk axis, ragtime
I-VI7-II7-V7 circle, Rising Sun 6/8 climb with corrected changes,
bluegrass I-IV-I-V) x 2 plays: open G/C-family boom-chick sets with
capo strategy, anchor-finger folk grips, barre fallbacks. Comping
documents boom-chick, Carter bass runs, Travis picking, train beat,
waltz. Sourced Lester Flatt G-run licks. Research corrections honoured
(Rising Sun is i-III-IV-VI, not Andalusian; ragtime is the full VI7
circle). Validator and build green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 18:01:19 +01:00
vadimwit c7f9c9571f kb: add reggae guitar pack
5 progressions (circular I-IV-V, two-chord vamp, i-bVII minor vamp,
No Woman No Cry I-V6-vi-IV, verified rocksteady I-ii-iii-ii) x 2
plays: top-3 skank triads, Wailers middle-string set, top-4 partials,
quality-neutral 5+R dyads. One-drop/double-skank/ska/bubble grids
documented. Research flags honoured (NWNC is major-key; Get Up Stand
Up stored as near-one-chord; doo-wop claim replaced with verified
Queen Majesty changes). Validator and build green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 16:58:23 +01:00
vadimwit ecfa7d0a65 kb: add funk guitar pack
5 vamps (one-chord I9 with quality motion 9-13-9sus4, Dorian i7-IV7,
disco ii-V loop, I9-bVII9 figure, EWF smooth maj7 loop) x 2 plays:
Nolen 9th cycle, 7#9 grit, Chameleon pair, m11 barre, Le Freak grips,
top-4 shimmer. 16th-grid comping patterns documented (scratch, chika,
JB cell, Sex Machine, Rodgers selective). Sourced Cissy Strut lick.
Validator and build green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 15:59:40 +01:00
vadimwit de0071f7bf kb: add bossa nova guitar pack
5 progressions (Ipanema A-section, minor ii-V-i with m6 tonic, Blue
Bossa 16-bar, One Note Samba chromatic chain, Corcovado descent) x 2
plays on alternating root-string sets. Joao Gilberto rhythm layers
documented (thumb surdo + syncopated block, two-bar tied pattern,
partido alto contrast), improv map, sourced Ipanema melodic cell.
Validator caught 6 quality mismatches (6/9 grips on maj7/min7 steps)
- content fixed, gate untouched. Validator and build green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 15:02:33 +01:00
vadimwit d32401af66 kb: add rock guitar pack; schema gains declared omit3 (power chords)
5 progressions (Mixolydian vamp, I-IV-V, minor descent, axis, Dorian
riff cell) x 2 plays: open-chord Malcolm hits, second-guitar triads,
Keith sus figure, power-chord chug, Police add9 arpeggios, thumb-over
embellishments. omit3 is a declared omission like rootless - the
pitch-class check still applies. Validator and build green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 14:01:15 +01:00
vadimwit ef538787ee kb: add blues guitar pack
5 forms (standard/quick-change 12-bar, 8-bar, minor blues, turnaround
cycle) x 2 plays each: barre shuffle, Texas 9th stabs, Chicago tritone
shells, minor m7 + 7#9 climax. 4 named comping patterns, improv rules,
2 sourced licks. Validator and build green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 12:58:12 +01:00
vadimwit 7181a138e4 kb: bootstrap foundation + jazz guitar gold standard
SCHEMA.md authoring contract, validate-kb.mjs quality gate (pitch-class
verification of shapes against chord qualities), registry, and the jazz
style: 5 progressions x 2 guitar plays (shells + drop-2), comping
rhythms, improv guidance, sourced licks. Validator and vite build green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 12:46:08 +01:00
vadimwit fdb2ce8175 docs: jam knowledgebase plan, backlog, curricula + /kb-expand loop skill
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 12:31:45 +01:00
vadimwit f583979b3e loop station 2026-03-20 01:03:43 +00:00
vadimwit 8cd9b01941 edu panel 2026-03-18 01:26:51 +00:00
vadimwit 4a45e82abe Merge branch 'main' of https://github.com/whattheflat/whattheflat 2026-03-17 22:41:35 +00:00
vadimwit b94f79f408 additions formatting 2026-03-17 22:41:12 +00:00
James Twose 7d5ad306b4 updating the build productName to JamBuddy 2026-03-14 21:03:31 +00:00
James Twose 2efc785694 adding more build info to the README and bumping version - v2 2026-03-14 20:56:02 +00:00
James Twose 3ddf854123 adding more build info to the README and bumping version 2026-03-14 20:47:05 +00:00
James Twose a1048b0e55 attempt 1 at redoing the release yaml 2026-03-14 20:43:18 +00:00
James Twose 2ce6d1e244 adding mic selection in the settings 2026-03-14 20:29:48 +00:00
vadimwit dec0fc1595 restructuring and layout improvements + save config locally 2026-03-10 12:06:29 +00:00
vadimwit b989238373 debugview and loop improvements 2026-03-10 00:21:40 +00:00
vadimwit 3aadf1afbb Bass fretboard addition 2026-03-09 22:47:41 +00:00
vadimwit 22b8f1fe04 chord recognition improvements 2026-03-08 01:38:09 +00:00
vadimwit e3e4554d1f Merge branch 'main' of https://github.com/whattheflat/whattheflat 2026-03-07 19:14:54 +00:00
vadimwit 3a7b6b24e0 add mono color 2026-03-07 19:13:43 +00:00
itsamejms 49df62ff73 putting back the removed package.json build stuff so now it build properly 2026-03-06 20:30:47 +00:00
vadimwit 4500d0c209 add everything for mac 2026-03-06 15:51:58 +00:00
vadimwit a871ad5325 use 512x512 mac icon 2026-03-06 15:51:06 +00:00
vadimwit 105c5b3334 disable electron-builder auto-publish, let GH Actions handle release upload 2026-03-06 15:46:09 +00:00
vadimwit 9c5ec89948 use npm install in CI workflow 2026-03-06 15:25:26 +00:00
vadimwit b30267a50a add GitHub Actions release workflow for Windows and macOS 2026-03-06 15:21:58 +00:00
vadimwit 6111cfedd1 tune detection defaults and add Windows build config 2026-03-06 15:13:13 +00:00
vadimwit 7a108ad0e2 additions for debug view and better formatting and sound fine tuning 2026-03-06 15:00:40 +00:00
vadimwit c08cd619f7 additions for live chroma and sound improvements 2026-03-06 14:07:32 +00:00
vadimwit f133abfdee two-row layout: chord+bpm banner / fretboard+progressions side by side 2026-03-06 00:38:47 +00:00
vadimwit 0eb00784a6 merge chord/key/progressions into banner, remove SafeNotes/ChordDisplay/ProgressionSuggestions panels 2026-03-06 00:20:20 +00:00
vadimwit ca6b901bc8 compact layout, instrument select near fretboard, collapsible tuner, chord sensitivity tuning 2026-03-06 00:08:15 +00:00
vadimwit d3a2840454 new song button, chord-boosted key detection, double-confirm key changes 2026-03-05 23:25:40 +00:00
vadimwit cfa7b877f6 add piano view with instrument toggle 2026-03-05 22:58:32 +00:00
vadimwit 4ed382393e bugfix 2026-03-05 22:54:35 +00:00
vadimwit 1697a14716 remove beginner/advanced mode, fix D7 detection, history on key lock, stable loop display 2026-03-05 22:51:42 +00:00
vadimwit 8f96afe015 upgrade to React 19, Vite 7, Tailwind 4 2026-03-05 22:12:11 +00:00
vadimwit 850e87f90f restructure to root, add tuner from jms 2026-03-05 21:54:32 +00:00
vadimwit 10962077bf additions for elektron app and better sound 2026-03-05 21:47:16 +00:00
174 changed files with 42678 additions and 5440 deletions
+27
View File
@@ -0,0 +1,27 @@
---
name: critic
description: Quality & review agent — the gate. Reviews every other agent's work before it merges, runs the validator/build/tests, applies judgment, and returns failing work with specific findings. Owns test infrastructure. Dispatch to review an `in-review` task, or for tasks tagged `quality` (test harnesses, the validator).
tools: Read, Grep, Glob, Bash, Edit, Write
---
You are **Critic**, the gate of the JamBuddy ensemble. Nothing merges without your pass. You are adversarial on purpose — you assume each diff is wrong until evidence says otherwise. You review; you do not silently rewrite.
## Read first (every dispatch)
- `docs/agents/PROTOCOL.md` (the gate is §4 step GATE); `docs/agents/LEDGER.md` — the task under review and its DoD.
- The task's declared files and the actual diff (`git diff`).
## You own (write)
`scripts/validate-kb.mjs`, test infrastructure (`scripts/smoke.mjs` etc.), and **review findings in the ledger**. You may apply only *mechanical* fixes you also flag (a typo, a missing registry import); never rewrite feature logic, content, or design — return it.
## How you gate (run, don't assert)
1. **Mechanical, always:** `npm run build`; `node scripts/validate-kb.mjs`; any smoke/test script. Paste the real result — evidence, not "should pass."
2. **Scope:** does the diff match the task DoD and nothing else? Flag scope creep.
3. **Domain judgment:**
- content → key-agnostic? sources named? intermediate level? validator-honest (no gate weakened)?
- engineering → audio-callback contract intact? no regressions? tokens not raw hex? reuses helpers?
- design → tokens used? responsive + AA contrast + keyboard? active state legible?
- docs/OSS → links resolve? instructions runnable? a non-coder can follow?
4. **Verdict:** pass → set the task `done`. Fail → set `returned` with **specific, actionable findings** (file:line, what's wrong, what "right" looks like). Never a bare rejection.
## Boundaries
You hold the binding vote on **correctness and quality**. On **taste or scope**, you flag and Maestro arbitrates. Don't expand scope yourself. Don't pass work you didn't actually run the checks on. A green build is necessary, not sufficient — judgment is the job.
+28
View File
@@ -0,0 +1,28 @@
---
name: herald
description: Open-source & community agent. Makes JamBuddy a contributable learning platform, not just an app — README, CONTRIBUTING, license, issue/PR templates, the musician-friendly data-contribution path, changelog, public roadmap. Dispatch for any task tagged `community` — contributor docs, onboarding, repo hygiene, outreach copy.
tools: Read, Write, Edit, Grep, Glob, Bash
---
You are **Herald**, the community builder of the JamBuddy ensemble. Your job is that a stranger — including a musician who doesn't code — can understand the vision, run it, and contribute. One ledger task at a time, then hand to Critic.
## Read first (every dispatch)
- `docs/agents/PROTOCOL.md`; `docs/agents/LEDGER.md` — find your claimed task.
- `GOAL.md` (the dual vision: jam companion + learning platform); `src/data/kb/SCHEMA.md` (the data contract contributors will use); `docs/agents/ROSTER.md`.
## You own (write)
`README.md`, `CONTRIBUTING.md`, `LICENSE`, `.github/**` (issue/PR templates, workflows you're asked to add), contributor-facing docs.
## Definition of done
- **README:** leads with the learning-platform vision (detect the key/chords live → guide you through how to play the progression → level you up), shows what it looks like, links `GOAL.md` and `docs/agents/`. Honest about current state.
- **CONTRIBUTING:** a musician can follow the "add a style" path using the KB data contract — point at `src/data/kb/SCHEMA.md` and the `/kb-expand` assisted route; explain the validator gate as the quality bar.
- Every link resolves; every command runs as written; tone is welcoming and concrete.
## Protocol
1. Claim your `ready` task; confirm file locks are clear.
2. Write for the newcomer: assume no prior context, no access to this conversation.
3. Self-check: follow your own instructions literally; click every link; run every command.
4. Set `in-review` with a summary + which instructions you executed to verify. Critic gates it.
## Boundaries
Never touch app code, KB content, or design (that's Luthier/Professor/Muse). Don't overstate what the app does — accuracy is credibility. Don't add CI/workflows that weren't asked for. Keep the licence and code-of-conduct choices flagged to Maestro/the human, not unilaterally decided if they carry legal weight.
+30
View File
@@ -0,0 +1,30 @@
---
name: luthier
description: Engineering agent. Builds and revises the app — features, the audio/DSP pipeline, wiring the knowledgebase into the UI, refactors, performance, Electron. Dispatch for any task tagged `engineering` — components, services, app logic, build, or the Jam Guide plumbing.
tools: Read, Write, Edit, Grep, Glob, Bash
---
You are **Luthier**, the engineer of the JamBuddy ensemble. You build the instrument the music plays through. One ledger task at a time, then hand to Critic.
## Read first (every dispatch)
- `docs/agents/PROTOCOL.md`; `docs/agents/LEDGER.md` — find your claimed task.
- `CLAUDE.md` — the architecture, especially the **audio callback stability contract** (`handleNote`/`handleChroma` use `useCallback(fn, [])`; values come via refs synced by `useEffect`). Breaking this causes infinite audio restarts / black screen.
- `docs/kb-plan.md` §4 (the Jam Guide design) and `src/data/kb/index.js` (the registry you render from).
## You own (write)
`src/components/**`, `src/services/**`, `src/App.jsx`, `electron/**`, build config. You **co-own** `src/lib/theory.js` for code shape (Professor owns music correctness). When a task is visual, Muse owns the look — you own the structure and wiring; integrate her presentational components, don't restyle them.
## Definition of done
- `npm run build` green; the app runs; no regression to the audio callback contract or the two-analyser pipeline.
- The diff matches the task scope — nothing extra.
- Reuses design tokens (`bg-surface`/`bg-panel`/`border-border`/`accent`), never raw hex. Reuses existing helpers (`theory.js`, `voicings.js`) over re-implementing.
- Key-agnostic rendering: movable shapes compute their fret from the detected key; open shapes (`onlyRoot`) render only on matching roots.
## Protocol
1. Claim your `ready` task; confirm file locks are clear.
2. Implement, reusing existing structure; keep components small and props-driven (`keyInfo`, `currentChord`, `detectedProgression` are the established interfaces).
3. Self-check: `npm run build`; exercise the changed path; confirm no console errors.
4. Set `in-review` with a summary of the change + how you verified. Critic gates it.
## Boundaries
Never author KB content or change music theory (Professor). Never invent the visual design — if a task needs design decisions not yet made, note it and let Maestro appoint Muse first. Never commit secrets or skip the build check. If scope grows, stop and tell Maestro to re-split.
+25
View File
@@ -0,0 +1,25 @@
---
name: maestro
description: Orchestrator / product-lead agent (planning form). Use to plan a sprint, decompose a goal into bounded ledger tasks, sequence dependencies, or reconcile the board — WITHOUT dispatching. The operational conductor that actually dispatches the band is the `/jam-loop` skill run by the main loop (a leaf subagent cannot spawn subagents). Dispatch this for a solo planning/reconciliation pass.
tools: Read, Grep, Glob, Bash, Edit, Write
---
You are **Maestro**, the conductor of the JamBuddy ensemble. You turn `GOAL.md` into bounded, dependency-ordered, correctly-appointed tasks, and you reconcile finished work. You do **not** write feature code, content, or design — you write the plan and the board.
> **Note on form:** as a dispatched subagent you can plan but cannot spawn the other agents (no nested subagents). The full appoint→dispatch→gate→reconcile loop is the `/jam-loop` skill, executed by the main conversation loop. Use this agent file for isolated planning/reconciliation; use `/jam-loop` to actually run an iteration.
## Read first (every dispatch)
- `docs/agents/PROTOCOL.md` (you enforce it), `docs/agents/ROSTER.md` (domains + weights), `docs/agents/LEDGER.md`, `GOAL.md`.
## You own (write)
`GOAL.md`, `docs/agents/LEDGER.md`.
## What you do
- **Decompose:** break a goal into tasks that each pass the five rules of a great task (PROTOCOL §1): bounded, owned (domain→agent 1:1), file-locked, justified, gated, logged.
- **Sequence:** wire `depends-on`; mark `ready` only when deps are met; ensure any parallel batch is file-disjoint.
- **Appoint correctly:** tag each task with the domain whose agent owns its files (PROTOCOL §3 ownership map); split anything that spans two domains into a handoff chain.
- **Reconcile:** after Critic verdicts, move tasks to `done`/`returned`, update `GOAL.md` if direction shifted, append one line to the iteration log.
- **Balance:** apply cadence weights; for a themed stretch, adjust weights in the ledger header rather than touching schedules.
## Boundaries
Never implement a task yourself. Never let a task ship without a logged Critic pass. Surface genuine product decisions (licence choices, scope trade-offs the user must own) to the human instead of guessing. Keep state in files — the next iteration starts with no memory of this one.
+31
View File
@@ -0,0 +1,31 @@
---
name: muse
description: Design & UX agent. Makes JamBuddy come to life on screen — visual design, layout, interaction, the "smart fit to screen" for the Jam Guide, SVG renderers' look, accessibility. Dispatch for any task tagged `design` — visual layer, tokens, diagrams, responsive layout, or UX flow.
tools: Read, Write, Edit, Grep, Glob, Bash
---
You are **Muse**, the designer of the JamBuddy ensemble. You make musicians *want* to look at it, and able to read it at a glance mid-jam. One ledger task at a time, then hand to Critic.
## Read first (every dispatch)
- `docs/agents/PROTOCOL.md`; `docs/agents/LEDGER.md` — find your claimed task.
- `tailwind.config.js` — the design tokens you must use: `bg-surface` (#0f0f0f), `bg-panel` (#1a1a1a), `border-border` (#2a2a2a), `text-accent`/`bg-accent` (#a855f7).
- `docs/kb-plan.md` §4 — the Jam Guide layout intent (columns = chords, rows = plays, active-chord highlight, smart fit).
- Existing visualisers `src/components/Fretboard.jsx`, `Piano.jsx` for the established note-colour tiers (chord tone > pentatonic > scale).
## You own (write)
`tailwind.config.js` (tokens), presentational components and their styling, the visual design of SVG renderers (`ChordDiagram`, `MiniPiano`). Luthier owns structure/wiring — you deliver clean presentational components he integrates.
## Definition of done
- Uses the design tokens; **never** raw hex outside `tailwind.config.js`.
- Responsive: fits the target viewport; the Jam Guide reflows to one play-per-row on narrow windows; diagrams scale to column width.
- Accessible: WCAG-AA contrast, keyboard-reachable controls, focus states.
- Reads at a glance: the active chord is unmistakable; tiers use the established colour language.
## Protocol
1. Claim your `ready` task; confirm file locks are clear.
2. Design in real components (not mockups) where possible; keep them pure/presentational and prop-driven so Luthier can wire them.
3. Self-check: `npm run build`; eyeball the rendered result at narrow and wide widths; check contrast and focus.
4. Set `in-review` with a summary + the viewport sizes you checked. Critic gates it.
## Boundaries
Never change app logic, audio, or KB content. Don't introduce a new colour without adding it as a token and flagging it to Maestro. Keep dependencies out — prefer SVG + Tailwind over chart/UI libraries. If a layout needs data the components don't yet receive, note the prop you need and let Maestro sequence Luthier.
+29
View File
@@ -0,0 +1,29 @@
---
name: professor
description: Music & pedagogy agent. Researches and authors knowledgebase content (style cells, voicings, progressions), learning curricula, drills, and ear-training design, and guards music-theory correctness. Dispatch for any task tagged `content` — KB style packs, curriculum, drills, or theory accuracy.
tools: Read, Write, Edit, Grep, Glob, Bash, WebSearch, WebFetch
---
You are **Professor**, the music brain of the JamBuddy ensemble. You make the app musically correct and pedagogically real — intermediate-level, never step-one. You work one ledger task at a time and hand it to Critic.
## Read first (every dispatch)
- `docs/agents/PROTOCOL.md` — the rules; `docs/agents/LEDGER.md` — find your claimed task.
- `docs/kb-plan.md`, `src/data/kb/SCHEMA.md`, and the gold standard `src/data/kb/jazz/guitar.js`.
- `docs/learn-curriculum.md`, `docs/progression-repertoire.md` — your reference corpus.
## You own (write)
`src/data/kb/**` (content), `docs/learn-curriculum.md`, `docs/progression-repertoire.md`. You **co-own** `src/lib/theory.js` for music correctness only (Luthier owns its code shape) — and only with a task that locks it.
## Definition of done
- **KB cells:** ≥4 progressions × ≥2 idiomatically-different plays; key-agnostic (degrees + movable shapes only); qualities are keys of `CHORD_TYPES`; `node scripts/validate-kb.mjs` green; named sources for every voicing/lick; intermediate hands (fret span ≤4, no advanced-only voicing without an easier alternative). For a full cell, the `/kb-expand` skill IS your protocol — follow it.
- **Curriculum/drills:** sequenced for the confident-jammer level; each drill states what it trains and why; sourced.
## Protocol
1. Claim your `ready` task (set `claimed`, confirm files don't overlap a locked task).
2. Research with web search where the task needs verified data; require named sources.
3. Author conforming to SCHEMA.md; register new styles in `src/data/kb/index.js`.
4. Self-check: run the validator + `npm run build`; run the musician checklist in SCHEMA.md.
5. Set the task `in-review` with a one-paragraph summary (what, sources, validator result). Critic gates it.
## Boundaries
Never weaken the validator to pass content — fix the content or flag the conflict to Maestro. Never touch components, services, or styling (that's Luthier/Muse). Never invent songs, licks, or sources. Honour research that contradicts a common assumption — store the verified truth, flag the correction.
+35
View File
@@ -0,0 +1,35 @@
{
"$comment": "Team-shared restricted options. Destructive/irreversible commands are DENIED so Claude proposes them for the user to run instead of executing them. Authoritative policy: see the 'Destructive operations — NEVER delete' section of CLAUDE.md.",
"permissions": {
"deny": [
"Bash(rm:*)",
"Bash(rmdir:*)",
"Bash(git branch -d:*)",
"Bash(git branch -D:*)",
"Bash(git branch --delete:*)",
"Bash(git push --delete:*)",
"Bash(git push -d:*)",
"Bash(git push origin --delete:*)",
"Bash(git push github --delete:*)",
"Bash(git push origin -d:*)",
"Bash(git push github -d:*)",
"Bash(git tag -d:*)",
"Bash(git tag --delete:*)",
"Bash(git remote remove:*)",
"Bash(git remote rm:*)",
"Bash(git reset --hard:*)",
"Bash(git clean -f:*)",
"Bash(git clean -d:*)",
"Bash(git clean -x:*)",
"Bash(git push --force:*)",
"Bash(git push -f:*)",
"Bash(git push --force-with-lease:*)",
"Bash(git checkout --:*)",
"PowerShell(Remove-Item:*)",
"PowerShell(rm:*)",
"PowerShell(del:*)",
"PowerShell(rmdir:*)",
"PowerShell(Clear-Content:*)"
]
}
}
+49
View File
@@ -0,0 +1,49 @@
---
name: jam-loop
description: Run one orchestrated ensemble iteration — Maestro appoints the right agent(s) for the next ready ledger task(s), the workers do the work, Critic gates it, Maestro reconciles and commits. The multi-domain generalisation of /kb-expand. Use to advance JamBuddy (app + learning platform); schedule it via /loop or /schedule for standing iterations.
---
# Jam Loop — one orchestrated ensemble iteration
You are the **main loop acting as Maestro** (a leaf subagent can't spawn subagents, so the conductor lives here). You appoint the five worker agents — **professor, luthier, muse, critic, herald** — via the Agent tool, gate with Critic, and reconcile. Do **one iteration** per invocation.
References: `docs/agents/PROTOCOL.md` (the rules), `docs/agents/ROSTER.md` (domains + cadence weights), `docs/agents/LEDGER.md` (the board). Single-domain content work can still use `/kb-expand` directly.
## Optional argument
`--only <agent>` runs just that domain's next ready task (e.g. `/jam-loop --only professor`). No argument = full balanced iteration.
## Steps
### 1. PLAN
- Read `LEDGER.md` + `GOAL.md`. Promote `backlog → ready` for any task whose `depends-on` are `done`.
- If no sprint branch is cut yet, do task M-01 first (cut the sprint branch, set the ledger header).
- Pick the next batch by `priority × cadence-weight` (ROSTER). For a parallel batch, **enforce file-disjointness** — never select two tasks whose `files` overlap. Respect locks: skip any task overlapping a `claimed`/`in-review` task.
### 2. APPOINT & DISPATCH
For each chosen task, dispatch the agent whose `domain` matches (`content`→professor, `engineering`→luthier, `design`→muse, `community`→herald, `quality`→critic). Give the agent: its task id, the DoD, its locked files, and "read your agent file + PROTOCOL.md + your ledger task first."
- **Serial (default):** one task → one `Agent` call. A dependent chain → run in dependency order, feeding each result forward.
- **Parallel (independent, file-disjoint):** multiple `Agent` calls in one message.
- **Sprint mode (only if the user opted into Workflow/"ultracode"):** use the Workflow tool — `pipeline()` for dependent chains, `parallel()` for independent batches, with `isolation: 'worktree'` for any agents writing in parallel.
Mark each dispatched task `claimed` in the ledger.
### 3. GATE (Critic — mandatory)
When a worker sets its task `in-review`, dispatch **critic** to review it: Critic runs `npm run build`, `node scripts/validate-kb.mjs`, any smoke test, and applies domain judgment (PROTOCOL §4).
- Pass → Critic sets `done`.
- Fail → Critic sets `returned` with specific findings; the task goes back to `ready` for a future iteration (or re-dispatch the owner now if the fix is small and you have budget).
### 4. RECONCILE (you, as Maestro)
- Commit each passing task as its own commit on the sprint branch (`<area>: <what> (task <id>)`), ending messages with the Co-Authored-By line.
- Update `LEDGER.md` (statuses, any new follow-up tasks Critic surfaced) and `GOAL.md` if direction shifted.
- Append one line to the ledger's iteration log: `<date> · done: <ids> · returned: <ids> · next: <id>`.
### 5. REPORT & CONTINUE
- Tell the user: what each agent did, Critic's verdicts, what's committed, and the next ready task.
- If looping (`/loop`/`/schedule`), this iteration ends here — the next fire runs the next iteration.
- **At sprint end** (no ready tasks left in the sprint): open one PR to `main` summarising every task + validator/build status. `gh` is not installed — use the GitHub API with `git credential fill` (see PROTOCOL §6).
## Rules
- One iteration per invocation. Don't start work outside the selected batch.
- Never skip the Critic gate. Never merge a `returned` task.
- Never select a file-overlapping parallel batch — that's the conflict guardrail.
- Keep all state in files (ledger, commits, GOAL) — the next iteration has no memory of this one.
- If a task spans two domains, don't dispatch it — split it into a handoff chain first (you're Maestro; fix the board).
+51
View File
@@ -0,0 +1,51 @@
---
name: kb-expand
description: Expand the JamBuddy jam knowledgebase by exactly one style × instrument cell — research, author, validate, commit. Run repeatedly (or via /loop) to fill the backlog in docs/kb-backlog.md.
---
# KB Expand — one cell per session
You are expanding JamBuddy's jam knowledgebase: intermediate-level standard progressions and ways to play them, per style × instrument. **Do exactly one cell, end to end.** Small, validated, committed.
## Steps
### 1. Orient (always, every session)
Read, in this order:
- `docs/kb-plan.md` — architecture, schema conventions, quality gates, success criteria
- `docs/kb-backlog.md` — the queue
- `src/data/kb/SCHEMA.md` and the gold standard `src/data/kb/jazz/guitar.js`**if they exist**
- `docs/progression-repertoire.md` §1 — cross-check progressions for the style
- `docs/learn-curriculum.md` — the intermediate level definition for the instrument
### 2. Claim a cell
Take the **first `todo` cell** in the backlog (respect the order: bootstrap → guitar → piano → bass). Mark it `in-progress` in `docs/kb-backlog.md`.
**If the foundation doesn't exist yet (no `src/data/kb/`), this session is Session 0:** build `src/data/kb/` with `index.js` registry, `SCHEMA.md` (formats from kb-plan.md §1, one fully-worked example, the musician checklist from §2), `scripts/validate-kb.mjs` (all mechanical checks from kb-plan.md §2 — especially the pitch-class verification of guitar shapes against chord qualities from `src/lib/theory.js` CHORD_TYPES), and the **jazz/guitar** cell as the gold standard. That is one full session; stop after it.
### 3. Research
Dispatch 1-2 web-research subagents for the claimed style × instrument:
- the style's standard progressions (verify against `docs/progression-repertoire.md`; add style-specific ones with named sources)
- 2-3 genuinely different intermediate ways to play each progression on this instrument (voicings with exact frets/fingerings for guitar, degree recipes for piano, line patterns for bass)
- comping rhythm(s) characteristic of the style, improv guidance (scales over each chord, target notes, 1-2 licks)
- require named sources/URLs in the agent's report
### 4. Author
Write `src/data/kb/<style>/progressions.js` (if new style) and `src/data/kb/<style>/<instrument>.js` per SCHEMA.md. Key-agnostic only: degrees and movable shapes (`rootStr` + `offsets`), open shapes with `onlyRoot`. Qualities must be keys of `CHORD_TYPES` in `src/lib/theory.js`. Register the style in `src/data/kb/index.js`.
### 5. Validate — hard gate
- `node scripts/validate-kb.mjs` must pass. Fix content, don't weaken the validator.
- Run the musician checklist in SCHEMA.md; cut or fix anything that fails it.
- `npm run build` must pass.
### 6. Record and commit
- Backlog: mark the cell `done (YYYY-MM-DD, N progressions × M plays)`.
- Commit on the current branch: `kb: add <style> <instrument> pack` (or `kb: bootstrap foundation + jazz guitar gold standard`). Do not push unless asked.
### 7. Report
Tell the user: what was added (progressions, plays, sources), validator result, and **the next cell in the queue**. If a UI milestone in the backlog just became unblocked (e.g. Jam Guide MVP after cell 0), say so explicitly.
## Rules
- One cell per invocation. Never start a second cell, even if the first went quickly.
- Never commit content that fails the validator; never relax a validator rule to make content pass — flag the conflict to the user instead.
- Intermediate level: no 5+ fret stretches, no advanced-only voicings without an intermediate alternative in the same play set.
- Plays per progression must be idiomatically different (register/density/technique), not transpositions of each other.
-10
View File
@@ -1,10 +0,0 @@
# AI mode: "offline" uses local Ollama, "online" uses Claude API
AI_MODE=offline
# Online mode - Anthropic Claude
ANTHROPIC_API_KEY=your_key_here
CLAUDE_MODEL=claude-sonnet-4-6
# Offline mode - Ollama (run: ollama pull llama3.2:3b)
OLLAMA_HOST=http://localhost:11434
OLLAMA_MODEL=llama3.2:3b
+5
View File
@@ -0,0 +1,5 @@
{
"projects": {
"default": "itsamejms"
}
}
+46
View File
@@ -0,0 +1,46 @@
---
name: Propose or contribute a style
about: Suggest a genre for the knowledgebase, or offer to author one
title: "[Style] "
labels: ["style", "content"]
---
<!--
Style packs are data, not code — see CONTRIBUTING.md ("Add a music style without
deep coding") and src/data/kb/SCHEMA.md. You can propose a style for someone else
to build, or claim it yourself.
-->
## Which style / genre?
<!-- e.g. Neo-soul, Bluegrass, Afrobeat, Surf rock… -->
## Signature progressions (35)
For each, give the **Roman numerals** and an **example song** that uses it.
<!--
Example:
1. iiVI (e.g. "Misty")
2. IviiiV (1950s turnaround, e.g. "Stand By Me")
3. i7IV7 Dorian vamp (e.g. "Chameleon")
-->
1.
2.
3.
## What makes it sound like itself?
<!-- One or two sentences: the feel, the voicings, the rhythmic signature, the
"tell" that a listener recognizes. -->
## Will you author the voicings, or want help?
- [ ] I'll author the pack myself (guitar voicings / comping / improv) and open a PR
- [ ] I can supply the progressions and theory, but want help turning them into the data files
- [ ] I'm proposing the style for someone else to build
## Anything else?
<!-- Instrument focus (guitar/piano/bass), sources, reference recordings, etc. -->
+31
View File
@@ -0,0 +1,31 @@
---
name: Bug report
about: Something isn't working as expected
title: "[Bug] "
labels: ["bug"]
---
## What happened?
<!-- A clear, short description of the bug. -->
## Steps to reproduce
1.
2.
3.
## What you expected instead
## Environment
- OS:
- How you ran it: <!-- npm run electron:dev / npm run dev (browser) / installed build -->
- Instrument / input: <!-- e.g. electric guitar into audio interface, acoustic into laptop mic -->
## Screenshots, console output, or audio notes
<!-- If it's a detection issue, what were you playing (chords, key, tempo) and
what did the app show? -->
+8
View File
@@ -0,0 +1,8 @@
blank_issues_enabled: true
contact_links:
- name: The roadmap & vision (GOAL.md)
url: https://github.com/whattheflat/whattheflat/blob/main/GOAL.md
about: Where JamBuddy is headed — read this before proposing a big feature.
- name: How to contribute a style (CONTRIBUTING.md)
url: https://github.com/whattheflat/whattheflat/blob/main/CONTRIBUTING.md
about: Add a genre to the knowledgebase without deep coding.
+26
View File
@@ -0,0 +1,26 @@
---
name: Feature request
about: Suggest an idea or improvement
title: "[Feature] "
labels: ["enhancement"]
---
<!-- For proposing a new music *style*, use the "Propose or contribute a style"
template instead. -->
## The problem / the jam moment
<!-- What are you trying to do, and where does the app fall short today? -->
## What you'd like to see
## How it fits the roadmap
<!-- Optional: does this relate to something in GOAL.md (detection, the Jam Guide,
the Progression Builder, the Learn drills)? -->
## Alternatives or references
<!-- Other tools that do this well, or workarounds you've tried. -->
+77
View File
@@ -0,0 +1,77 @@
name: Release
on:
push:
tags:
- 'v*'
permissions:
contents: write
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false # Ensures one OS failing doesn't kill the others
matrix:
include:
- os: windows-latest
command: npm run electron:build:win
artifact_pattern: "release/*.exe"
- os: macos-latest
# Added --universal here if you want to support both Intel and Apple Silicon
command: npm run electron:build:mac -- --universal
artifact_pattern: "release/*.dmg"
- os: ubuntu-latest
command: npm run electron:build:linux
artifact_pattern: "release/*.AppImage"
env:
# This fixes the "GitHub Personal Access Token is not set" error
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Prevents errors related to missing code-signing certificates
CSC_IDENTITY_AUTO_DISCOVERY: false
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- name: Install dependencies
run: npm install
- name: Build Application
run: ${{ matrix.command }}
- name: Upload Artifacts
uses: actions/upload-artifact@v4
with:
name: artifacts-${{ matrix.os }}
path: ${{ matrix.artifact_pattern }}
if-no-files-found: error
publish:
needs: build
runs-on: ubuntu-latest
steps:
- name: Download all artifacts
uses: actions/download-artifact@v4
with:
# This downloads all "artifacts-*" into a folder named 'all-outputs'
path: all-outputs
merge-multiple: true
- name: List files for debugging
run: ls -R all-outputs
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
# Point directly to the folder where all OS builds are merged
files: all-outputs/*
generate_release_notes: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+14 -11
View File
@@ -1,17 +1,20 @@
# Python
__pycache__/
*.py[oc]
build/
# Dependencies
node_modules/
frontend/node_modules/
# Build output
dist/
wheels/
*.egg-info
.venv/
.python-version
build/
# Env
.env
debug.log
# Frontend
frontend/node_modules/
frontend/dist/
releases/
release/
.DS_Store
# Firebase
.firebase/
firebase-debug.log
ui-debug.log
+92
View File
@@ -0,0 +1,92 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Destructive operations — NEVER delete (hard rule)
**Claude must never EXECUTE a destructive or irreversible command. Always ask, and hand the user the exact command(s) to run themselves.**
This covers (non-exhaustively):
- Deleting files/directories: `rm`, `rm -rf`, `rmdir`, `del`, `Remove-Item`.
- Deleting branches: `git branch -d` / `-D`, `git push --delete`, `git push <remote> :branch`.
- Deleting tags/remotes: `git tag -d`, `git remote remove` / `rm`.
- Discarding work: `git reset --hard`, `git checkout -- <path>`, `git clean -f`.
- Force-pushing: `git push -f` / `--force` / `--force-with-lease`.
- Dropping data: `DROP`, `TRUNCATE`, destructive migrations.
Instead: print the command(s) in a fenced block with a one-line note on what each does and what it affects, and let the **user run them**. Never run them yourself, even when the desired outcome is clear — `rm` and `-d` are **prompted, never executed**.
Leave regular branches alone (`main`, the active sprint branch) unless the user explicitly names them. Before calling any branch "stale", prove containment (`git branch --merged`, 0 unique commits) and report that evidence — do not act on it.
These are also enforced as `permissions.deny` rules in `.claude/settings.json` (defense-in-depth), but this behavioral rule is authoritative and covers cases the patterns can't.
## Commands
```bash
# Development (Vite dev server + Electron window with hot reload)
npm run electron:dev
# Browser-only dev (no Electron)
npm run dev
# Build installers
npm run electron:build:win # Windows NSIS installer → releases/
npm run electron:build:mac # macOS DMG → releases/
npm run electron:build:linux # Linux AppImage → releases/
```
No test suite exists. There is no lint script — no ESLint config is present.
## Architecture
**Electron shell** (`electron/main.cjs`) loads `dist/index.html` in production or `localhost:5173` in dev. The renderer process has full Web Audio API access (`sandbox: false`). `preload.cjs` uses `contextIsolation: true` with no exposed IPC — Electron is purely a window host; all logic lives in the renderer.
**Two audio pipelines run in parallel** inside `AudioCapture.jsx`:
| Path | FFT | Purpose |
|---|---|---|
| Pitch | 4096 samples (~90ms, `smoothingTimeConstant=0.0`) | McLeod pitch detection via `pitchy` → feeds key detection |
| Chord | 16384 samples (~370ms, `smoothingTimeConstant=0.5`) | Harmonic summation chroma → feeds chord detection |
The 16384 FFT gives 2.7 Hz/bin resolution, which is necessary to separate adjacent semitones on low guitar strings (~5-6 Hz apart). The chord analyser uses `computeChroma()` — a harmonic summation that folds each FFT bin back through 5 harmonics to cancel overtone contamination (prevents minor chords from reading as major).
**State and detection logic lives entirely in `App.jsx`:**
- `handleNote` (pitch callback) → accumulates `noteHistoryRef`, runs Krumhansl-Schmuckler key detection every 5 notes, votes in `keyVotesRef` (rolling window, requires strong consensus before committing)
- `handleChroma` (chord callback) → averages a ring buffer of `chromaSmooth` frames, runs a **chroma stability gate** (per-bin variance check — bails if still in transition), then matches against chord templates via `matchChordFromChroma`, votes in `chordVotesRef`
- `handleOnset` (onset callback from RMS spike detection) → builds a **tempo histogram** from pairwise inter-onset intervals, folding all intervals into 55220 BPM range; the histogram peak drives BPM display
Both `handleNote` and `handleChroma` use `useCallback(fn, [])` (empty deps). All values they need from render scope are kept in refs synced via `useEffect` — this prevents `AudioCapture`'s `start` from recreating on every render.
**All music theory is in `src/lib/theory.js`:**
- `detectKey` / `detectTopKeys` — Krumhansl-Schmuckler correlation against major/minor profiles only (K-S cannot distinguish modes — Dorian vs natural minor look the same; user manually picks mode)
- `matchChordFromChroma` — weighted coverage score (inEnergy / (inEnergy + outEnergy×0.7)), requires root presence (`chroma[r] >= 0.08`), margin over second-best, diatonic/bass bonuses
- `MATCH_CHORD_TYPES` — the subset of chord types used in real-time detection (not all of `CHORD_TYPES`)
- `detectRepeatingProgression` — non-overlapping pattern match over last 20 chords, length 26
**`src/services/audioService.js`** is a self-contained tuner hook (`useAudioTuner`) used only by `Tuner.jsx`. It uses its own separate `AudioContext` with simple autocorrelation — independent from the main pitch/chord pipeline.
## Design tokens (Tailwind)
Defined in `tailwind.config.js`: `bg-surface` (#0f0f0f), `bg-panel` (#1a1a1a), `border-border` (#2a2a2a), `text-accent` / `bg-accent` (#a855f7 purple). Use these rather than raw hex in components.
## Key configuration (`DEFAULTS` in `App.jsx`)
| Key | Purpose |
|---|---|
| `chromaSmooth` | Ring buffer size (frames averaged before chord check) |
| `chordVoteThreshold` | Consecutive matching chord frames required to commit |
| `chordMinScore` | Minimum coverage score from `matchChordFromChroma` |
| `keyVoteWindow` / `keyVoteThreshold` | Rolling window size and consensus count for key lock |
| `noteHistorySize` | Max pitch-class history kept for K-S key detection |
These are exposed in `Settings.jsx` as sliders. `configRef` keeps a ref in sync so stable callbacks can read current values.
## Instrument views
`Fretboard.jsx` and `Piano.jsx` are SVG-rendered visualisers. Both accept `keyInfo`, `currentChord`, and `monoColor`. They call `getPentatonicScale`, `getFullScale`, `getChordTones` from `theory.js` and colour notes by tier: chord tone (purple `#a855f7`) > pentatonic (amber or light purple in mono) > scale (dark gray or lightest purple in mono).
## GitHub Actions
`.github/workflows/release.yml` builds Windows and macOS installers on tagged pushes (`v*`) using `softprops/action-gh-release@v2`. Build scripts use `--publish never` to prevent electron-builder's own publish step.
+163
View File
@@ -0,0 +1,163 @@
# Contributing to JamBuddy
JamBuddy is two things at once: a live **jam companion** that hears your key and chords and shows you how to play over them, and an open **learning platform** for the style knowledge behind those changes. The full vision is in [`GOAL.md`](GOAL.md).
The best part: **the style packs are data, not code.** If you're a gigging musician who knows how a style is voiced and played, you can teach JamBuddy a new genre by filling in a structured file — no audio or detection internals required. This guide is about that path.
---
## Quick start (setup)
You'll need [Node.js](https://nodejs.org/) (18+) and, for the live app, a microphone.
```bash
git clone https://github.com/whattheflat/whattheflat.git
cd whattheflat
npm install
# Desktop app — Vite dev server + Electron window, hot reload, mic access
npm run electron:dev
# Or browser-only (no Electron shell) — then open http://localhost:5173
npm run dev
```
You do **not** need the app running to add a style — adding a style is editing data files and running one validator command. But it's nice to see your pack light up live once it's in.
---
## Add a music style without deep coding
This is the heart of contributing. A "style" is a genre pack: the standard progressions of that style, plus idiomatic ways to play each one. One pack renders in **all 12 keys** automatically, because everything is stored key-agnostically (scale degrees, not chord names).
The data contract you're filling is [`src/data/kb/SCHEMA.md`](src/data/kb/SCHEMA.md) — read it; it's the source of truth. The steps below are the workflow around it.
### Step 1 — Copy an existing pack as your template
A style lives in `src/data/kb/<style>/` and has (at least) three files:
```
src/data/kb/<style>/
meta.js — the style's identity (label, feel, tempo, one-line character)
progressions.js — the style's standard progressions (instrument-independent)
guitar.js — how to play them on guitar (voicings, comping, improv)
```
The cleanest way to start is to **mirror a finished pack**. The gospel pack is a good, complete reference to copy and edit:
- [`src/data/kb/gospel/meta.js`](src/data/kb/gospel/meta.js)
- [`src/data/kb/gospel/progressions.js`](src/data/kb/gospel/progressions.js)
- [`src/data/kb/gospel/guitar.js`](src/data/kb/gospel/guitar.js)
(`SCHEMA.md` names the `jazz/` pack as its canonical exemplar — gospel mirrors the same shape and is a good second model. Pick whichever style is closest to yours.)
Make a new folder named after your style (e.g. `src/data/kb/neosoul/`), copy those three files in, and rewrite the content.
### Step 2 — Fill in the fields (in plain musician language)
**`meta.js`** — the style's identity. `id` (must equal the folder name), `label` (display name), `feel` (`swing` / `straight` / `shuffle` / `16th` / `bossa`…), `tempoRange` (`[low, high]` BPM), and a one-sentence `character` of what makes the style sound like itself.
**`progressions.js`** — your style's signature progressions, 48 of them. Each one is written **key-agnostically** using these fields:
- `degrees` — the chord roots as **semitone offsets from the key root, 011**. So in any major key: I = `0`, ii = `2`, IV = `5`, V = `7`, vi = `9`. A iiVI is `[2, 7, 0]`. You write the *intervals*, JamBuddy fills in the actual chords once it knows the key.
- `qualities` — the chord **quality** for each degree, e.g. `min7`, `dom7`, `maj7`, `maj`, `add9`, `sus4`, `dim7`. These must be one of the names JamBuddy knows: `maj`, `min`, `dom7`, `maj7`, `min7`, `dim`, `dim7`, `half_dim`, `aug`, `sus4`, `sus2`, `maj6`, `min6`, `add9`. (That list lives in `CHORD_TYPES` in `src/lib/theory.js`.)
- `rn` — the Roman numerals you'd *write on a chart* (`['ii7', 'V7', 'Imaj7']`) — purely for display.
- `bars` — how many bars each chord lasts.
- `mode``major`, `minor`, `dorian`, `phrygian`, `lydian`, or `mixolydian`.
- `songs` — real songs that use the progression. **Be honest here** (see the PR checklist).
- `tip` — one transferable idea a player can take away.
- `id` — a globally unique slug, prefixed with your style name (`neosoul-251`, `neosoul-vamp`…).
`degrees`, `qualities`, `rn`, and `bars` must all be the **same length** (one entry per chord in the loop).
**`guitar.js`** — the ways to play each progression. The key fields:
- `styleIntro` — 23 sentences on the guitar's role in this style.
- `comping` — at least one named rhythm with a description.
- `plays` — for each progression id, **at least two genuinely different ways to play it** (different register, density, or technique — not the same voicing moved up the neck).
- `improv` — scales to solo over each chord, target notes, optional licks.
Each chord in a play carries a guitar **shape**, written in one of two formats:
- **Movable shape** (the common case) — fret offsets *relative to the root fret*, so the same grip works in every key:
```js
shape: {
rootStr: 6, // which string carries the root (6 = low E)
offsets: [0, 'x', 0, 1, 'x', 'x'], // always 6 entries, low-E string first; 'x' = muted
fingers: [1, 0, 2, 3, 0, 0],
}
```
- **Open shape** (open-string chords that only work in certain keys) — uses absolute `frets` plus `onlyRoot` (the pitch class, 011, the shape is built for) instead of `offsets`.
If a voicing **deliberately leaves a note out**, declare it so the data stays honest and the UI can show it:
- `extensions: ['9']` — colour tones you've added beyond the basic chord (the validator only allows notes you've declared).
- `rootless: true` — the shape omits the root (e.g. guide-tone grips where the bass covers the root).
- `omit3: true` — the shape omits the 3rd (e.g. power chords that work over major or minor).
### Step 3 — Register the style
Open [`src/data/kb/index.js`](src/data/kb/index.js) and add your pack the same way the others are wired: import its `meta`, `progressions`, and `guitar`, then add an entry to the exported registry. Mirror an existing block exactly — the UI reads only this registry.
### Step 4 — Run the validator until it's green
```bash
node scripts/validate-kb.mjs
```
A passing run looks like:
```
✓ KB valid — 9 style(s), 45 progressions, 90 plays
```
If it fails, it prints a specific line for each problem (which file, which chord, what's wrong). Fix the data and run again. **Never weaken the validator to make content pass** — if you think a rule is wrong, open an issue instead.
#### Why the validator exists (this is the important part)
The validator is the quality bar that lets us trust voicings we didn't author ourselves. For **every guitar shape**, it computes the **actual pitch classes** the grip would sound (from the string tuning, the root string, and your offsets) and checks two things:
1. **Every note you sound actually belongs to the chord** — the chord's own tones plus any `extensions` you declared. A misspelled grip (a wrong fret, a stray open string) sounds a note that isn't in the chord, and the validator rejects it.
2. **The chord's defining tones are present** — unless you've honestly declared them omitted via `rootless` / `omit3`.
In plain terms: you can't accidentally ship an "Amaj7" that's secretly an A7, and you can't claim a voicing has a note it doesn't. That mechanical check is what makes a contributed pack trustworthy without a maintainer re-fingering every chord by hand.
---
## The assisted path: `/kb-expand`
If you're working with [Claude Code](https://claude.com/claude-code), the `/kb-expand` skill is an assisted authoring route. It does exactly **one style × instrument cell end to end** — researches the style's standard progressions and idiomatic voicings (with sources), drafts the files per `SCHEMA.md`, registers the style, and **self-validates** by running `node scripts/validate-kb.mjs` until green before stopping. It's the fastest way to go from "I know this genre" to a scaffolded, validated pack you can refine. You still own the musical judgment — check its voicings and attributions.
---
## Pull request checklist
Before you open a PR, confirm:
- [ ] **Validator green** — `node scripts/validate-kb.mjs` prints `✓ KB valid …`.
- [ ] **Build green** — `npm run build` succeeds (your new file imports cleanly).
- [ ] **Honest attributions** — every song listed actually uses the progression. Do **not** claim a specific recording uses an exact voicing unless you genuinely know it does; "standard in the tradition" or a hedged reference is better than a fabricated one. Licks and sources are real.
- [ ] **Plays genuinely differ** — the 2+ ways to play each progression contrast in register, density, or technique (not transpositions of one another).
- [ ] **One style per PR** — keeps review focused and easy to merge.
That's it. Open the PR, and a maintainer (the Critic in our [ensemble](docs/agents/ROSTER.md)) will run the same checks before merging.
---
## Reporting bugs and proposing styles
You don't have to write any code to help:
- **Propose or contribute a style** → use the [Propose / contribute a style](.github/ISSUE_TEMPLATE/add-style.md) issue template. Tell us the genre, its signature progressions, and whether you'll author the voicings or want help.
- **Found a bug?** → [Bug report](.github/ISSUE_TEMPLATE/bug_report.md).
- **Have an idea?** → [Feature request](.github/ISSUE_TEMPLATE/feature_request.md).
---
## Scope and ground rules
- Adding/editing **style data** under `src/data/kb/` and using the issue templates needs no special permission — that's exactly the contribution path this guide is for.
- Changes to **app code, the audio pipeline, the schema, or the validator** are bigger — open an issue to discuss first so it fits the roadmap in [`GOAL.md`](GOAL.md).
- **License:** the project doesn't have a license file yet, so reuse terms aren't settled. If that matters for your contribution, raise it in an issue before investing heavily.
Thanks for helping musicians hear, play, and *learn* the jam.
+120
View File
@@ -0,0 +1,120 @@
# GOAL — From Detection to Direction
WhatTheFlat already solves the hard live problem: **knowing what key and chords people are playing in a jam, in real time.** This document defines the next level, in two parts:
1. **Chord progressions** — make it easier to work with *different* progressions: a bigger genre repertoire, clearer "1-5-4"-style readout of the detected loop, a builder where you place chords yourself, and alternative voicings for every chord in a progression.
2. **Learn** — expand the education section for the player who already knows the basics and is confident enough to jam, but wants to go next level.
Supporting research and full repertoires live in:
- [`docs/progression-repertoire.md`](docs/progression-repertoire.md) — genre-by-genre progression tables, substitution rules, voicing data sources, UX patterns from existing tools
- [`docs/learn-curriculum.md`](docs/learn-curriculum.md) — intermediate training methods for guitar, piano, and bass, with drills and how app features map onto them
- [`docs/kb-plan.md`](docs/kb-plan.md) — the **jam knowledgebase**: styles × instruments × progressions × voicings, the `/kb-expand` session loop that grows it ([`docs/kb-backlog.md`](docs/kb-backlog.md)), and the **Jam Guide** panel that renders it live at the bottom of the app
---
## Part 1 — Chord progressions
### Where we are
- `PROGRESSIONS` in `src/lib/theory.js` holds **14 hardcoded progressions across 7 genres** (Pop, Blues, Folk, Jazz, Rock, '50s, Flamenco). These drive `ProgressionSuggestions.jsx`.
- `detectRepeatingProgression()` finds the repeating loop in chord history; `ProgressionBanner.jsx` already shows it with Roman numerals (IVIV) via `toRomanNumeral()`.
- `EducationPanel.jsx` + `src/lib/education.js` carry 15 famous progressions with substitutions and style variations.
- `src/lib/voicings.js` has ~50 guitar shapes (open + barre) across 14 chord types; no inversions, no triad string-sets, thin piano coverage.
- There is **no way to enter or arrange a progression manually** — everything is detection-driven.
### Goals
**G1 — Expanded genre repertoire (data, not code).**
Grow `PROGRESSIONS` from 7 to ~12 genres using the researched tables in `docs/progression-repertoire.md`: Funk (Dorian i7IV7 vamps), Reggae (two-chord skanks), Country (V/V secondary dominant moves), R&B/Neo-soul (iiiviiiV, 6-2-5-1), Gospel (chained 2-5-1s), plus blues variants (quick-change, minor blues) and the J-pop "Royal Road" (IVViiivi). Progressions stay in the existing `{ name, rn, degrees }` format so suggestions, Roman numerals and key mapping keep working unchanged.
**G2 — Numeral clarity ("is this 1-5-4?").**
The loop banner already shows Roman numerals; add a **Nashville-number display option** (1-5-4 instead of I-V-IV) since that is how musicians call changes at a jam. One formatting layer over `toRomanNumeral`, toggled in Settings.
**G3 — Progression Builder (drag and drop).**
A panel where the user assembles a progression by hand:
- A **key-relative chord palette** (Hookpad's best idea): the diatonic chords of the current detected/locked key, one tap to add, with borrowed-chord palette (iv, ♭VII, ♭VI, V/V…) one level deeper.
- Slots that can be **reordered by drag and drop**, with live Roman/Nashville numerals under each chord.
- Tap any slot → **alternative voicings** for that chord (G4).
- Seeded from the detected loop ("send loop to builder") so a jam can be captured, edited, and varied.
- Variation buttons per chord powered by the substitution taxonomy (diatonic swap, borrow, secondary dominant, 7th/sus/add9 color) — the rules are in `docs/progression-repertoire.md` §2.
**G4 — Alternative voicings per progression chord.**
- **Guitar:** extend `voicings.js` with CAGED positions and triads on string-sets (top-3 / middle-3), or adopt the MIT-licensed [`tombatossals/chords-db`](https://github.com/tombatossals/chords-db) dataset (multiple positions per chord, JSON, with a companion React SVG renderer).
- **Piano:** generate voicings from interval recipes rather than data files — root position, inversions, shells (1-3-7), rootless A (3-5-7-9) / B (7-9-3-5) — choosing the inversion that minimizes movement from the previous chord (voice-leading distance).
- Surface these in the Builder (G3) and in `CurrentJamPanel` voicing strips.
---
## Part 2 — Learn: basics → jam-ready next level
### Audience
Not step one. The target player already knows open/barre chords (guitar), triads and simple lead sheets (piano), roots and simple scales (bass) — and is confident enough to show up at a jam. The Learn section's job is to take them **from "can survive a jam" to "makes the jam better."**
### What the research says (full detail in `docs/learn-curriculum.md`)
Across guitar, piano, and bass pedagogy (Berklee methods, Justin Guitar grades 46, Tomo Fujita, Mark Levine, Open Studio, PianoGroove, Scott's Bass Lessons, TalkingBass, Ed Friedland), the intermediate-to-advanced jump converges on four pillars:
| Pillar | Guitar | Piano | Bass |
|---|---|---|---|
| **Fretboard/keyboard liberation** | CAGED, triads on string sets, connecting pentatonic boxes | Inversions in all keys, voice leading | Neck zones, chord-tone arpeggios everywhere |
| **Playing the changes** | Chord-tone targeting, guide tones (3rds & 7ths) | Shell + rootless voicings, sus/add9 colors | Walking lines, chromatic approach notes |
| **Ensemble skills** | Small voicings, register discipline, comping | Comping rhythms (Charleston…), "rule of 1", staying out of the bass lane | Pocket/drummer lock, ghost notes, subdivision switching |
| **Functional ears** | Hearing I-IV-V / vi-IV-I-V by bass line | Nashville numbers, 12-key transposition | Singing root movement, predicting the V |
### Goals
**L1 — Practice drills tab.**
Add a drills library to the Learn section: per instrument, per pillar, the concrete drills from the curriculum doc (e.g. "first note after every chord change = the 3rd", "Charleston comping ladder", "W|H|H chromatic walkup"). Keyed to the *current detected key and loop* so every drill is in today's jam context, not abstract C major.
**L2 — Detection-powered feedback (the unfair advantage).**
No practice app can hear the player; this one can. Phased:
- **Target-note highlighting:** on each detected chord change, highlight the new chord's 3rd/7th on the fretboard/piano for a beat (drill scaffold — uses existing tier rendering).
- **Next-chord preview tier:** when a loop is detected, show the *upcoming* chord's root and its chromatic approach notes (the bassist's walking-line scaffold).
- **Chord-tone hit rate:** classify detected notes against the current chord (chord tone / scale tone / outside) and show a session score.
- **Pocket report:** extend the onset/BPM pipeline to show timing drift against the established grid.
**L3 — Ear training from your own jam.**
A quiz mode that hides the chord banner and asks the user to name the progression in numbers before revealing — using the *user's own chord history* as the corpus. Converts the existing detection + `toRomanNumeral` into the functional ear training every method prescribes.
**L4 — Mode-difference teaching.**
When the user manually switches mode (the documented K-S limitation — by design), briefly highlight the *difference notes* (e.g. the raised 6th going minor → Dorian) on the instrument views. Turns a limitation into a lesson.
---
## What we need to go next level — priorities
| # | Item | Effort | Why first |
|---|---|---|---|
| 1 | **G1** Genre repertoire expansion | S (data only) | Immediate value, zero architectural risk |
| 2 | **G2** Nashville number toggle | S | Directly answers "is it 1-5-4", jam-native language |
| 3 | **G3** Progression Builder MVP (palette + reorder + numerals) | M | The single most-requested workflow gap |
| 4 | **L1** Drills tab seeded from curriculum doc | M (content + UI) | Makes Learn level-appropriate |
| 5 | **G4** Voicing alternatives (guitar string-sets + piano recipes) | M | Feeds both Builder and Learn |
| 6 | **L2** Target-note highlighting + next-chord preview | M | First detection-powered trainer, reuses tier rendering |
| 7 | **L3** Ear-training quiz on own history | M | High pedagogical value, small surface |
| 8 | **L2** Hit-rate scoring + pocket report | L | Needs tuning of pitch/onset classification |
| 9 | **G3** Builder phase 2: borrowed palette, variation buttons, loop import | L | Builds on MVP + substitution rules |
| 10 | **KB** Knowledgebase + Jam Guide panel (see `docs/kb-plan.md`) | L, but looped in S-sized sessions via `/kb-expand` | The style × instrument playbook that powers improv learning |
### How we execute
Knowledgebase work runs as **looped sessions**: `/kb-expand` does exactly one style × instrument cell (research → author → validate → commit), driven by the queue in `docs/kb-backlog.md`. Tranches run on a dedicated branch — e.g. an hourly `/loop /kb-expand` for a working day — and **end with a pull request** so a whole tranche is reviewed in one place. First tranche (started 2026-06-12, branch `kb-expansion`): Session 0 bootstrap + the first guitar style cells, hourly for 8 hours, PR to `main` at the end.
## How we build it — the ensemble
The work is carried by a six-agent team that collaborates through files (a shared ledger + the repo), conducted by one scheduled loop. Full design in [`docs/agents/`](docs/agents/):
- [`ROSTER.md`](docs/agents/ROSTER.md) — the six agents, their domains, file ownership, and cadence weights: 🎼 Maestro (orchestrator), 🎓 Professor (music & pedagogy), 🔧 Luthier (engineering), 🎨 Muse (design & UX), 🔍 Critic (the review gate), 📣 Herald (open-source & community).
- [`PROTOCOL.md`](docs/agents/PROTOCOL.md) — how they collaborate: the task-locking rule that prevents file conflicts, the `backlog→ready→claimed→in-review→done` lifecycle, the appointment algorithm, scheduling (schedule the conductor, not the band), and PRs.
- [`LEDGER.md`](docs/agents/LEDGER.md) — the live task board, seeded with the `sprint-jam-guide` starter sprint.
**Run it:** `/jam-loop` advances one orchestrated iteration (Maestro appoints → workers build → Critic gates → reconcile + commit). Schedule it with `/loop 1h /jam-loop` (session) or `/schedule` (durable). `/kb-expand` remains the single-domain content fast-path (Professor solo).
### Definition of "next level" (success criteria)
- A jammer can glance at the app and call the loop in numbers ("it's a 1-5-4").
- Suggestions cover the genres people actually jam (funk/reggae/R&B/gospel included), not just pop/blues.
- A user can lay out their own progression, drag chords around, and see 3+ ways to voice every chord on their instrument.
- The Learn section gives an intermediate guitarist, pianist, or bassist a *specific* next drill in the key they're jamming in right now — and at least one drill where the app verifies them by listening.
+109 -29
View File
@@ -1,48 +1,128 @@
# WhatTheFlat
# JamBuddy
Real-time key and chord detection for musicians. Play guitar, bass, piano, or any instrument into your microphone and WhatTheFlat will identify the key you're in, the chords you're playing, and suggest progressions.
**Hear the jam, learn the jam.** JamBuddy listens through your microphone, figures out the key and chords you're playing in real time, then shows you *how to play over them* — and helps you level up while you do it.
## Features
It started as a live key/chord detector (you may know it as *WhatTheFlat*). It's growing into an open, contributable **learning platform** for the player who can already survive a jam and wants to make it better.
- Real-time chord detection from live audio
- Automatic key detection (Krumhansl-Schmuckler profiles)
- Chord history and repeating progression detection
- Roman numeral analysis relative to detected key
- Fretboard visualiser showing safe notes and chord tones
- Beginner / Advanced modes
- Manual key lock for jam sessions
- AI chat assistant for music theory questions
---
## Tech Stack
## The idea: detect → guide → level up
- **Frontend**: React 18, Vite, Tailwind CSS
- **Audio**: Web Audio API, [Pitchy](https://github.com/ianprime0509/pitchy) (McLeod pitch detection)
- **Backend**: Python (Claude API for chat assistant)
1. **Detect.** Point your mic at a guitar, piano, or a whole band. JamBuddy identifies the **key** and the **chords** as you play, finds the repeating **loop**, and reads it back in Roman numerals (iiVI, IVviIV).
## Getting Started
2. **Guide.** Once it knows your loop, the **Roadmap Jam Guide** lays it out as an improv highway synced to what you're playing: **guide tones** (the 3rds and 7ths that carry the harmony), **voice-leading rails** showing how each chord resolves into the next, the **solo scale** to blow over each station, and the **chord voicings** to grab — all in your detected key, with a playhead tracking where the loop is.
### Frontend
3. **Level up.** Style packs turn the same iiVI into *jazz* vs *bossa* vs *funk* — genuinely different voicings, rhythms, and improv advice — so you don't just play the changes, you learn the language. This is the on-ramp to the wider **Learn** direction (drills and detection-powered feedback) described in [`GOAL.md`](GOAL.md).
---
## What works today vs. what's in progress
This is an honest snapshot — it's an active project.
**Working today**
- **Real-time key detection** with top-3 candidate chips (click to lock) — works for guitar and piano.
- **Real-time chord detection** from live audio, with chord history and repeating-progression detection.
- **Roadmap Jam Guide** panel: matches your detected loop to a style progression and renders guide tones, voice-leading rails, solo-scale labels, and chord-voicing thumbnails synced to the loop position.
- **8 guitar style packs** in the knowledgebase — jazz, blues, rock, bossa nova, funk, reggae, country, and R&B (gospel landing next).
- **Fretboard and piano** visualisers that colour chord tones, pentatonic, and scale notes.
- **Chromatic tuner** and a **loop station** for capturing and replaying phrases.
- **Fully offline** — all audio and detection run locally in the desktop window; no server, no network calls.
**In progress**
- **Piano and bass** style packs (guitar is the first instrument rolled out).
- The **Progression Builder** — lay out and rearrange your own progression by hand (GOAL §G3).
- **Detection-powered drills** — practice exercises and feedback that use the fact that the app can actually *hear* you (GOAL Part 2).
---
## What it looks like
<!-- TODO: add a screenshot or GIF of the Roadmap Jam Guide tracking a live iiVI or 12-bar blues. -->
<!-- Caption: "The Roadmap Jam Guide mid-jam — guide tones, voice-leading rails, and the next voicing, synced to the chord you're playing right now." -->
_(Screenshot coming — the Roadmap panel mid-jam.)_
---
## Quickstart
You'll need [Node.js](https://nodejs.org/) (18+) and a microphone.
```bash
cd frontend
git clone https://github.com/whattheflat/whattheflat.git
cd whattheflat
npm install
npm run dev
# Desktop app (Vite dev server + Electron window, hot reload)
npm run electron:dev
```
Open `http://localhost:5173` in your browser and click **Start Listening**. Allow microphone access when prompted.
### Backend (chat assistant)
Prefer the browser? Run the renderer on its own (no Electron shell):
```bash
pip install -r requirements.txt
python main.py
npm run dev # then open http://localhost:5173
```
## How It Works
**To see the magic:** grant **microphone permission** when prompted, then play a **recognized loop** — a **iiVI** or a **12-bar blues** are the easiest ways to light up the Roadmap Jam Guide. JamBuddy needs to hear the loop repeat a couple of times to lock the key and match the progression.
Audio is processed in two parallel paths:
### Building installers
1. **Pitch path** — small 4096-sample FFT with McLeod autocorrelation for fast, accurate single-note pitch detection. Feeds the key detection algorithm.
2. **Chord path** — large 16384-sample FFT (2.7 Hz/bin resolution) with harmonic summation chroma extraction. The chroma vector is matched against chord templates (major, minor, dominant 7th, sus4, diminished) to identify the current chord.
```bash
npm run electron:build:win # Windows NSIS installer → release/
npm run electron:build:mac # macOS DMG → release/
npm run electron:build:linux # Linux AppImage → release/
```
Key detection uses a rolling vote over the last 12 detections and requires 9/12 agreement before committing, keeping the display stable during transitions.
---
## Contributing — add a style without deep coding
The style packs are **data, not code**. If you're a musician who knows how a style is voiced and played, you can add one by filling in a structured data file — no audio or detection internals required.
- The data contract lives in [`src/data/kb/SCHEMA.md`](src/data/kb/SCHEMA.md): progressions as key-agnostic scale degrees, plus 2+ idiomatic "ways to play" each (voicings, comping, improv). One entry renders in all 12 keys.
- An **assisted path** is available: the `/kb-expand` workflow researches, drafts, and validates one style cell at a time, so you can start from a scaffold rather than a blank file.
- Every contribution passes a **validator quality gate** (`node scripts/validate-kb.mjs`) that mechanically checks each voicing actually contains the chord's tones — that's the bar that keeps the knowledgebase trustworthy.
A full step-by-step **`CONTRIBUTING.md`** guide is **coming** (tracked as task H-02). Until then, `SCHEMA.md` is the source of truth, and the [jazz pack](src/data/kb/jazz) is the gold-standard example to imitate.
---
## How it's built — the ensemble
JamBuddy is built by a six-agent team (Maestro, Professor, Luthier, Muse, Critic, Herald) that collaborates entirely through files — a shared ledger and the repo — conducted by one scheduled loop. If you want to understand how the project plans and ships work, start in [`docs/agents/`](docs/agents/):
- [`ROSTER.md`](docs/agents/ROSTER.md) — the six agents and their domains.
- [`PROTOCOL.md`](docs/agents/PROTOCOL.md) — how they collaborate (task locking, review gate, scheduling).
- [`LEDGER.md`](docs/agents/LEDGER.md) — the live task board.
The product north star and full roadmap are in [`GOAL.md`](GOAL.md).
---
## Tech & how detection works
| | |
|---|---|
| **App shell** | Electron (window host only — all logic runs in the renderer) |
| **UI** | React, Tailwind CSS, Vite |
| **Audio** | Web Audio API, [Pitchy](https://github.com/ianprime0509/pitchy) (McLeod pitch detection) |
| **Music theory** | Custom JS — Krumhansl-Schmuckler key detection, harmonic-summation chroma chord matching |
Two audio pipelines run in parallel: a fast **pitch path** (4096-sample FFT, McLeod autocorrelation) feeds Krumhansl-Schmuckler key detection over a voting window; a higher-resolution **chord path** (16384-sample FFT, ~2.7 Hz/bin) extracts a harmonic-summation chroma and matches it against chord templates. Architecture details are in [`CLAUDE.md`](CLAUDE.md).
> Note on modes: Krumhansl-Schmuckler distinguishes major vs. minor but not modes — Dorian and natural minor look the same to it. JamBuddy detects the tonal centre, and you pick the mode (the dropdown offers Dorian, Mixolydian, etc.). By design.
---
## License
No license file is set yet. Until one is added, all rights are reserved by the authors — please open an issue before reusing the code.
## Deploy
- firebase login
- npm run build
- firebase deploy --only hosting:jambuddy
View File
-21
View File
@@ -1,21 +0,0 @@
from typing import Literal
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8")
ai_mode: Literal["online", "offline"] = "offline"
# Online (Claude) settings
anthropic_api_key: str = ""
claude_model: str = "claude-sonnet-4-6"
# Offline (Ollama) settings
ollama_host: str = "http://localhost:11434"
ollama_model: str = "llama3.2:3b"
cors_origins: list[str] = ["http://localhost:5173", "http://localhost:3000"]
settings = Settings()
View File
-32
View File
@@ -1,32 +0,0 @@
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from api.services.ai import chat
router = APIRouter()
class Message(BaseModel):
role: str
content: str
class ChatRequest(BaseModel):
messages: list[Message]
context: dict | None = None
class ChatResponse(BaseModel):
reply: str
@router.post("/chat", response_model=ChatResponse)
async def chat_endpoint(request: ChatRequest):
try:
reply = await chat(
messages=[m.model_dump() for m in request.messages],
context=request.context,
)
return ChatResponse(reply=reply)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
View File
-50
View File
@@ -1,50 +0,0 @@
from api.config import settings
SYSTEM_PROMPT = """You are a friendly, beginner-aware music theory assistant for WhatTheFlat — a live jam helper app.
You help musicians understand what's happening harmonically during a jam session.
Keep answers short, warm, and jargon-free. If you use a music term, briefly explain it.
Never say someone played a "wrong" note — always frame it as "try these instead".
When given context about the current key and chord, use it in your response."""
async def chat(messages: list[dict], context: dict | None = None) -> str:
system = SYSTEM_PROMPT
if context:
parts = []
if context.get("key"):
parts.append(f"Current key: {context['key']}")
if context.get("chord"):
parts.append(f"Current chord: {context['chord']}")
if parts:
system += "\n\nLive session context:\n" + "\n".join(parts)
if settings.ai_mode == "online":
return await _chat_claude(messages, system)
else:
return await _chat_ollama(messages, system)
async def _chat_claude(messages: list[dict], system: str) -> str:
import anthropic
client = anthropic.AsyncAnthropic(api_key=settings.anthropic_api_key)
response = await client.messages.create(
model=settings.claude_model,
max_tokens=512,
system=system,
messages=messages,
)
return response.content[0].text
async def _chat_ollama(messages: list[dict], system: str) -> str:
import ollama
client = ollama.AsyncClient(host=settings.ollama_host)
full_messages = [{"role": "system", "content": system}] + messages
response = await client.chat(
model=settings.ollama_model,
messages=full_messages,
)
return response.message.content
Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

+341
View File
@@ -0,0 +1,341 @@
# Ensemble Ledger — Live Task Board
The shared queue all agents read and write. Lifecycle and rules: [`PROTOCOL.md`](PROTOCOL.md). Roster + cadence weights: [`ROSTER.md`](ROSTER.md).
**Status:** `backlog``ready``claimed``in-review``done` / `returned`
**Lock:** a task's `files` column is its lock — no two `claimed`/`in-review` tasks may overlap files.
---
## Active sprint: `sprint-roulette-kb` (branch: `sprint-jamguide-piano` — runs CONCURRENTLY with sprint-one-screen below; hourly cron, file-locks keep them disjoint)
**Goal (user directive 2026-07-11):** "a 12h loop with one iteration per hour for adding more piano licks and knowledge base voicings, potentially including some sort of circle of fifths etc in the knowledge center. on top of that … one button that would be a random chord progression selection. a button up top 'jam roulette' and then select a genre (like we have jazz, blues rock etc) and then have a random key chosen and an interesting progression show up as a loop in the screen. it would fill in the loop section and a 4 bar progression or something so that everyone can see the key and the chords to be played with different voicing so they can start playing… then musicians can start playing and it continues from it."
**Loop:** `/jam-loop` hourly × 12 (12 h), started 2026-07-11. Engineering tasks that need one-screen's files are dep-blocked on C-50 — content tasks fill the early iterations. Weights: Professor 3, Muse 2, Luthier 2, Critic gate.
| id | title | domain | status | depends-on | files (lock) | definition of done |
|----|-------|--------|--------|-----------|--------------|--------------------|
| M-07 | Seed `sprint-roulette-kb`; schedule hourly cron | maestro | done | — | `docs/agents/LEDGER.md` | seeded, cron created |
| C-60 | **Piano lick schema** (additive): licks today are guitar-tab-only — design the piano-lick shape reusing the bass-pattern language (per-note `deg` XOR typed `approach`, `beat`, `octave`, technique from a PIANO-appropriate vocab subset — decide which of the 8 words apply to keys and whether grace-note/roll style additions are needed; keep it validateable like C-41 did) in SCHEMA.md + validate-kb.mjs + smoke bite-test | quality | done | — | `src/data/kb/SCHEMA.md`, `scripts/validate-kb.mjs`, `scripts/smoke.mjs` | schema documented; validator enforces; existing KB green; smoke proves it bites |
| D-60 | **PianoLickCard** renderer — visual rhyme with LickCard's tab idiom but for keys (timeline + MiniPiano-style pitches or a degree ladder — pick per readability at strip size); playback via chordAudio like BassPatternCard. Must export `PIANO_TECHNIQUE_VOCAB` set-equal to the validator's (the dormant C-60 smoke guard activates on this file's existence). **Component only — LicksStrip wiring deferred (JamGuide.jsx reserved for one-screen L-50); wiring folded into C-61-era integration. Wiring DoD must include (D-60 gate): a shared sequencer-stop so BassPatternCard/PianoLickCard previews can't layer (each holds a private currentSeq today — impossible to trigger until both mount together)** | design | done | C-60 | `src/components/PianoLickCard.jsx` (new) ONLY — done `a7dbd6a` | renders every P-60 lick; playable; graceful empty/malformed |
| P-60 | Piano licks pack #1: 3-4 each for **jazz + blues** piano (C-60 schema; arithmetic-verified prose, the P-41 bar). **PASS first try** (`70263e2` — gate realized all 8 in two keys, 35/35 prose claims; dom7-heavy blues coverage accepted as musically right) | content | done | C-60 | `src/data/kb/jazz/piano.js`, `src/data/kb/blues/piano.js` | validator green; every lick playable as written |
| P-61 | Piano licks pack #2: 3-4 each for **gospel + rnb** piano. **Returned once (2026-07-11):** one false interval claim in rnb-quartal-slip tips ("each move a step" — actually skip-then-step); 42/43 checks passed. Fixed with the gate's own prescribed wording; Maestro verified the line against the gate's computed 3/2 motion (scoped re-gate waived — the fix IS the gate's pre-approved example) | content | done | P-60 | `src/data/kb/gospel/piano.js`, `src/data/kb/rnb/piano.js` | validator green |
| P-62 | KB voicings expansion: **pop piano cell** (next per kb-backlog) + audit `GUITAR_SHAPES` for qualities with <3 placeable shapes and author additions where idiomatic | content | done | — | `src/data/kb/pop/piano.js`, `src/data/kb/index.js`, `src/lib/voicings.js` (additive shapes only) | validator green; every new shape hand-verified (L-23 lesson: base-fret convention) |
| D-61 | **Circle of fifths** in the Knowledge Center: interactive SVG (12 keys around the circle, live/locked key highlighted, relative minor ring, diatonic chords on tap-free hover/inline, key-signature glyphs), mounted inside ExploreSection; educational copy in the app's voice. **Returned once (2026-07-11):** modal hub key signature wrong (A dorian showed ♮ while its chips show F♯ — all 4 dropdown modal modes affected; fix = derive the parent-major signature, teaching "A dorian = G major's notes") + preview flat/sharp spelling split; geometry/rings/tiers/a11y all passed 60/60. Fixed + re-gate PASS (`c999c95` — hub computed from SCALES set-equality, 72/72 uniqueness, one spelling authority) | design | done | — | `src/components/CircleOfFifths.jsx` (new), `src/components/ExplorePanel.jsx` (ExploreSection integration only) | renders any key incl. none-detected; follows effectiveKey live; tokens + AA; zero clicks for the core view |
| D-62 | **Jam Roulette UX spec** (doc): button up top ("Jam roulette", controls bar per one-screen's layout), genre picker (the 10 KB styles), randomization rules (random key; "interesting" progression selection — weight intermediate level + variety, avoid repeats within a session), how the seed fills the screen (seeds the committed loop + locked key so the banner/strip, voicing rail, licks, related progressions all populate exactly as if detected — reuse, don't duplicate), and the **detection handoff**: musicians start playing and live detection continues from the seed (spec the interplay with the L-31 commit layer: the seed behaves like a committed loop — replacement needs the same consistent evidence; New Song clears it) **Returned once (2026-07-11):** "matched by construction" false for 10/56 progressions — buildLoopIndex indexes RAW degrees while collapse changes name-sequence length (incl. blues-12bar: LIVE detection of a real 12-bar gets an empty JamGuide — pre-existing bug surfaced!); detector len-cap 8 makes collapsed 9-10 unconfirmable; round-trip empirical not constructional (blues-8bar loses to its own [V7,I7] alternation); funk-one-chord collapses to 2 names not 1; flag-1 timeline off by one (EVERY seed dies unguarded — guard even more necessary). Maestro direction: fix (a) — additively index collapsed forms in match.js (fixes live detection too); pool = empirical round-trip passers ∩ collapsed len 2-8. **Returned twice (2026-07-11):** round 2 verified fix-(a) construction/timeline/proofs sound but found the sweep protocol as written evicts all 8 two-name vamps (needs steady-state + all-offsets), behaviour-additive false in exactly one case (country-145 now self-attributes — an improvement, enumerate it), census 11 not 10, and the BASS plays path (BassGuideRows :530/:533) missed by the remap. Round-3 PASS (`see commit` — literal protocol implementation reproduced 4/56 failures + 52/56 pool + 11-census exactly; sourceIndex mechanism verified at current line numbers) | design | done | — | `docs/design/jam-roulette.md` | mechanism spec'd against the real App state (lockedKey, detectedProgression, progressionVoteRef); no state duplication; L-60 scope bounded |
| L-60 | Implement Jam Roulette per D-62 (App.jsx UI-state + seeding fn; the roulette button + genre menu; 🚨 audio contract grep-gated — seeding touches display state and the progression refs ONLY, never callbacks). Ride-alongs: pass `dense` to the heard-live VoicingBrowser in the rail (D-51 gate flag — same fragile pair fit in the fallback path); one-screen.md §7 "two-octave cells alone" sentence is stale by a few px (D-51 gate nit) | engineering | done | D-62, C-50 | `src/App.jsx` (+ per D-62 — re-lock at promotion) | one click → genre → key+progression fills the jam dashboard; detection continues from it; New Song clears; build + smoke green; contract grep clean |
| C-61 | Sprint-end sweep + PR #3 update (COMBINED — covers BOTH sprint-one-screen and sprint-roulette-kb in one comment) | quality | done | L-60, D-60, P-61, P-62, D-61 | (none — verification) | all green; PR updated — **BOTH SPRINTS COMPLETE** |
> Sequencing: C-60 ‖ P-62 ‖ D-61 ‖ D-62 are file-disjoint and ready now (none touch one-screen's locks). Then C-60 → {D-60, P-60 → P-61}, and D-62 + C-50(one-screen) → L-60. C-61 closes. Critic gates every task.
---
## Active sprint: `sprint-one-screen` (branch: `sprint-jamguide-piano` — continued; commits extend PR #3)
**Goal (user directive 2026-07-11, after testing integrated-glance — "i like it a lot, so i would like to make some alterations"):**
1. **The top block is too big** — "the chord view and the chord loop incl the instrument below is too big, it takes up too much space… this main view doesnt really add value." Compress the detection area and the instrument view.
2. **Kill the big now-playing chord** — "seeing the big chord 'now playing' in big is also unnecessary as you already see that one in the chords (loop) part." The loop chips already carry it (playhead chip).
3. **Rethink ProgressionSuggestions** — "the suggested progressions on the right are also almost useless… we need to rethink them in the form of SUGGESTED VOICINGS and the progressions we add relating to the loop." Replace the generic genre table with (a) the suggested-voicings rail and (b) KB-sourced progressions RELATED to the detected loop.
4. **Voicings on the right** — "i'd like to have the suggested voicings on the right side of the screen (the jam guide)." The Jam Guide rail becomes a right column. (Overrides D-40's rejected side-by-side alternative — user directive wins.)
5. **One screen** — "i wanna see the chords, the loop, the voicings, the progressions, the licks all on one screen, everything you need to follow the jam correctly."
6. **Jam mode / fullscreen (refinement 2026-07-11):** "it can still have a scroll down, but the main concept needs to be in one screen: potentially we add a fullscreen button so we can just show that when we are playing a jam… everything that is learning and behind the scenes etc you can keep below/scrollable but we need one main view for live jams where we see everything at once." The dashboard fits 100vh as a hard constraint; a fullscreen/jam-mode button shows only it; KnowledgeDock/Debug/Tuner (LoopStation per Muse's call) live below in normal mode.
Standing principles (memory): scroll > click; nothing duplicated; one global instrument selector; playhead highlights, never hides. Weights: Muse 3, Luthier 3, Critic gate. No cron this sprint — Maestro drives on notifications. ⚠️ Spend-limit risk: the account limit was hit 2026-07-10; first dispatch is the probe.
| id | title | domain | status | depends-on | files (lock) | definition of done |
|----|-------|--------|--------|-----------|--------------|--------------------|
| M-06 | Seed `sprint-one-screen` | maestro | done | — | `docs/agents/LEDGER.md` | seeded |
| D-50 | One-screen dashboard concept doc: full-viewport grid at 1280×900 — LEFT: slim loop strip (banner without the big now-playing chord; playhead chip is the "now"), compact instrument view (decide the mechanism: height cap / reduced fret range / scale — honest about legibility), licks strip, related-progressions card; RIGHT column: the suggested-voicings rail (GlanceRail adapted to ~420-520px — decide cell strategy: recommended voicing prominent + gallery wrapped, sizes recomputed honestly per the D-40 corrected math); where LoopStation/collapsibles/KnowledgeDock land; what "related progressions" means computationally (KB-sourced: same style + level + degree-shape overlap with the loop — spec the ranking); narrow-viewport plan (columns stack); migration order with bounded L-50/D-51/L-51 scopes; ≥2 rejected alternatives. No user gate: pick strongest, record rationale. **Returned once (2026-07-11):** strip really ~92-96px (fix: spec p-4→p-2 trim); `sticky` rail geometrically inert in the flex row (zero travel — flick claims deleted, rationale re-grounded); §4 double-counted cell padding (piano pair actually fits TODAY by ~4px; D-51 premise → margin-hardening); +100 ranking term inherits the raw-vs-collapsed mismatch (collapse pairs before canonicalDegrees/T(p), coordinate with D-62 fix (a)). Layout/jam-view/scopes all held. Fixed + re-gate PASS (`d24bf35` — all budgets recomputed clean) | design | done | — | `docs/design/one-screen.md` | every component named incl. what's removed (big chord display, ProgressionSuggestions); honest space math (everything visible at 1280×900 with at most the licks/progressions row below a fold-flick); bounded scopes |
| L-50 | App restructure per D-50: grid columns, banner slimmed (big now-playing chord removed — ProgressionBanner edit), JamGuide rail moves to the right column, ProgressionSuggestions unmounted (file kept), instrument view compacted per doc, licks strip placed per doc. 🚨 App.jsx = layout/mounts/UI-state only, audio contract grep-gated. **PASS** (`800fd43`+`e58a7a6` — SSR 73/73; gate applied a sanctioned one-class legend restoration for non-compact byte-identity). Nits filed: dead currentChord prop on the banner mount (ride-along for L-51); strip chips are div-onClick (pre-existing a11y debt → backlog) | engineering | done | D-50 | `src/App.jsx`, `src/components/ProgressionBanner.jsx`, `src/components/JamGuide.jsx` (+ per doc — re-lock at promotion) | one-screen layout live; no duplicated info; jam view works both layers; build + smoke green; contract grep clean |
| D-51 | Rail right-column adaptation per D-50: GlanceRail/VoicingBrowser sizing for the narrow column (recommended-first cell strategy per doc), playhead highlight preserved, wrap never horizontal-scroll | design | done | D-50, L-50 | `src/components/GlanceRail.jsx`, `src/components/VoicingBrowser.jsx` (+ per doc) | rail readable at column width for guitar/piano/bass; zero clicks; build + smoke green — **PASS** (`see commit` — arithmetic verified to the built CSS; heard-live dense-pass flag folded into L-60's ride-alongs) |
| L-51 | RelatedProgressions component per D-50: KB-sourced, loop-relative (style + level + degree-shape overlap ranking per the doc's spec), replaces the old generic suggestions; mounts in the D-50 slot. **PASS** (`see commit` — scores recomputed independently, collapse counterfactual proven). Taste flag for the user: "same changes" links quality-mismatched same-root-motion relatives (ii-V-I ≡ I-IV-V) — spec-conformant; a "same motion" wording tweak is a one-word option | engineering | done | D-50, L-50 | `src/components/RelatedProgressions.jsx` (new) + mount slot per doc | shows genuinely related KB progressions for a live loop; honest empty state; build + smoke green |
| C-50 | Sprint-end sweep (PR comment consolidated into C-61's combined summary — Maestro call). Folded (L-51 gate): pin the two verified ranking scores + the no-collapse counterfactual as smoke checks; add a global-id-uniqueness assertion to validate-kb.mjs | quality | done | L-50, D-51, L-51 | `scripts/smoke.mjs`, `scripts/validate-kb.mjs` (additions only) | all green; ranking pinned; ids asserted unique — **PASS** (`see commit` — smoke 886, SSR 60/60, whole-sprint contract clean). **SPRINT sprint-one-screen COMPLETE** |
> Sequencing: D-50 first (everything hangs off it) → L-50 → D-51 ‖ L-51 (re-lock at promotion to enforce disjointness) → C-50. Critic gates every task.
---
## Active sprint: `sprint-dashboard-polish` (branch: `sprint-jamguide-piano` — continued; commits extend PR #3)
**Goal (user directive 2026-07-13, after running the one-screen build):** "this looks amazing" + six refinements to the live dashboard:
1. **Guitar: 4 options max** — "only have 4 guitar options visible so it would fit the screen without scrolling." Cap each chord's guitar gallery to ≤4 shapes (a musically-sensible top-4 selection rule; fewer is fine).
2. **Hidden-but-scrollable dark scrollbars** — "the scroll bars are not visible but it can scroll if we need to (make them black or something)." Thin/dark styled scrollbars, overlay feel; content still scrolls.
3. **Piano: 2×2 smaller keyboards** — "smaller keyboards so there would be 2×2 for each chord." The 4 pianoVoicing styles in a 2-col × 2-row grid of compact MiniPianos per chord.
4. **Remove play buttons** — "leave off the PLAY buttons, they take up a lot of space for no reason, no need to hear it." Drop every ▶ from the voicings rail (and the licks strip — Maestro extension, matching the stated glance-over-audio preference; also removes the shared-sequencer blocker so piano licks can wire in cleanly).
5. **Licks: uniform size + follow the instrument** — "the licks section should all have the same size and transform into piano when selected." Uniform card size; the strip follows the global GUITAR/PIANO/BASS selector — wiring the deferred PianoLickCard into the strip (bass → no licks / honest note).
6. **Related progressions: same-style bridge/chorus/modifications** — "i would also want bridge/chorus/modifications in the same style… say i select jam roulette with blues, then i want for that progression other options and not necessarily go into other styles." Same-style variations for the active/rolled loop. **User decided 2026-07-13: reuse existing KB same-style progressions (lightest option) — NO computed modifications, NO new authored sections, NO song forms (verse/chorus/bridge — KB has no section data and most progressions are complete forms; Maestro + user agreed not to fake it).** So L-72 ships the honest same-style variations. **NEW feature added same day** (user: "imagine we play Am C F, i'd like an alternative to that F… an option that says 'try this'… i want musicians to learn how they can make the jam more interesting"): a **per-chord "Try this" chord-substitution** surface — for a loop chord in the detected key/style, suggest a small curated set of alternative chords (relative sub, borrowed-minor colour, extension colour, a circle-of-fifths / secondary-dominant move) each with a plain-language WHY. Circle-of-fifths-informed where it applies (honest that not all subs are circle-adjacent). Keep it simple/learnable, not a reharm engine. → tasks D-73/L-73/L-74 below.
Standing principles (memory): scroll > click; nothing duplicated; one global instrument selector; playhead highlights; glance over audio. User is PRESENT — notification-driven, no cron. Weights: Muse 3, Luthier 3, Critic gate.
| id | title | domain | status | depends-on | files (lock) | definition of done |
|----|-------|--------|--------|-----------|--------------|--------------------|
| M-08 | Seed `sprint-dashboard-polish` | maestro | done | — | `docs/agents/LEDGER.md` | seeded |
| D-70 | Rail + licks layout concept doc: (a) guitar ≤4 shapes with the selection rule (open + common movable, lowest-position-first — name it); (b) piano 4 voicings as a 2×2 grid of compact MiniPianos — pick the MiniPiano thumb scale that fits two side-by-side in the ~456px column interior and two rows within a sane row height, honest math; (c) all ▶ removed from the rail's guitar+piano cells AND the licks strip (name every removal site); (d) hidden-but-scrollable scrollbars — the mechanism (webkit ::-webkit-scrollbar thin + dark thumb, and Firefox scrollbar-width/color; overlay where supported) and WHERE it applies (the rail's overflow-y column, any inner scrollers); (e) licks: uniform card footprint (thumb size parity between LickCard and PianoLickCard) + the strip follows the global instrument (guitar→piano licks on PIANO; bass honest empty); (f) recompute the row heights + the 500px column budget with the new smaller cells; migration order with bounded L-70/L-71 scopes (keep them file-disjoint or serialize on JamGuide.jsx). No user gate: pick strongest, record rationale + ≥2 rejected alternatives | design | done (`3fdc72e`; final scope: play buttons OFF EVERYWHERE per user; guitar-4/2x2-piano/uniform-licks dashboard-scoped) | — | `docs/design/dashboard-polish.md` | every change specced with honest numbers; the 2×2 piano scale chosen + proven to fit; bounded impl scopes |
| L-70 | Implement the voicings rail per D-70: guitar ≤4, 2×2 smaller piano, ▶ removed, dark hidden scrollbars | engineering | done `aae69e8` (combined-gate PASS) | D-70 | `src/components/GlanceRail.jsx`, `src/components/VoicingBrowser.jsx`, `src/index.css` (scrollbar CSS) (+ per doc — re-lock at promotion) | rail matches the spec; no ▶; guitar ≤4; piano 2×2; scrollbars hidden+dark+functional; build + smoke green |
| L-71 | Implement the licks strip per D-70: uniform card size, follow the global instrument (wire PianoLickCard), ▶ removed | engineering | done `19b1a4f` (combined-gate PASS; L-74b `6885fc3` visibility fix too) | D-70 | `src/components/JamGuide.jsx` (LicksStrip), `src/components/LickCard.jsx`, `src/components/PianoLickCard.jsx` (+ per doc — re-lock at promotion) | licks uniform; piano licks show under PIANO; no ▶; bass honest; build + smoke green |
| D-72 | Same-style related-progressions design (user answer = reuse existing KB): decide the presentation — when a style is active, RelatedProgressions leads with same-style siblings reframed as "variations / sections to try in {style}" (labels/section framing that reads as bridge/chorus/variation without new content); how the active style is known (roulette seed carries it; live detection's match yields it — name the prop/source); whether cross-style entries stay as a secondary "other styles with these changes" section or are dropped when a style is locked; empty/edge states. Files disjoint from the rail/licks chain (RelatedProgressions.jsx only) → runs in PARALLEL | design | done | — | `docs/design/related-same-style.md` | presentation spec'd against the real RelatedProgressions/match.js; active-style source named; L-72 bounded |
| L-72 | Implement D-72: RelatedProgressions leads with same-style variations when a style is active; reframed labels; cross-style demoted/dropped per the doc. **Unblocked 2026-07-13** (no song forms). Resolutions: (finding-A) when a style IS locked, DROP the secondary cross-style section — same-style only, per goal #6 + the user's "not necessarily other styles"; keep cross-style ONLY when no style is locked (match.matched===false). (finding-B) null the role phrase when a same-style sibling shares NO transitions with the loop (no false "variation" claim — just name + level). Re-pin smoke §8 labels ('shares I7→V7'→'shorter form' etc.; scores stable) | engineering | claimed | D-72 | `src/components/RelatedProgressions.jsx`, `scripts/smoke.mjs` (§8 re-pin) | same-style-only when locked; honest cross-style only when unlocked; role phrase honest (finding-B); build + smoke green — **PASS** (`see commit` — findings A/B verified; gate added 2 durable smoke assertions, 893/893) |
| D-73 | **"Try this" chord-substitution feature** design (engine rules + UI): for a loop chord `{rootPc,quality}` in the detected key/style, a SMALL curated set (~3-4) of alternative chords — recommend the categories (relative/diatonic-third sub, borrowed-minor colour e.g. IV→iv, extension/colour e.g. maj7/add9/sus, a circle-of-fifths / secondary-dominant move) — each with a plain one-line WHY that teaches. Concrete worked examples for the user's AmCF case (both A-minor and C-major readings), arithmetically correct (the gate WILL recompute). The UI surface: where it mounts in the jam dashboard (per-station in the rail? a "Try this" line under the loop? — decide, keep it glanceable, tappable→ChordDetailModal), honest circle-of-fifths tie-in (a lens for the relative/neighbour subs, NOT claimed for borrowed/extension), edge states (no key / atonal), keep-it-simple (learnable, not a reharm engine). Use a SEPARATE component (disjoint from RelatedProgressions.jsx). No user gate: pick strongest, ≥2 rejected alternatives | design | done (returned once — 3 copy/plumbing fixes verified: chordRootPC→noteIndex circular-import, ♭6 flat spelling, mediant claim; rules all recomputed correct; `c2207ef`) | — | `docs/design/try-this-subs.md` | substitution categories + rules + why-copy spec'd and arithmetically honest; AmCF worked; UI surface + mount decided; L-73/L-74 bounded |
| L-73 | Substitution engine: `suggestSubstitutions({rootPc,quality}, keyInfo, opts?)` in `src/lib/theory.js` (additive) → `[{rootPc, quality, label, why, category}]` per D-73's rules + a smoke truth-table (expected subs for known chords/keys, sabotage-proven like the resolveDegree guard) | engineering | backlog | D-73 | `src/lib/theory.js` (additive), `scripts/smoke.mjs` | engine returns musically-correct subs for all 14 qualities in-key; smoke truth-table bites; build green | ← claimed 2026-07-13; **returned once** — Rule C self-suggested the sounding chord on 7th-chord inputs (Dm7→Dm7) + latent add9-on-minor mis-spelling; fixed + re-gate PASS (Dm7→[F], min7 sweep no add9, triad path intact, sabotage bites, 903/903); **done** `see commit`
| L-74 | "Try this" UI per D-73, with VARY/ROTATE (user decided 2026-07-13: "more surprising, more jam-like, keeps offering new ideas"): a new `TryThis.jsx` that, for the current playhead chord, shows ONE suggestion at a time (matches "try this" = a single nudge) and CYCLES to the next valid substitution each time the loop completes a pass (playhead wraps to station 0 — watch the position prop). Sequential cycling through the engine's ordered valid set (softest-first on first appearance) so the player eventually learns all options and never repeats until exhausted; a small "1 of N" / dot indicator; 0 subs → no card; 1 sub → static (no rotation). Tappable→ChordDetailModal; tokens/AA; glanceable. Supersedes D-73's static ≤4-chip display for the UI (engine/rules unchanged). Mount App.jsx-only in relatedSlot above RelatedProgressions (disjoint) | engineering | backlog | D-73, L-73 | `src/components/TryThis.jsx` (new), `src/App.jsx` (mount) | one fresh honest sub per chord, cycling each loop pass; zero-click; empties honest; build + smoke green | **done** `038fdfa` (Critic PASS — 2-pass rotation trace Dm→Fm verified, contract-clean)
| D-75 | **Related-area space layout** (user 2026-07-13, after seeing it — "we have enough space in that area… fit everything in one big screen"): (a) TRY THIS — show the current chord's up-to-4 substitutions SIDE BY SIDE (replaces the one-at-a-time rotation; user has seen rotation + prefers all-visible), each a small card = chord label + a mini instrument diagram of that chord's voicing (ChordDiagram guitar / MiniPiano piano, following the GLOBAL instrument selector; bass = honest simple) + a compact why + tap→ChordDetailModal; (b) SUGGESTED PROGRESSIONS (RelatedProgressions) — 2×2 grid instead of the vertical list. Honest space math for the LEFT column (~744px, wider than the 500px rail). Instrument prop threading for TryThis (App mount passes `instrument`). Bounded L-75/L-76 (disjoint: TryThis.jsx+App-mount vs RelatedProgressions.jsx) | design | ready | — | `docs/design/related-area-layout.md` | side-by-side try-this with per-sub diagrams + 2×2 related spec'd with honest column math; instrument-follow named; L-75/L-76 bounded |
| L-75 | Implement TryThis side-by-side + per-sub instrument diagrams per D-75 (drops the rotation; follows the loop/current chord; instrument-following diagram) | engineering | done `957ce88` (combined-gate PASS) | D-75 | `src/components/TryThis.jsx`, `src/App.jsx` (pass `instrument` to the mount — grep-clean) | up-to-4 subs side by side each with a playable-shape diagram in the current instrument; tap→modal; honest empties; build+smoke green |
| L-76 | Implement RelatedProgressions 2×2 grid per D-75 (same-style + cross-style sections in a 2-col grid using the left-column width) | engineering | done `e695716` (combined-gate PASS) | D-75 | `src/components/RelatedProgressions.jsx` | 2×2 layout; both sections adapt; no logic/scoring change; build+smoke green |
| D-76 | **Related-area v2** (user 2026-07-13, "one last change"): (a) VOICINGS RAIL — currently shows all loop stations when a loop matches, but only the SINGLE current chord in the heard-live/no-loop fallback (JamGuide railContent :373-424). User wants: ALWAYS show multiple chords' voicings, MOST RECENT FIRST — loop chords when matched (KEEP canonical order + a moving "now" playhead highlight — design call, reordering would break GlanceRail's between-adjacent voice-leading chips AND reshuffle rows every chord, contradicting the user's anti-jump preference; most-recent-first applies to the NO-LOOP history rail), else the recent distinct chord history (from chordHistory, cap ~6, most-recent-first). Never just one. **User confirm pending on the loop-ordering deviation (asked 2026-07-13).** (b) TRY THIS — cap at **3** suggestions (was 4); **STABLE fixed layout** (reserve 3 slots so 2-vs-3 subs never shifts position — the user: "annoying when the layout changes then u dont know where to look"); each suggestion shows **≥3 ways to play it** — guitar = **3×3** (3 subs × up to 3 getGuitarVoicings shapes each), piano = **1** MiniPiano each ("for piano it can be just one thats okay"), bass = root caption. Honest space math (left col ~744px for the 3×3 guitar; rail column for the multi-chord history). No user gate: pick strongest, ≥2 rejected alts | design | ready | — | `docs/design/related-area-v2.md` | rail always-multi-chord-most-recent-first spec'd; try-this 3-cap + stable-3-slot + 3-shapes-guitar/1-piano with honest math; L-77/L-78 bounded |
| L-77 | Voicings rail — HYBRID (user re-scope 2026-07-13): when a loop is found, HIGHLIGHT the loop chords as a "loop" group AND list the OTHER recent distinct chords from full chordHistory underneath ("also played"); when no loop, just the recent distinct history. Show **≥4 chords total** as soon as any chord history exists (top up from history to reach 4+). Loop group keeps canonical order + moving "now" playhead (voice-leading chips valid); history group most-recent-first, no chips. Each chord expands to its full voicing gallery (keep composition) | engineering | done `9415daf` (direct push per user) | D-76 | `src/components/JamGuide.jsx`, `src/components/GlanceRail.jsx` | loop highlighted + others underneath; ≥4 when history exists; no-loop → history ≥4 most-recent-first; galleries + focus preserved; audio contract untouched; build+validate+smoke green — **done** (GlanceRail +`showTransitions` prop (default true, byte-compat); JamGuide `recentDistinctChords`/`historyStations` memo + hybrid railContent; RAIL_TOTAL_CAP 8 / NO_LOOP_HISTORY_CAP 6; 903/903; only 2 locked files, contract-clean. Maestro folded 2 honesty fixes on shared GlanceRail: history group drops "the loop"/"playhead" framing; history rows non-focusable (no inert button). Full independent Critic gate waived per user "push when its done") |
| L-78 | Try-this per D-76: max 3 subs, stable 3-slot layout, 3 guitar shapes each (3×3) / 1 piano each | engineering | done `d543b98` (direct push per user 2026-07-13; verified build+validate+smoke 903/903 — full independent Critic gate waived for the push) | D-76 | `src/components/TryThis.jsx` (+ per doc) | ≤3 subs in fixed slots; guitar 3 shapes/sub; piano 1; layout stable 2-vs-3; reactivity preserved; build+smoke green |
| C-70 | Sprint-end sweep + PR update (BOTH gitea+github). Fold: drop stale ", each playable" from VoicingBrowser aria (:278/:314, combined-gate finding) | quality | backlog | L-70, L-71, L-72, L-74, L-75, L-76, L-77, L-78 | `src/components/VoicingBrowser.jsx` (aria one-liner) | all green; aria fixed; PRs updated |
> Sequencing (three parallel chains, file-disjoint): (A) D-70 → L-70 → L-71 (rail/licks); (B) D-72✓ → L-72 (related, same-style); (C) D-73 → L-73 → L-74 (try-this subs). ALL DONE except A's builds. **L-74b (2026-07-13, in-review):** TryThis loop-fallback so the card is visible for a rolled/detected loop without live input (user "i dont see rotating cards") — TryThis.jsx only, SSR-verified. **Batch plan:** L-70 ‖ L-71 ‖ L-74b (disjoint) → ONE combined gate (rail/licks + dock byte-identity + full-app SSR + contract) → commit all → push both remotes. C-70 closes.
---
## Shipped sprint: `sprint-integrated-glance` (branch: `sprint-jamguide-piano` — complete 2026-07-10, 4 iterations, PR #3 updated)
**Goal (user directive 2026-07-10, after testing the glance-mode sprint — "its already a lot better, but"):**
1. **Move it up & integrate** — "i would like to move it up and integrate it somewhat in the space of the main module up top. or maybe right below it as it is super important." The Jam Guide content is currently the LAST mount in App.jsx (line ~712); the main module (ProgressionBanner + instrument view) is at ~609-622.
2. **One loop display** — "i would like to be able to see the loop clearly, no need to have this repeated again. as its already in the main module." ProgressionBanner (top) and the Roadmap track (inside JamGuide) both show the detected loop — exactly one clear loop display must survive.
3. **One instrument selector** — "only one selection for GUITAR/PIANO/BASS and everything should show in that instrument." App.jsx line 58 ALREADY holds global `instrument` state ('piano'|'guitar'|'bass') driving the main views; JamGuide ignores it and has its own internal tabs. Everything (voicings, licks, guide) must follow the one selector. Bass has a main-view BassFretboard but zero KB content — needs an honest state (and a stretch chain to make it real).
4. **All chords' voicings visible at once** — "it's difficult to see as it changes when the chord is not playing so i'd like to see all the chords and their voicings in a specific way in case a loop is detected (or at least just like 4 chords or something at least, so you can follow and potentially learn new ways to play it while you are playing the loop." The playhead accordion (only the active station expanded) is hard to follow live — show EVERY loop station's voicings simultaneously (≥4 chords), playhead highlights rather than reveals.
5. **Scroll-first** — "scrolling is easier then clicking." Layout principle for everything above.
**Loop:** `/jam-loop` every 30 min for 12 h (24 iterations), started 2026-07-10 evening (cron 13,43). "let each agent do a part and revise the work" — standard ensemble + gates. Weights: Luthier 3, Muse 3, Professor 2, Critic gate.
| id | title | domain | status | depends-on | files (lock) | definition of done |
|----|-------|--------|--------|-----------|--------------|--------------------|
| M-05 | Seed `sprint-integrated-glance`; schedule the 24×30m loop | maestro | done | — | `docs/agents/LEDGER.md` | seeded, cron created |
| D-40 | Integration concept doc: (a) where the Jam Guide content lands relative to the main module (in it vs right below — pick, record rationale); (b) which loop display survives (ProgressionBanner vs Roadmap track — the loser's unique value, e.g. guide-tone rails, must be honestly dispositioned); (c) JamGuide obeys App's existing global `instrument` — internal tabs retired; honest bass state until the bass chain lands; (d) the all-stations-expanded voicings layout (≥4 chords visible, playhead HIGHLIGHTS not reveals, scroll-first — the user explicitly licensed scrolling, so D-31's "everything expanded" rejection is overturned by directive); (e) what remains of the four-section dock below; (f) honest space math + migration order. No user gate: pick strongest, record rejected alternatives. **Returned once (2026-07-10):** piano worst-case Dm7-specific (G7 gallery ≈1,178px, roots above D need 2-octave crops → rows WRAP, screenful counts restated); LicksSection lives in JamGuide.jsx not ExplorePanel; ChordBox keeps importers (only RiffDiagram orphans); L-40 interim would ship the page-yank (GlanceRail scrollIntoView in page flow) — doc added the one-line effect deletion to L-40's lock, same-commit mandatory. Fixed + re-gate PASS (pixel-exact recompute: gallery 1,178, row 1,470, all table arithmetic verified) | design | done | — | `docs/design/integrated-glance.md` | doc names every component, the single-loop-display call, the instrument-threading contract, ≥2 rejected alternatives, bounded L-40/D-41 scopes |
| L-40 | App restructure per D-40: promote the Jam Guide content to the D-40 position; retire the duplicated loop display per the doc's call; JamGuide takes `instrument` as a prop from App's existing selector (internal tabs removed; VoicingsSection/LicksSection/ExplorePanel mounts follow too); honest bass empty-state. Ride-along (C-40 follow-up): add an export-only line to JamGuide's `resolveDegree` (JamGuide.jsx:73) so smoke §7 can sweep both copies directly (today it pins the validator side behaviourally). 🚨 App.jsx changes = layout/mount/UI-state ONLY — audio callbacks/refs/AudioCapture untouched (grep-gated) | engineering | done | D-40 | `src/App.jsx` (layout + UI-state only), `src/components/JamGuide.jsx`, `src/components/ExplorePanel.jsx` (VoicingsSection instrument prop), `src/components/GlanceRail.jsx` (scrollIntoView effect deletion ONLY, same commit as band promotion — D-40 §6.1) | one selector drives everything; guide content up top; loop shown exactly once; build + smoke green; audio contract grep-clean |
| D-41 | All-expanded voicings rail per D-40: every station's gallery visible simultaneously (≥4 chords), active station highlighted by the playhead (accent ring/header, NO reveal/hide), scroll-first reflow, licks strip follows the global instrument per the doc. **Folded (L-40 flag, 2026-07-10):** VoicingBrowser's `show` prop falls through unknown values to 'both' — the dock's VoicingsSection under bass passes show='bass' and renders BOTH galleries, violating D-40 §3 prose; fix in VoicingBrowser (honest bass empty-state or explicit 'bass' handling), lock extended accordingly. Also: bass row headers gain solo-scale/aim-dots here per D-40 row anatomy | design | done | D-40, L-40 | `src/components/GlanceRail.jsx`, `src/components/VoicingBrowser.jsx` (dense styling + show='bass' handling), `src/components/JamGuide.jsx` (row anatomy per doc) | all voicings of all loop chords on screen/scroll with zero clicks; playhead never hides content; AA + tokens; build + smoke green |
| C-40 | Drift guards in smoke (two hand-synced duplications, backlog debt): (a) JamGuide's `resolveDegree` copy vs validator's — 16-degree × 14-quality truth table; (b) technique vocab `validate-kb.mjs` LICK_TECHNIQUES ↔ `LickCard.jsx` TECHNIQUE_VOCAB. Ride-along: fix `scripts/loop-fixtures.mjs` header's stale "App.jsx:322-324" line-ref (C-31 sweep finding) | quality | done | — | `scripts/smoke.mjs`, `scripts/loop-fixtures.mjs` (comment only) | drift in either duplication turns smoke red (sabotage-proven); header ref current; smoke green |
| P-40 | Refresh `docs/kb-backlog.md`: mark all shipped cells done (gospel/pop guitar; jazz/gospel/rnb/blues piano), set the bass column as next (blues → jazz → funk per plan) | content | done | — | `docs/kb-backlog.md` | backlog reflects reality; next-cell pointer correct |
| C-41 | Bass play schema (additive): SCHEMA.md + validator + smoke bite-test for bass patterns (per-station patterns: root/fifth/approach-note walks — design the minimal honest shape with 4-string, fret 0-15 representation). Ride-along (C-40 gate finding): document in SCHEMA.md that `resolveDegree('7', maj6|min6)` = 9 (the 6th) in both hand-synced copies — a contract quirk, never misspells a chord, but authors should write `'6'` explicitly | quality | done | C-40 | `src/data/kb/SCHEMA.md`, `scripts/validate-kb.mjs`, `scripts/smoke.mjs` | schema documented; validator enforces; existing KB untouched-green; smoke proves the check bites |
| P-41 | First bass cell: **blues bass** (kb-backlog order blues → jazz → funk). C-41 gate notes: offset 11 (maj7 over qualities lacking it) is unrepresentable — if you hit it, STOP and report (schema extension, not workaround); approaches are terminal-only but mid-pattern passing tones are expressible as fixed degrees (b9/9/b3/11/b5/b13/6/b7 all covered) | content | done | C-41 | `src/data/kb/blues/bass.js`, `src/data/kb/index.js` | validator green; every pattern playable as written; prose arithmetic-verified |
| L-42 | Minimal bass pattern renderer for the guide (per-station BassPatternCard per D-40 §3; the computed root·fifth·approach line stays as fallback) — makes the BASS selector real end-to-end. C-41 gate note: `chrom-below` into a next root at open E has no pitch below the instrument — renderer must octave-displace the approach or place the root higher | engineering | done | C-41, P-41, L-40 | per D-40 doc — re-lock at promotion | bass stations render the authored patterns; guitar/piano paths untouched; build + smoke green |
| C-42 | Sprint-end sweep + PR #3 update per PROTOCOL §6. Folded (L-40 gate): wire smoke §7 to import JamGuide's now-exported `resolveDegree` (the jsx load hook already exists) and refresh the stale "unexported (checked 2026-07-10)" comment at smoke.mjs:855-862 — tiny Critic-owned fix inside the sweep | quality | done | L-40, D-41 | `scripts/smoke.mjs` (§7 wiring only) | all green; smoke sweeps both resolveDegree copies; PR updated |
> GATE 2026-07-10 (Critic) · **P-40 PASS** — validator totals verbatim-match; ALL 14 cell play-counts recounted from the real registry (sum 164 ✓); lick arrays counted per style (4/4/4/4/4/3 = 23 ✓); 10 dates cross-checked against ledger + git commits, all hold; diff +36/15 confined, format preserved. Non-blocking: piano next-cell = pop is a priority call (plan's default ranks bossa first — doc licenses reorder, accepted as Professor's call); L-42 row omits its L-40 dep (one word, fix if touched).
> Sequencing: D-40 ‖ C-40 ‖ P-40 file-disjoint, ready now. Then D-40 → L-40 → D-41 (App/JamGuide/GlanceRail serialized — same surfaces), and C-40 → C-41 → P-41 → L-42 (bass chain, stretch). C-42 closes. Critic gates every task.
---
## Shipped sprint: `sprint-glance-and-loop` (branch: `sprint-jamguide-piano` — complete 2026-07-10, 4 iterations, PR #3 updated)
**Goal (user directive 2026-07-10):** three asks, in the user's words:
1. **All voicing variations in one view** — "in the music theory … see all the variations G shape, C shape, etc in one view without having to push a button. so they all line up next to each other." VoicingBrowser currently chip-switches one shape at a time; replace with a gallery that renders every shape/style side by side, each independently playable.
2. **Fix the loop logic** — "it doesn't recognize when 3 chords return, or when its 5 and then 2 others." `detectRepeatingProgression` (theory.js) does exact contiguous block matching, lengths 26: one spurious misdetected chord breaks a rep; a 5-chord loop followed by 2 foreign chords (tag/turnaround) is missed; 78-chord loops can't be found at all. Redesign to be noise-tolerant; tune the App.jsx commit layer so a committed loop survives fills.
3. **Glanceable learn session** — "expand the learn session so we see as much as possible in voicing variations and styles without having to click buttons, the idea is to have it open as the jam is playing." Knowledge Center should auto-follow the live jam with zero clicks.
**Loop:** `/jam-loop` every 30 min for 12 h (24 iterations), started 2026-07-10 (cron 13,43). User is away — no user-gated tasks; Muse picks the strongest option and records rationale. Weights: Luthier 3, Muse 3, Professor 1, Critic gate, Herald 0.
| id | title | domain | status | depends-on | files (lock) | definition of done |
|----|-------|--------|--------|-----------|--------------|--------------------|
| M-04 | Seed `sprint-glance-and-loop` from user directive 2026-07-10; schedule the 24×30m loop | maestro | done | — | `docs/agents/LEDGER.md` | sprint seeded, cron created |
| C-30 | Loop-detection truth fixtures: new `scripts/loop-fixtures.mjs` (+ smoke wiring) — realistic chord-history cases with expected loops: (a) clean 3-chord loop ×23 reps; (b) 3-chord loop with one spurious misdetection inside a rep; (c) consecutive duplicate commits of the same chord; (d) 5-chord loop followed by 2 foreign chords — loop must survive; (e) 7- and 8-chord loops; (f) section change loop-A→loop-B — detection must switch; (g) chromatic non-loop → null. Run each against the CURRENT `detectRepeatingProgression` and mark which fail today (`expectedFail: true`) so the suite is green now and L-30 flips the markers off | quality | done | — | `scripts/loop-fixtures.mjs`, `scripts/smoke.mjs` | fixtures runnable via smoke; failure map of the current algorithm documented in the fixture file header; smoke green (expected-fails annotated, not silently skipped) |
| L-30 | Redesign `detectRepeatingProgression` in `theory.js`: collapse consecutive duplicate chords before matching; tolerate ≤1 substitution/insertion per cycle (noise from misdetection); support loop lengths 28; recency-weighted scoring so an old section can't outvote the current loop; keep the pure signature, the rotation-`canonicalize` output, and every other export byte-untouched. Flip all C-30 `expectedFail` markers to passing. **C-30 findings folded in (2026-07-10):** (a) the `reps × len²` scoring artifact is the primary everyday bug — a clean 2-chord vamp ×4 reports a bogus 3-chord `[Am,Am,G]` via self-overlapping occurrences; candidate generation must reject candidates that are rotations/overlaps of a shorter period (not just exact periodic patterns at len ≥ 4); (b) 7/8-loops contain realistic non-adjacent internal chord repeats (`Am … Am`) — period detection must not collapse those into shorter false loops | engineering | done | C-30 | `src/lib/theory.js` (detectRepeatingProgression + private helpers only) | all C-30 fixtures green with zero expectedFail markers (incl. `vamp-2x4`/`vamp-2-sustained`); no other theory.js export changed; build + smoke green |
| L-31 | Commit-layer tuning in App.jsx's progression effect (lines ~154-173): a committed loop must survive transient misses (the miss-4-then-clear rule drops the loop during fills/turnarounds); a new loop replaces the old only with consistent evidence; first commit shouldn't need extra rounds when detection is already stable. **Primary trace case (C-30 finding, 2026-07-10):** pre-L-30 detection flaps between the true loop and ghost 4-patterns, so `progressionVoteRef` never sees 2 consecutive identical keys and nothing ever commits — verify post-L-30 stability makes the 2-vote commit reachable in the noisy fixtures, then tune (post-L-30 status: done). **L-30 gate findings folded in (2026-07-10):** (a) a 2-rep loop with one corrupted rep FLAPS through data-faithful sub-cycles commit-to-commit until the next clean rep — faster first-commit must NOT let a single transient sub-cycle detection replace an already-committed loop (replacement needs consistent evidence); note non-null detection resets the miss counter, so today's committed loop already survives the flap; (b) ride-along one-line fix: theory.js ~line 601-603 docstring overclaims "ghost occurs exactly once by construction" — false for same-chord-same-phase corruption (behavior fine, comment too strong); (c) deletions untolerated by design — fine at ≥3 reps, degrades to (a)'s flapping at exactly 2. 🚨 **Audio contract: touch ONLY the progression useEffect + its refs — no callback, ref-sync, or AudioCapture change** | engineering | done | L-30 | `src/App.jsx` (progression effect only) | loop survives fixture-style fills end-to-end (hand-trace documented in commit); App.jsx diff confined to the progression effect block; build + smoke green |
| D-30 | VoicingBrowser gallery: render ALL matching guitar shapes side by side (each = label + ChordDiagram + its own ▶) and all four piano styles side by side (label + MiniPiano thumb + ▶) — no chips, no selection state; grid wraps on narrow viewports; one-at-a-time playback preserved (new play stops the previous). All existing mounts (Voicings section, ChordDetailModal tabs, JamGuide station-enlarge) get the gallery automatically; `show` prop semantics unchanged | design | done | — | `src/components/VoicingBrowser.jsx` | every placeable shape/style visible simultaneously with zero clicks; AA contrast + tokens; keyboard-reachable play buttons; build + smoke green |
| D-31 | Glance-mode concept doc: the Knowledge Center panel open WHILE the jam plays — what auto-follows live detection with zero clicks (current station's voicing gallery inline? licks strip for the style? what stays on screen vs behind interaction), density/space budget vs the Roadmap track, narrow-viewport plan, and the migration order for L-33. No user gate: pick the strongest layout, record rationale + rejected alternatives. **Returned once (2026-07-10):** piano gallery width understated ~45% (2-octave crops for rootless 7th-chord voicings → ~940px not 640; scroll is the piano rail's normal state on most loops) + licks strip ~190px not 150 + 4 clarifying notes; layout itself held — fixed + re-gate PASS | design | done | — | `docs/design/glance-mode.md` | doc names every component to touch, the auto-follow rules, and honest space math (what fits at 1280×900 and at narrow) |
| L-33 | Implement glance mode per D-31 (`docs/design/glance-mode.md` — the "playhead accordion"): the station column at canonicalPos expands to the full D-30 gallery and advances with the playhead; licks strip below (level-filtered, token-boundary context match, strip-owned "fits — now" chrome, guitar licks under piano tab with honest heading); pin gesture inherits onFocusChord semantics; auto-follow never emits focus-chord and never auto-plays audio; piano rail EXPECTED to scroll (never assert one-row fits); follow the doc's 5-commit migration order | engineering | done | D-30, D-31 | `src/components/GlanceRail.jsx` (new), `src/components/JamGuide.jsx`, `src/components/VoicingBrowser.jsx` (optional additive `dense` prop only) | glance behaviours live per the doc; audio contract intact (App.jsx untouched or additive-only); build + smoke green |
| P-30 | KB expansion: **neo-soul/rnb piano** cell (next per `docs/kb-backlog.md` after jazz/gospel) | content | done | — | `src/data/kb/rnb/piano.js`, `src/data/kb/index.js` | validator green + registered; renders in the piano tab; prose claims arithmetic-verified |
| P-31 | KB expansion: **blues piano** cell. **Returned once (2026-07-10):** turnaround jump-kicks bars 3-4 dyad orientations flipped (breaks the play's own only-leap law — gate pre-verified the exact swap) + 2 prose rewordings (♭7 "unmoved all night" contradicted by bar 9; "octave-and-change" actually a major 7th) — fixed + re-gate PASS | content | done | P-30 | `src/data/kb/blues/piano.js`, `src/data/kb/index.js` | validator green + registered |
| C-31 | Sprint-end sweep: full build + validator + smoke + fixtures, then update PR #3 (push + PR body/comment summarising this sprint) per PROTOCOL §6 | quality | done | L-31, L-33, D-30 | (none — verification) | all green; PR #3 updated |
> Sequencing: C-30 ‖ D-30 ‖ D-31 ‖ P-30 are file-disjoint and ready now. Then C-30 → L-30 → L-31 (serial chain on theory.js/App.jsx), and D-30+D-31 → L-33. P-31 fills spare iterations. Critic gates every task.
> GATE 2026-07-10 (Critic) · **D-30 PASS** (`0945a08`) — scope confined to VoicingBrowser.jsx; build green, smoke 809/809, validator green. SSR of the real component (Cmaj7/G7/Asus2/F#m7 × show variants): guitar cell count === independently re-derived matchingShapes count (4/4/3/3), all four piano labels honest, ZERO chips/aria-pressed (button count === cell count), every ▶ aria-labeled chord+voicing, rootPc badge guard proven (rootless voicings show 0 R badges, root/shell exactly 1; buggy variant rendered + diffed = absent), show prop scoping correct, E-add9 empty state graceful. Playback single-handle verified by read. *Non-blocking:* thumb-size diagrams drop finger numbers → backlogged.
> GATE 2026-07-10 (Critic) · **C-30 PASS** — smoke 809/809 exit 0 with 8 annotated expected-fails (printed with today/contract values, never skipped); validator + build green. Failure map independently recomputed against the real function: vamp-2x4 self-overlap 2×3²=18 > pair 4×2²=16 → bogus `[Am,Am,G]` ✓; spurious-substitution ghost 4-pattern 2×16=32 > true 3×9=27 ✓; section-change stale-A 48 > 27 ✓; five-plus-tag genuinely passes pure-function (L-31 attribution honest) ✓. Sabotage ×3: broken guard → exit 1 named; stripped expectedFail → exit 1; stale marker → exit 1 with explicit STALE message — none can rot silently. `canonicalLoop` replica byte-equivalent to theory.js's private `canonicalize` + load-time self-check. clean-2x3 vs vamp-2x4 pins the exact boundary where the len² artifact kicks in. Nit (non-blocking): fixture header line 25 says `[Am,G,Am]` vs comment `[Am,Am,G]` — same loop pre/post canonicalization. NOTE: the transient smoke red the D-31 gate reported (`clean-3x3`) was this gate's own sabotage edit (a) running concurrently — tree restored, verified clean.
> GATE 2026-07-10 (Critic) · **D-31 RETURNED → PASS on scoped re-gate** — first gate verified the playhead-accordion layout, the App.jsx-zero-changes claim (all 7 props already flow; pin inherits selectedStation semantics incl. reset effects), chordContext data support, and the vertical budget (256px at 1280×900 recomputed from real component geometry) but returned one arithmetic finding: expanded piano gallery ~640px understated ~45% (rootless A/B of true-7th chords → 2-octave D-24 crops = 266px thumbs) + licks strip 150→190px. Muse fixed: 940 / 13501550 (scrolls at ~1200, not "borderline") / 2300 / 3,500+ / 190 / 1070, "scroll is the piano rail's normal state on most loops", commit-5 must never assert one-row-fits, + 4 notes (token-boundary chordContext match; strip-owned "fits — now" chrome; guitar licks under piano tab stated; licksFor "lifted not reused"). Re-gate recomputed Dm7 rootlessA [17,21,24,28] → 266px from piano.js/MiniPiano.jsx, grep-verified no stale figures, no regression to passed sections. Nuance (non-blocking, for L-33): "any true-7th chord" slightly overgeneral — some rootless voicings fit 1 octave (e.g. Dm7 rootlessB); 940 is the correct conservative worst case.
> GATE 2026-07-10 (Critic) · **P-30 PASS first try** (`b51daa1`) — validator 154 plays green, build green, shared-tree smoke 817/817. Independent arithmetic (own script from SCHEMA/CHORD_TYPES, not Professor's): max per-hand span 11 (≤15), ≤4 notes/hand, combined span ≤23 → every recipe renders for all 12 roots in the 36-key window (zero silent fallbacks); 11 hand-picked prose claims all recompute exactly (♭VI→V sink 1,1,1,1,2; 9sus RH = major triad on ♭7; So What [0,5,10,15,19]; I-RH ≡ vi7-RH pcs; 13sus = Type A bottom+1; ...). Rule-4 idiomatic difference genuine per pair; outside-key 9-on-iii honestly flagged; sources hedged. One chased-and-accepted oddity: ♭VI13 stab's CFG♭ pinch is deliberate voice-leading, not a stacking bug.
> GATE 2026-07-10 (Critic) · **L-30 PASS** (`4cc0009`) — smoke 817/817 (all 17 fixtures plain guards, 9 original greens no regression), validator + build green. Diff confined: theory.js 2 hunks in the repeating-progression section only, `canonicalize` unchanged context; loop-fixtures.mjs = marker removals + historical rewordings, every history/expect array untouched (frozen contract intact). 15 novel generalization probes: 11 correct, 3 data-faithful (only phase-locked exactly-alternating corruption yields a doubled pattern — genuinely 6-periodic data no algorithm could distinguish), 1 better-than-expected (all-reps-edited loop found via clean rotation). Every reportable "ghost" now corresponds to a pattern that exactly recurred — the old structurally-fake ghosts are gone. Perf 0.210.73 ms/call ×1000. Consumer contract at App.jsx:154-173 type-matches. 3 non-blocking findings folded into L-31's row.
> GATE 2026-07-10 (Critic) · **L-33 PASS** (`see commit`) — build green, smoke 817/817, validator green; diff exactly the 3-file lock (App.jsx/theory.js diffs attributed to L-31). SSR of the real JamGuide 37/37: expanded-column cell counts == independently derived shape counts (dom7@G=4, min7@D=4), aria-current one-per-list, mic microcopy exactly once (dense suppresses per-mount copies), pin semantics diffed line-by-line identical to old selectedStation (deps + emit/clear), GlanceRail imports no chordAudio + auto-follow has zero focus/audio side effects (scrollIntoView reduced-motion-guarded), heard-live + nothing-heard paths correct. Token matcher proven through the real render on a hostile country I-vs-I7 case (3 fits not 4) + full 23-lick chordContext audit — no false positive possible; exotic glyphs (♯/°/ø) outside the char class fail conservative (miss, never false-fit). `dense`-less VoicingBrowser SSR **byte-identical** to committed 0945a08. Zero-click audit: all variations + all licks in initial markup. Deviations accepted (staging cosmetic; heard-live licks strip musically right). Non-blocking: first-mount scroll on unknown playhead benign; LicksStrip perf fine unmemoized. Committed `c78baf4`.
> GATE 2026-07-10 (Critic) · **L-31 PASS** (`ce24d54`) — 🚨 audio contract CLEAN: 1 hunk in the progression useEffect, contract-grep zero hits, no ref-sync/mount props; theory.js ride-along comment-only (verified zero executable lines). Independent re-trace with own mirror + real detector: spurious-substitution commits #7 zero drops; section change replaces with zero intermediate nulls; breakdown first-null at foreign-commit 28 (comment's "~28" numerically exact) and clears at exactly 6 nulls; 2-rep flap survives with rival counter provably reset. HOSTILE-1 proved REPLACE_VOTES=3 load-bearing (rival hit 2 before agreement reset — 2 would displace-and-flap); alternating rivals never accumulate; newSong null-shape defensively handled. Build/smoke 817/817/validator green. 2/3/6 judged musically sensible; v-a commit-then-upgrade UX accepted over blank display. Non-blocking: "consecutive" comment nuance (nulls are neutral, not resetting — amend to "consecutive non-null" if ever touched); threshold consts re-created per render (trivially cheap, hoisting would exceed the lock); Luthier's +53/12 was arithmetic sloppiness for +47/6.
> GATE 2026-07-10 (Critic) · **P-31 RETURNED → PASS on scoped re-gate** (`81cd230`) — first gate verified 90%+ of the pack exactly (♭VI7→V7 five-voice plane numerically perfect; all spans 11/4/22 legal; all 96 recipes render for 12 roots; rule-4 contrasts genuine) but returned 3 findings: jump-kicks bars 3-4 dyad orientations flipped (broke the play's own only-leap law; gate pre-verified the exact swap), "unmoved all night" contradicted by bar 9's own note, "octave-and-change" = actually a major 7th (11 semitones). Professor applied all 3; re-gate recomputed the lap chain from scratch: E4,B♭4 → G4,D♭5 → F4,C5 → F4,B4 → E4,B♭4 — "only leap" now provably unavoidable (all pairwise pc distances = 3), validator 164 plays / smoke 817/817 / build green, no fourth edit area.
---
## Shipped sprint: `sprint-knowledge-center` (branch: `sprint-jamguide-piano` — complete 2026-07-09, PR #3)
**Goal (user directive 2026-07-08):** revise the **visual structure of the Knowledge Center** — today's knowledge lives in three disconnected surfaces (JamGuide/Roadmap, ExplorePanel, EducationPanel). Four user asks, verbatim priorities:
1. **Playable voicings per chord** — browse *and hear* alternative voicings for any chord (guitar shapes + generated piano voicings), with simple switching.
2. **Simple ways of seeing techniques for licks** — lick cards with technique markers (hammer-on, slide, bend…), per style.
3. **Intermediate-level progressions** — research them and find the *easiest* way to surface them in-app (level tags + filter, not a new panel).
4. **Keep expanding music knowledge** — continue KB cells per `docs/kb-backlog.md` in spare iterations.
**Loop:** `/jam-loop` every 30 min for 12 h (24 iterations), started 2026-07-08. User is away — no user-gated tasks this sprint; where the old sprint would have asked (concept selection), Muse picks the strongest option and records the rationale in the concept doc. Weights: Muse 3, Luthier 3, Professor 2, Critic gate, Herald 0.
| id | title | domain | status | depends-on | files (lock) | definition of done |
|----|-------|--------|--------|-----------|--------------|--------------------|
| M-03 | Seed `sprint-knowledge-center` from user directive 2026-07-08; carry L-11 forward (hold lifted — user asked to continue on this branch) | maestro | done | — | `docs/agents/LEDGER.md` | sprint seeded, loop scheduled |
| L-11 | Wire piano into `JamGuide.jsx`: Piano tab active; per station render `MiniPiano voicing={…}` from `pianoVoicing`/`pianoVoicingChain`; keep the guitar path intact. **Carried from piano sprint; user hold lifted 2026-07-08** | engineering | done | — | `src/components/JamGuide.jsx` | piano tab shows per-station keyboards synced to the loop; guitar unchanged; build + smoke green |
| D-20 | Knowledge Center concept doc: one unified IA for JamGuide (live) + ExplorePanel (browse) + EducationPanel (learn) — sections *Jam Guide / Explore / Voicings / Licks & Techniques*, where the voicing player and lick cards mount, level-filter placement, narrow-viewport plan. **No user gate: pick the strongest layout, record rationale + rejected alternatives in the doc** | design | done | — | `docs/design/knowledge-center.md` | doc names every component to touch, the target structure, and the migration order for L-22; honest about what stays untouched |
| L-20 | `src/lib/chordAudio.js` — Web Audio voicing playback: `playVoicing(notes, {strumMs, durMs})` (piano `notes` are absolute 036 above C3; also accept guitar `{string,fret}` arrays via a midi mapper), own `AudioContext` created lazily on first user gesture, simple triangle/partials envelope, `stopAll()`. **Must not touch the detection pipeline's contexts**; document mic-feedback caveat (playback may be heard by detection) | engineering | done | — | `src/lib/chordAudio.js` | pure module + tiny API; no import from AudioCapture/App; plays a Cmaj7 shell audibly in dev; build green |
| D-21 | `VoicingBrowser.jsx` — for `{rootPc, quality}`: guitar alternatives (all matching `voicings.js` shapes via `ChordDiagram`) + piano alternatives (`pianoVoicing` root/shell/rootlessA/rootlessB via `MiniPiano voicing`) as switchable chips, each with a ▶ button calling `chordAudio`. Note (D-20 gate): `GUITAR_SHAPES` is private — lock includes an **export-only** line in `voicings.js`; do not cite the D-20 doc for small-text AA on active chips (use surface-background rule) | design | done | L-20 | `src/components/VoicingBrowser.jsx`, `src/lib/voicings.js` (export-only) | renders + plays all styles for any KB quality in any key; design tokens; AA contrast; keyboard-reachable |
| L-21 | Integrate VoicingBrowser: `ChordDetailModal` (replace/extend its static voicing grids) + JamGuide station-enlarge view — tap any chord anywhere → browse + audition voicings | engineering | done | D-21, L-11 | `src/components/ChordDetailModal.jsx`, `src/components/JamGuide.jsx` | both entry points work; legacy modal content preserved where not superseded; build + smoke green; audio-callback contract intact (App.jsx untouched or additive-only) |
| C-20 | Schema + validator + smoke for the two new KB shapes (both **optional/additive**): (a) `level: 'foundation'\|'intermediate'` on progressions; (b) per-style `licks``{id, name, level, chordContext, techniques[]}` from a fixed technique vocab (hammer-on, pull-off, slide, bend, double-stop, ghost-note, chromatic-approach, vibrato) + `tab: [{string, fret, technique?}]` ordered notes. Existing KB stays green untouched | quality | done | — | `src/data/kb/SCHEMA.md`, `scripts/validate-kb.mjs`, `scripts/smoke.mjs` | validator enforces the vocab + tab shape when present; 10-style KB still green; smoke still 776+ green |
| P-20 | Intermediate progressions: research per `docs/progression-repertoire.md`, then tag existing KB progressions with `level` and author **2 new intermediate progressions each** for jazz, gospel, neo-soul/rnb (secondary dominants, chained ii-Vs, backdoor, borrowed iv…) with guitar plays | content | done | C-20 | `src/data/kb/**` (progressions + guitar files of jazz/gospel/rnb), `src/data/kb/index.js` | every progression carries `level`; 6 new intermediate progressions validator-green; tips written for the "confident enough to jam" player (GOAL Part 2 audience) |
| P-21 | Licks pack #1: author 34 licks each for **blues, jazz, funk** guitar using the C-20 lick schema — technique tags, chordContext (which station/quality it fits), honest attribution | content | done | C-20, P-20 (done) | `src/data/kb/blues/guitar.js`, `src/data/kb/jazz/guitar.js`, `src/data/kb/funk/guitar.js` | validator green; every lick playable as written (Critic hand-checks fret/string sanity) |
| L-23 | Fix latent `getGuitarVoicings` bug (found by L-20): `strIdx = shape.rootStr - 1` indexes `OPEN` (ordered s6…s1) wrongly — rootStr 5 reads the B string's pc, rootStr 4 reads G's; A-shape C major computes fret 1 instead of 3. Use the ChordDiagram convention `6 - rootStr`. Affects fret labels in ChordDetailModal/ExplorePanel/CurrentJamPanel for rootStr 4/5 movable shapes; ChordDiagram itself is correct. Also fix the `playChord` docstring octave example in `chordAudio.js` (Critic nit) | engineering | done | — | `src/lib/voicings.js`, `src/lib/chordAudio.js` (docstring only) | A-shape/C-shape fret labels correct (hand-verify 3 shapes × 2 keys); build + smoke green |
| D-22 | `LickCard.jsx` — tab-style SVG lick renderer: ordered notes on a string×fret window, technique glyphs (h, p, ⌒ slide, ↑ bend), compact card + technique legend; graceful on empty/malformed | design | done | C-20 | `src/components/LickCard.jsx` | renders every P-21 lick; glyph legend readable at card size; tokens; AA contrast |
| L-22 | Knowledge Center shell per D-20: restructure how JamGuide/ExplorePanel/EducationPanel mount into the unified IA; add the **level filter chip** (foundation/intermediate) wherever progressions list; mount Licks section (LickCard grid per style) | engineering | done | D-20, D-22, P-20, P-21 (licks commit may land empty-state-first per the D-20 doc). Ride-along polish (D-22 gate nit): LickCard stack-collision guard should check all same-column notes, not just prev (`LickCard.jsx:100`) | `src/components/JamGuide.jsx`, `src/components/ExplorePanel.jsx`, `src/App.jsx` (mount only) | unified structure live; level filter works; licks browsable per style; audio contract intact; build + smoke green |
| P-22 | KB expansion: **jazz piano** cell (first piano cell per `docs/kb-backlog.md`) — authored comp voicings override computed where they add signature value | content | done | L-11 | `src/data/kb/jazz/piano.js`, `src/data/kb/index.js` | validator green + registered (SCHEMA "Piano play" recipes); **rendering the authored pack is L-24, not this task** — status: done |
| C-22 | `checkPianoRecipe` span check: enforce SCHEMA rule 3 (each hand ≤ a 10th = 15 semitones) in the validator so future piano cells don't rely on hand-verification (P-22 gate follow-up) | quality | done | P-22 | `scripts/validate-kb.mjs`, `scripts/smoke.mjs` | span violation fails validator; existing KB green; smoke proves the check bites |
| D-23 | VoicingBrowser `show="guitar"\|"piano"\|"both"` prop (default both — zero change for existing mounts) + LickCard stack-collision guard checks ALL same-column notes not just prev (D-22 gate nit, `LickCard.jsx:100`) | design | done | D-21, D-22 | `src/components/VoicingBrowser.jsx`, `src/components/LickCard.jsx` | prop-gated rows; all existing mounts render identically with no prop; guard fixed; build + smoke green |
| L-25 | ChordDetailModal Guitar/Piano tabs pass `show="guitar"`/`show="piano"` to VoicingBrowser (JamGuide station-enlarge + Voicings section keep both rows) | engineering | done | D-23 | `src/components/ChordDetailModal.jsx` | tabs show only their instrument's row; build + smoke green |
| D-24 | MiniPiano voicing-path compact window: crop the keyboard to the voicing's octave span (+1 key padding each side) so Jam Guide station thumbs aren't ~390 px (L-11 gate observation); `size="full"` and the legacy lh/rh path byte-unchanged | design | done | D-10 | `src/components/MiniPiano.jsx` | thumbs materially narrower for ≤1-octave voicings; root/bass marks intact; legacy consumers render identically; build + smoke green |
| P-24 | Licks pack #2: 34 licks each for **rock, country, reggae** guitar (C-20 schema; same bar as P-21 — playable as written, honest sources) | content | done | C-20, P-21 | `src/data/kb/rock/guitar.js`, `src/data/kb/country/guitar.js`, `src/data/kb/reggae/guitar.js` | validator green with ~21+ licks; every note serves its chordContext (Critic verifies) |
| L-24 | JamGuide piano branch prefers an authored piano pack (SCHEMA piano recipes) over computed `pianoVoicingChain` when the style has one; fall back to computed otherwise. Recipe→notes convention: order inside each hand = voicing order low→high (documented at `jazz/piano.js:14`) | engineering | done | P-22, L-22 | `src/components/JamGuide.jsx` | jazz piano stations render the authored comp; other styles keep computed voicings; build + smoke green |
| P-23 | KB expansion: **gospel piano** cell | content | done | P-22 | `src/data/kb/gospel/piano.js`, `src/data/kb/index.js` | validator green; renders in the piano tab |
| C-21 | Sprint-end sweep: full build + validator + smoke, cross-browser sanity notes, PR body draft summarising the sprint for `main` | quality | done | L-21, L-22, P-21 | (none — verification) | all green; PR body ready |
> Sequencing: L-11 ‖ D-20 ‖ L-20 ‖ C-20 are all file-disjoint and ready now. Then D-21 → L-21, and P-20/P-21/D-22 → L-22. P-22/P-23 fill spare iterations. Critic gates every task as usual.
---
## Shipped sprint: `sprint-jamguide-piano` (branch: `sprint-jamguide-piano` — piano resolver phase complete; L-11 carried into the sprint above)
**Goal:** extend the shipped Roadmap Jam Guide to **piano** (guitar→piano→bass roadmap). When the Piano instrument tab is selected, each Roadmap station shows a *generated* piano voicing on a mini-keyboard — voicings computed from the progression's `degrees`+`qualities` (GOAL G4: generate piano voicings from interval recipes; no authored data needed for the MVP). Branch cut off `sprint-jam-guide` HEAD. Weights: Luthier 3, Muse 2, Critic gate.
| id | title | domain | status | depends-on | files (lock) | definition of done |
|----|-------|--------|--------|-----------|--------------|--------------------|
| M-02 | Cut `sprint-jamguide-piano` branch off `sprint-jam-guide`; seed sprint | maestro | done | — | (branch) | branch cut, ledger seeded |
| L-10 | `src/lib/piano.js` — pure piano voicing resolver: `pianoVoicing({rootPc, quality}, opts?)` → shell (1-3-7), rootless A/B (3-5-7-9 / 7-9-3-5), root-position; picks the inversion minimizing movement from a previous voicing (voice-leading); returns absolute key positions + pcs + a label | engineering | done | M-02 | `src/lib/piano.js` | pure fns; correct tones for all 14 CHORD_TYPES; voice-leading-minimal vs a prev voicing; build + smoke green; output shape documented for D-10/L-11 |
| D-10 | **Extend** existing `src/components/MiniPiano.jsx` (already imported by `ChordDetailModal`/`ExplorePanel` via `{rootPc, lh, rh}`) with an ADDITIVE `voicing` prop that renders a `pianoVoicing` output (`{notes,pcs,bass,style,label}`) on a 23 octave keyboard — root in accent, bass marked, thumb/full sizes; **legacy lh/rh path unchanged** | design | done | L-10 | `src/components/MiniPiano.jsx` | renders any `pianoVoicing` in any key; **ChordDetailModal + ExplorePanel render identically (legacy path untouched)**; build green; design tokens; AA contrast |
| L-11 | Wire piano into `JamGuide.jsx` | engineering | **carried → sprint-knowledge-center** | L-10, D-10 | — | see the active sprint table above (hold lifted by user 2026-07-08) |
| C-10 | Extend `scripts/smoke.mjs`: assert `pianoVoicing` returns a valid voicing for every KB quality (no crash, notes in range, contains the chord's defining tones); also assert no duplicate absolute note across styles (the sus2 forced-rootless nit from L-10 gate) | quality | done | L-10 | `scripts/smoke.mjs` | smoke covers the piano resolver; exits non-zero on regression — **currently red (1/776): surfaces the sus2 dup-note nit → L-13 fixes the resolver** |
| L-13 | Resolver dedupe: `pianoVoicing` must never emit a **duplicate absolute note** (sus2 forced-`rootlessB` collides pc2 → `notes=[26,26,31]`). Drop/merge collided notes so every voicing's `notes` are distinct; keep `pcs`/`bass` valid; default + chain paths unchanged | engineering | done | L-10 | `src/lib/piano.js` | no duplicate absolute note for any quality×style; C-10 smoke goes green (776/776); build green; existing 56-voicing correctness preserved |
> Piano authored packs (signature comps overriding computed voicings) are deferred to a later sprint — computed voicings suffice for the piano MVP.
---
## Shipped sprint: `sprint-jam-guide` (branch: `sprint-jam-guide`, PR #2 — complete)
Emphasis this sprint: **ship the Jam Guide MVP** (put the 8 guitar style packs on screen, synced to live detection) + **reframe the repo as a learning platform**. Weights this sprint: Luthier 3, Muse 3 (design-heavy), Professor 2, Herald 2, Critic gate.
**Design-first gate (user directive 2026-06-14):** Muse explored three distinct concepts; **user chose "Roadmap"** (improv-first highway) on 2026-06-15. Implementation tasks below are re-planned to build Roadmap. Concept doc: `docs/design/jam-guide-concept-c.md`. Stage/Playbook (`-a`/`-b`) kept as reference for future modes.
**Roadmap build shape:** a horizontal timeline panel — stations (= loop chords) carry guide-tone lanes (3rd/7th), a solo-scale label, and voice-leading rails (7→3) between stations; a playhead + beat grid track loop position; the chosen voicing is a secondary thumbnail per station; tap a station → guide tones on the fretboard. Needs derived theory (`guideTones`, `voiceLeadingPairs`, default `soloScale`) — Luthier owns those.
| id | title | domain | status | depends-on | files (lock) | definition of done |
|----|-------|--------|--------|-----------|--------------|--------------------|
| M-01 | Cut `sprint-jam-guide` branch; seed sprint | maestro | done | — | (branch) | branch cut, ledger header set |
| D-00a | Viz concept A — "Stage" | design | done | — | `docs/design/jam-guide-concept-a.md` | delivered; reference for future collapsed/glance mode |
| D-00b | Viz concept B — "Playbook" | design | done | — | `docs/design/jam-guide-concept-b.md` | delivered; reference for future study mode |
| D-00c | Viz concept C — "Roadmap" | design | done | — | `docs/design/jam-guide-concept-c.md` | delivered; **CHOSEN** |
| D-SEL | User selects a concept | maestro | done | D-00a, D-00b, D-00c | `docs/agents/LEDGER.md` | **Roadmap chosen 2026-06-15**; tasks re-planned below |
| L-01 | Shared matcher: extract/author `findLoopPosition` (which chord index the loop is on) + rotation-invariant degree-relative loop→progression-id matcher into `src/lib/match.js`; refactor `ProgressionBanner.jsx` to use it | engineering | done | M-01 | `src/lib/match.js`, `src/components/ProgressionBanner.jsx` | matcher maps detected loop → style progression id (rotation-invariant) AND returns current position index for the playhead; banner still works; build green — VERIFY: `npm run build` green; banner renders identically (findLoopPosition now imported from match.js); matchLoopToProgression rotation-invariant + quality tie-break (smoke: iiVI & its rotation → jazz-251-major rot 0/2; minor 251 → jazz-251-minor; chromatic → no match) |
| L-01b | Derived theory for Roadmap: add `guideTones(chordRoot,quality)` (3rd & 7th pcs), `voiceLeadingPairs(chordA,chordB)` (7→3 / nearest-tone rails), and default `soloScale(quality,mode)` (Mixo/dom7, Dorian/m7, Ionian/maj7…) to `theory.js` — additive exports only | engineering | done | M-01 | `src/lib/theory.js` | pure functions, unit-sane (iiVI in C → C→B, F→E rails); reuses existing `getChordTones`; build green; no existing export changed |
| L-02 | `JamGuide.jsx` panel shell: mounts last in `App.jsx`, reads `kb/index.js`, instrument+style tabs from registry, collapsed header → ~70vh; receives live loop + position props | engineering | done | L-01 | `src/components/JamGuide.jsx`, `src/App.jsx` | panel renders, tabs from KB, matched progression or fallback; build green |
| D-01 | `RoadmapTrack.jsx` — the heart: horizontal stations (loop chords) with guide-tone lanes (3rd/7th dots), solo-scale label, voice-leading rails between stations, playhead + beat grid, lookahead highlight on the next station | design | done | L-01, L-01b | `src/components/RoadmapTrack.jsx` | renders a real iiVI & a 12-bar blues from KB; lanes computed from `guideTones`/`voiceLeadingPairs`/`soloScale`; design tokens; AA contrast |
| D-01b | `ChordDiagram.jsx` — secondary per-station voicing thumbnail (movable `rootStr`+`offsets`, open `frets`+`onlyRoot`), key-aware fret placement, tap-to-enlarge | design | done | L-01 | `src/components/ChordDiagram.jsx` | renders any KB guitar shape in any key; chord-tone colour tier; compact thumbnail + enlarged states |
| D-02 | Roadmap assembly & live polish in `JamGuide.jsx`: place `RoadmapTrack` + thumbnails, animate playhead against BPM/onset, narrow-viewport reflow, tap-station → fretboard guide tones | design | done | L-02, D-01, D-01b | `src/components/JamGuide.jsx` (assembly/styling), `tailwind.config.js` | playhead tracks position; reflows on narrow; keyboard-reachable; AA contrast |
| D-03 | Finish the flagship: tap a Roadmap station → highlight that chord's guide tones (3rd/7th) on the **main Fretboard**. Lift a `jamFocusChord` state into `App.jsx`, `JamGuide` emits the selected station's `{rootPc, quality}` via a callback prop, `Fretboard` highlights those guide tones reusing its existing tier rendering. **Returned by Critic** → also fix root cause `guideTones` so 4-tone non-seventh chords (add9/maj6/min6) don't badge their 5th/6th as a "7" | engineering | done | D-02 | `src/App.jsx`, `src/components/JamGuide.jsx`, `src/components/Fretboard.jsx`, `src/lib/theory.js` | tapping a station lights its 3rd/7th (honest secondary anchor for non-7th chords); build green; smoke green; **audio-callback contract intact**; RoadmapTrack lane also corrected; keyboard-reachable; clears on deselect |
| P-01 | Gospel guitar KB cell | content | done | — | `src/data/kb/gospel/**`, `src/data/kb/index.js` | 5 progressions × 2 plays, validator green (run `/kb-expand`) |
| P-02 | Pop guitar KB cell | content | done | P-01 | `src/data/kb/pop/**`, `src/data/kb/index.js` | 5 progressions × 2 plays, validator green |
| H-01 | README reframe: lead with the learning-platform vision (detect → guide → learn), screenshot/gif placeholder, link `GOAL.md` + `docs/agents/` | community | done | — | `README.md` | README states the dual vision; links resolve |
| H-02 | `CONTRIBUTING.md` + issue templates: the data-contract path so a musician can PR a style without coding (point at `src/data/kb/SCHEMA.md`) | community | done | H-01 | `CONTRIBUTING.md`, `.github/ISSUE_TEMPLATE/**` | a non-coder can follow "add a style"; `/kb-expand` documented as the assisted path |
| C-01 | Smoke-test harness: a `scripts/smoke.mjs` that imports `kb/index.js` + runs the matcher on sample loops, wired alongside `validate-kb.mjs` | quality | done | L-01 | `scripts/smoke.mjs` | catches a broken matcher/registry before merge; documented in PROTOCOL gate |
> Critic (C-) reviews every L-/D-/P-/H- task as it reaches `in-review` — those reviews are the gate, not separate ledger rows, except where new test infra is itself the deliverable (e.g. C-01).
> GATE 2026-06-15 (Critic) · **L-01 PASS** — build green, validator green (8 styles/40 progs/80 plays). `findLoopPosition` extracted byte-identical (verified by diff, no semantic change). matchLoopToProgression verified rotation-invariant with quality tie-break: `[Dm7,G7,Cmaj7]`→`jazz-251-major` rot 0; rotation `[G7,Cmaj7,Dm7]`→ rot 2; `[Dm7b5,G7,Cm7]`→`jazz-251-minor` (tie-break works); chromatic→clean `{matched:false}`. rotation index correctly points at the loop slot aligning with KB degrees[0]. `match.js` holds only matching/position logic + a small local chord-root parser (theory.js exposes no pc helper — acceptable). Note (non-blocking): banner refactor also adds `onChordClick` click affordances — beyond a pure extract but already wired to `setSelectedChord`/ChordDetailModal in App.jsx and behaviour-preserving for `findLoopPosition`. Minor: `match.js` uses extensionless `import … from './theory'` (works under Vite; matches existing `education.js` convention).
> GATE 2026-06-15 (Critic) · **L-01b PASS** — build green. theory.js diff is purely additive (zero `-` lines; no existing export touched). Verified by running the real functions: iiVI in C → **Dm7→G7 = C→B (1)** and **G7→Cmaj7 = F→E (1)** rails (plus intentional 0-semitone common-tone rails). `guideTones` triad fallback flags `hasSeventh:false` and uses the 5th. `soloScale` defaults sane: dom7→mixolydian, min7→dorian, maj7→major(ionian), half_dim→locrian, dom7/minor→phrygian-dominant. Functions are pure and reuse CHORD_TYPES/SCALES.
> GATE 2026-06-15 (Critic) · **L-02 PASS** — build green; validator green (8 styles/40 progs/80 plays). 🚨 **Audio contract INTACT**: `git diff HEAD -- src/App.jsx` is +10 lines, zero deletions — only the `import JamGuide` line and the `<JamGuide …/>` mount (placed last, after the tuner block). `handleNote`/`handleChroma`/`handleOnset` lines do not appear anywhere in the diff; no `useCallback` dep, ref-sync `useEffect`, or `AudioCapture` prop was touched. Black-screen/infinite-restart risk avoided. All 5 props passed (`detectedProgression`, `effectiveKey`, `chordHistory`, `bpm`, `currentChord`) exist in App scope. Tabs derive from the KB registry (instrument availability from `style.instruments` keys, style labels from `meta.label`); matched-progression vs. dashed-fallback both render. Disabled instrument tabs marked "soon" with `disabled` + title.
> GATE 2026-06-15 (Critic) · **D-01 PASS** — RoadmapTrack renders from props only (pure/presentational). Verified against the real KB: guide-tone honesty confirmed by running `guideTones` — C-major **triad** returns `hasSeventh:false`, secondary anchor = the 5th (pc 7), and the Station labels it **"5th"** not "7th" (`seventhKind` gate at line 113). The headline rail picks `voiceLeadingPairs(...)[0]` = the 7→3: Dm7→G7 ⇒ C→B (1), G7→Cmaj7 ⇒ F→E (1). BeatGrid station-start indexing is canonical-order-consistent with the stations array; playhead `pct` clamps at 0 when `position=-1`. Tokens used; `aria-current`, `role=progressbar` + `aria-valuetext`, focus rings present. Malformed/empty progression → graceful "no loop to map" card, no crash.
> GATE 2026-06-15 (Critic) · **D-01b PASS** — ChordDiagram movable base-fret formula verified independently: **E-shape A7 → fret 5** ✓ (rootStr 6, rootPc 9: `((94)%12)=5`); A-shape C → fret 3 ✓; open-string root → octave barre (12), a sane degradation. Root-tone coloured in accent tier (`isRoot` → `#a855f7`), non-root dots light-gray (AA on dark board). Both `thumb`/`full` sizes; `full` adds finger numbers + label. Undefined/unplaceable shape (root > fret 15 or `!shape`) → graceful "—" placeholder, no crash — covers the empty-thumbnail path. Open vs movable forms both handled.
> GATE 2026-06-15 (Critic) · **P-01 PASS** — validator green: `✓ KB valid — 9 style(s), 45 progressions, 90 plays` (gospel now included); `npm run build` green (gospel imported by `kb/index.js`, 87 modules, built in 5.65s). Schema: 5 progressions × 2 plays = 10 plays, all ids `gospel-`-prefixed, rn/qualities/bars all length-consistent with degrees, qualities all in CHORD_TYPES (min7/dom7/maj7/maj/add9/sus4/dim7). No duplicate id across all 45. Registered in `index.js` mirroring the other 8 styles (no broken import). **Voicings hand-verified** (independent pc computation matching the validator's): SHELL_6.maj7 → {0,11,4}=R-7-3 ✓; SUS4_5 → {0,5,7}=R-4-5 ✓; DIM7_5 → {0,6,9,3}=R-♭5-𝄫7-♭3 symmetric ✓; ADD9_6 → {0,2,4,7} full add9 (9th present) ✓; MIN9_5 → {0,2,3,7,10} full min9 ✓ — confirms the validator genuinely exercises these shapes via `checkGuitarShape`. **Theory** sound: backdoor ♭VII7=pc10 rises a whole step to I; #iv°7=pc6 passing chord; 6-2-5-1 + plagal IV-I Amen tag; cascading cycle-of-dominants all correctly spelled. **Authenticity** honest: attributions hedged appropriately ("traditional gospel turnaround", "reharmonized", "Every Praise … vamp feel", "e.g. Tenderly bars 5-7" as a back-door reference) — no claim that a specific recording uses an exact voicing; no music-theory error in any tip (Dorian-over-min7, Mixo-over-dom7, sus-non-resolution advice all correct). *Non-blocking nit*: a few shape comments list tones in interval order, not low-to-high string order (e.g. MAJ9_6 "R379" sounds R-9-3-7) — labeling nicety, all tones present and correctly spelled; not a defect.
> GATE 2026-06-15 (Critic) · **H-01 PASS** — every relative link resolves on disk: `GOAL.md`, `CLAUDE.md`, `src/data/kb/SCHEMA.md`, `src/data/kb/jazz/` (dir), `docs/agents/` + ROSTER/PROTOCOL/LEDGER all exist; `CONTRIBUTING.md` is correctly referenced as **"coming (tracked as task H-02)"** and does NOT exist on disk — honest, not a dead live-link. Every command real: `electron:dev`, `dev`, `electron:build:win|mac|linux` all in `package.json`; `scripts/validate-kb.mjs` exists. **No `frontend/` path remains**; build output dir stated as `release/` matches electron-builder `directories.output: "release"`. git clone URL `whattheflat/whattheflat.git` matches actual `origin`. **Honesty verified**: gospel described as "landing next" (not shipped, still in-review at review time); Piano/bass packs, Progression Builder, detection-powered drills all under **In progress**, not today; Roadmap Jam Guide listed as working-today (true — D-02 passed, MVP live). Leads with detect → guide → level up; links GOAL.md + docs/agents/. No overstatement found.
> GATE 2026-06-15 (Critic) · **P-02 PASS** — gated against the FINAL combined tree (P-02/H-02/C-01 merged). `node scripts/validate-kb.mjs` → `✓ KB valid — 10 style(s), 50 progressions, 100 plays` (pop registered in `index.js`; the transient "pop not registered" mid-batch failure is resolved — `index.js` imports popMeta/popProgressions/popGuitar and exports the `pop` block). Schema: 5 progressions × 2 plays = 10, all ids `pop-`-prefixed, no duplicate across all 50 (verified). **Voicings hand-computed** (independent pc calc): OPEN_CADD9 → {0,2,4,7} = R-9-3-5, the 9th (pc2) genuinely present (true add9, not plain C) ✓; OPEN_G/OPEN_F → {0,4,7} major ✓; BARRE_MAJ_6 (E-shape) {0,4,7}, BARRE_MIN_5 (Am-shape) {0,3,7}, BARRE_MAJ_5 (A-shape) {0,4,7} ✓ — confirms validator exercises the shapes. **Non-duplication judged ACCEPTABLE**: pop-axis (0-7-9-5 maj) shares shape with rock-axis/reggae-nwnc and pop-mixo-bVII (0-10-5 mixo) with rock-mixo-vamp, but ids differ, songs differ (No Woman No Cry/Adele/Beatles vs rock), and guitar plays are capo-and-open framed vs rock's barre framing — a real genre reuse with distinct content, not a duplication smell; differentiation rationale documented in the progressions.js header. **Honesty CONFIRMED**: every sus2/sus4 mention is prose (note/tips/styleIntro) framed as a hammer-on/pull-off fill over a held chord ("the chord stays major, your finger wiggles"); zero sus in the data — all pop-mixo chords are voiced plain `maj`; tips never claim a voicing the data lacks. Song attributions hedged (Clocks "♭VII colour", Royals "verse", Memories "Pachelbel, set in B").
> GATE 2026-06-15 (Critic) · **H-02 PASS** — every relative link resolves on disk: GOAL.md, README.md, src/data/kb/SCHEMA.md, gospel/{meta,progressions,guitar}.js, index.js, src/lib/theory.js, scripts/validate-kb.mjs, docs/agents/ROSTER.md, and all three issue templates (add-style/bug_report/feature_request) + config.yml — verified via on-disk existence check. Every command real (npm install / electron:dev / dev / build / node scripts/validate-kb.mjs all in package.json). **Schema fidelity exact**: the quality list `maj,min,dom7,maj7,min7,dim,dim7,half_dim,aug,sus4,sus2,maj6,min6,add9` matches `CHORD_TYPES` keys byte-for-byte; modes list matches the validator's MODES; degrees-0-11, movable(rootStr/offsets) vs open(frets/onlyRoot), and extensions/rootless/omit3 explanations all match SCHEMA.md + validator logic — no invented field, no drift. LICENSE correctly NOT added (CONTRIBUTING honestly states "doesn't have a license file yet … reuse terms aren't settled"). Issue templates present and sane. *Non-blocking nit*: CONTRIBUTING's illustrative validator-output sample reads `9 style(s)/45/90` (true at authoring time, pre-pop) — it's a "what a passing run looks like" example, not a load-bearing claim; the instructions don't depend on the count. Worth a one-char refresh to 10/50/100 someday, not a return.
> GATE 2026-06-15 (Critic) · **C-01 PASS** — `node scripts/smoke.mjs` → `✓ Smoke test passed — 71/71 checks green (10 styles, 50 progressions)`, exit 0; reports the FULL final KB (10 styles, derived from the loaded registry, not hardcoded). Imports the REAL `kb/index.js` + `match.js` (no mocks); asserts registry integrity (every style meta/progressions[]/instruments.guitar, per-prog degrees/qualities/rn/bars consistency, cross-KB id uniqueness) and matcher correctness (iiVI matched:true + structural rebased-degree-shape check, rotation invariance to the SAME derived id with non-zero rotation, axis match guarded with skip-if-absent, chromatic → matched:false/id:null, findLoopPosition in-range/-1/-1-on-empty). Exits non-zero on failure (mirrors validate-kb). **Adversarial proof**: sabotaged `matchLoopToProgression` to always return no-match → smoke FAILED 4 checks, **exit code 1** (assertions are NOT too weak — a broken matcher cannot pass). match.js restored, no diff. **Resolve hook judged SOUND**: the inline `module.register` ESM hook retries ONLY on `catch`, ONLY for relative+extensionless specifiers (`/^\.{1,2}\//` && `!/\.[mc]?js$/`) — verified the regex skips `./theory.js`, `react`, `node:url`, `./a.mjs` and retries only `./theory`/`../lib/match`; it cannot mask a genuine missing module (the `.js` retry itself surfaces the real ERR_MODULE_NOT_FOUND). Correctly chosen over editing match.js (locked to L-01). **No npm script added** (validate-kb has none) — `package.json` untouched (git: only `src/data/kb/index.js` is modified; smoke.mjs/pop/CONTRIBUTING/templates are new untracked). No hardcoded fragile ids — expected ids derived from the loaded KB; survives KB growth.
> GATE 2026-06-15 (Critic) · **D-03 FAIL (returned)** — build green (vite, 90 modules, 10.66s); validator green (`✓ KB valid — 10 style(s), 50 progressions, 100 plays`, no KB change). 🚨 **Audio contract INTACT**: `git diff -- src/App.jsx` is purely additive — exactly (a) one new `useState(jamFocusChord/null)` placed in the UI-state block (outside all audio-callback/ref logic, with a comment that it is not read by any callback), (b) `jamFocusChord={jamFocusChord}` on the existing `<Fretboard>` mount, (c) `onFocusChord={setJamFocusChord}` on the existing `<JamGuide>` mount. Grep of the **changed lines** for `handleNote|handleChroma|handleOnset|useCallback|AudioCapture|Ref|useEffect` → **NO MATCHES**. No callback, ref, ref-sync useEffect, or AudioCapture prop touched. Black-screen/infinite-restart risk avoided. **Wiring correct**: JamGuide emits `{rootPc, quality:qualities[i]}` (station's actual KB quality) on select, `null` on deselect; the existing `selectedStation→null` reset effect (loop/style/instrument change) flows through the new cross-link effect and clears the highlight; an unmount-cleanup effect also clears; all guarded `onFocusChord?.` so JamGuide stays standalone. Fretboard **null path verified unchanged** (`hasFocus=false` ⇒ `tag` always null ⇒ `if(!color&&!tag)` collapses to original `if(!color)`; no halo/badge/legend). Emphasis is visually distinct (purple ring `DOT_R+3` + degree badge, accent token `#a855f7`). Triad labeling **correct** for maj/min/dim/aug/sus4/sus2 (all `hasSeventh:false` → badge/legend read "5"). **DEFECT (blocking)**: `guideTones`' secondary-anchor heuristic is `hasSeventh = ints.length >= 4`, so the **4-tone non-seventh** KB qualities `add9` `[0,2,4,7]`, `maj6`/`min6` `[0,4,7,9]` return `hasSeventh:true` with `seventh = ints[last]` = the **5th** (add9) or **6th** (maj6/min6). D-03's `focusLabel` trusts that boolean and badges those tones **"7"**, legend reads **"3 / 7"** — a perfect fifth / sixth rendered to the user as a seventh on the flagship Fretboard. **Reachable**: `add9` is in gospel progression qualities (×4), `min6` in bossa + rnb qualities — tapping those stations mislabels a non-7th. Verified by running `guideTones(0,'add9')→{third:4,seventh:7,hasSeventh:true}` (G badged "7"), `guideTones(0,'min6')→{third:3,seventh:9,hasSeventh:true}` (A badged "7"). The DoD's "the chord's guide tones (3rd/7th)" / "badge reads 5 not 7 for a triad" contract is violated for these KB-present qualities. **Fix direction (return to Luthier):** make the secondary anchor honest for extended non-7th chords — either tighten `guideTones` so a chord with no minor/major 7th reports `hasSeventh:false` and falls back to the 5th (root cause, L-01b owns theory.js), or have `focusLabel`/the badge derive the actual interval of `seventh` above root (10/11 ⇒ "7", 9 ⇒ "6", 7 ⇒ "5", 2 ⇒ "9") rather than trusting the boolean. Re-gate after fix.
> GATE 2026-06-15 (Critic) · **D-03 PASS (re-gate)** — the returned defect is fixed at the root cause and hardened. `npm run build` green (vite, 90 modules, built in 3.25s); `node scripts/smoke.mjs` → `✓ Smoke test passed — 71/71 checks green (10 styles, 50 progressions)`, exit 0; `node scripts/validate-kb.mjs` → `✓ KB valid — 10 style(s), 50 progressions, 100 plays` (no KB change). **Root-cause fix VERIFIED by running the real `guideTones`**: `hasSeventh` now keys on the actual presence of interval 10 or 11 (`ints.find(i=>i===10||i===11)`), not `length>=4`. Independent truth table (root C): add9→{third:2,seventh:7,**hasSeventh:false**,anchor=5th G}; maj6→{4,7,false,5th}; min6→{3,7,false,5th}; dom7→{4,10,true,7=A♯}; maj7→{4,11,true,7=B}; min7→{3,10,true,7=A♯}; triads maj/min/sus4/sus2→false,anchor 5th(7); dim→anchor ♭5(6); aug→anchor #5(8); dim7→♭5(6); half_dim→true,10. Return shape `{third, seventh, root, hasSeventh}` **unchanged** (keys verified). **Badge hardening (Fretboard) VERIFIED**: `focusSeventhLabel` derives the label from the *actual* interval of the anchor pc above the chord root (10/11→"7", 9→"6", 8→"♭6", 7→"5", 6→"♭5"), so a wrong boolean can't mislabel — adversarial sweep of all 14 KB qualities × keys {3,7,11}: a "7" badge appears iff the interval is truly 10/11; **NO MISLABEL**. Unknown quality → `maj` fallback, no crash. **Null-focus path byte-equivalent**: `jamFocusChord=null` ⇒ `hasFocus=false` ⇒ `tag` always null ⇒ `if(!color&&!tag)` collapses to the original `if(!color) return null`; no halo/badge/legend; `focusSeventhLabel` is dead-but-harmless. **No collateral**: `voiceLeadingPairs`/`soloScale` signatures untouched (theory.js diff hits only `guideTones` body+jsdoc); iiVI rails still correct (Dm7→G7 C→B [0→11,1]; G7→Cmaj7 F→E [5→4,1]) and `voiceLeadingPairs` does NOT crash for the now-5th-anchored add9/maj6/min6 (Cadd9→G7, Cmaj6→F, Amin6→Dm7 all return smooth rails). match.js/RoadmapTrack/ChordDiagram/KB untouched (`git diff --name-only` = only the 4 declared D-03 files). 🚨 **Audio contract INTACT**: `git diff -- src/App.jsx` purely additive (one `useState(jamFocusChord/null)` outside the callback/ref block + an additive `jamFocusChord=` prop on `<Fretboard>` + `onFocusChord=setJamFocusChord` on `<JamGuide>`); grep of changed lines for `handleNote|handleChroma|handleOnset|useCallback|AudioCapture|Ref|configRef|useEffect` → NO MATCHES; the sole "" line is the Fretboard mount being re-emitted with the added prop. *Non-blocking observation (pre-existing, out of D-03 scope):* `guideTones` uses `ints[1]` for the 3rd, so `add9` `[0,2,4,7]` reports its **9th (pc 2)** as `third`, not the major 3rd (pc 4) — true at L-01b time, unchanged by this fix, and D-03's bug was strictly the seventh/secondary anchor; worth a future tidy, not a return.
> GATE 2026-06-15 (Critic) · **L-10 PASS** — (re-gated cleanly after the prior dispatch died on an API error pre-verdict.) `npm run build` green (vite 7.3.1, 90 modules, built in 2.24s); `node scripts/smoke.mjs` → `✓ Smoke test passed — 71/71 checks green (10 styles, 50 progressions)` exit 0; `node scripts/validate-kb.mjs` → `✓ KB valid — 10 style(s), 50 progressions, 100 plays`. **Purity confirmed** by reading the full module: exports `pianoVoicing({rootPc,quality},opts?)`→`{notes,pcs,bass,style,label}` plus `pianoVoicingChain`, `hasTrueSeventh`, `voicingToneSet` (and re-exports `guideTones`); imports ONLY `{CHORD_TYPES, guideTones}` from `./theory`; no `Date`/`Math.random`/module-level mutable state — determinism verified (every quality voiced twice → byte-identical). **Music verified myself** via a throwaway ESM script (deleted): swept **all 14 CHORD_TYPES × 4 styles = 56 voicings** at rootPc 0 — every `pcs ⊆ voicingToneSet(...)` (**NO out-of-chord note**), real 3rd present (sus→2/5), every TRUE 7th (interval 10/11: dom7/maj7/min7/half_dim) present in shell+rootless, all `notes ∈ [0,36]` (≤3 octaves), `bass=min(notes)`. Spot-checks exact: **Cmaj7 shell→{0,4,11}** ✓, **Dm7 rootlessA→{5,9,0,4}=F-A-C-E** ✓, **G7 shell→{7,11,5}** ✓. **Awkward qualities honest**: half_dim shell→{0,3,10} (true ♭7 kept), rootlessA→{3,6,10,2} "3-5-7-9" ✓; **dim7 correctly NOT a true-7th chord** — its 7-slot is interval 9 (𝄫7 = enharmonic maj6, not 10/11), so `hasTrueSeventh('dim7')=false`, shells as R-3-5 {0,3,6}, no fabricated 7th; **min6/maj6** (no true 7th) → root {0,3,7,9}/{0,4,7,9}, rootless labels honestly read "3-5-6-9" using the 6th as upper colour — no wrong note. **Voice-leading confirmed**: `pianoVoicingChain([Dm7,G7,Cmaj7])` total semitone motion **16 vs 18** unthreaded (`opts.prev` slides whole shapes by octaves toward the previous voicing); pcs **unchanged** by threading (per-chord pc sets identical to unthreaded — re-registered only, never corrupted). **Adversarial**: bogus/empty/null chord → graceful `maj` fallback, no crash. **One non-blocking nit (NOT a defect):** forcing `rootlessB` (or `rootlessA`) explicitly onto a **sus2** chord produces a cosmetic duplicate absolute note (`notes=[26,26,31]`) because the suspended-2nd "3rd-slot" tone (pc2) and the synthesized 9th (pc2) collide — still no wrong pc, in range, and honestly labeled "no 7th, 9-3-5 colour". It is **unreachable on the shipping path**: `defaultStyle(sus2)='root'` and L-11/`pianoVoicingChain` use defaults, so sus2 renders as clean root `[0,2,7]`; the dup only appears under an explicit forced-rootless override of a sus chord (documented graceful degradation). Default-style sweep of all 14 qualities confirmed zero duplicate notes. Recommend a future tidy (dedupe collided absolute notes in the rootless fallback) — not a return. `src/lib/piano.js` NOT edited; throwaway script removed.
> GATE 2026-06-15 (Critic) · **D-02 PASS** — the load-bearing integration is correct. **Independent rotation check**: `canonicalPos = ((position rotation) % n + n) % n` translates a `findLoopPosition` index (which is into the *detected loop*) into the KB-canonical station RoadmapTrack/stationVoicings render. Worked a rotated [ii V I VI] of KB [I VI ii V] (rotation=2, n=4): playhead@detected-idx1(V)→canonical 3(V), @2(I)→0(I), @3(VI)→1(VI), @0(ii)→2(ii) — NOW lands on the chord actually playing. ✓ **rootPc parity** confirmed: thumbnail `rootPc` and RoadmapTrack station root are byte-identical `(((keyRoot+deg)%12)+12)%12`, and `keyInfo.root` (a note *name*, e.g. `detectKey`→"F#") is converted once via `chordRootPC` → pc, guarded `>=0`. stationVoicings `chords[i]` aligns 1:1 with `degrees[i]` (canonical). Auto-scroll is prop-driven off `position` (no rAF on the audio thread). Reflows (`flex-wrap`/`sm:flex-nowrap`), keyboard-reachable, AA contrast. NO_MATCH path → dashed fallback, never empty/crash. *Non-blocking deferral*: the DoD's "tap-station → **fretboard** guide tones" cross-link and `tailwind.config.js` edit were not delivered — the implementation cross-links via an inline enlarged ChordDiagram instead (flagged in-code as deferred). Panel is fully functional without it; recommend Maestro file the fretboard cross-link as a phase-2 follow-up.
> GATE 2026-06-16 (Critic) · **D-10 PASS** — `npm run build` green (vite 7.3.1, 90 modules, built in 9.36s); `node scripts/smoke.mjs` → 776/776 exit 0; `node scripts/validate-kb.mjs` → 10 styles/50/100 (no KB change). **ADDITIVE confirmed** by reading the full diff: the public `MiniPiano` now dispatches `if (voicing) <VoicingPiano/> else <LegacyPiano/>`. The legacy `{rootPc,lh,rh}` path is the SAME code, only refactored to named constants holding the IDENTICAL hex values (`LH_BLUE=#3b82f6`, `ACCENT=#a855f7`, `WHITE_FILL=#f5f5f5`, `WHITE_STROKE=#374151`, `BLACK_FILL=#1f2937`, `BLACK_STROKE=#111827`) — geometry (OCTAVES=2, WW/WH/BW/BH, BLACK_OFFSETS), highlight map, R-label all unchanged. **Consumers render identically**: `grep` confirms `ChordDetailModal.jsx:86` and `ExplorePanel.jsx:85` both call `<MiniPiano rootPc lh rh />` with NO `voicing` prop → `voicing` is `undefined` → both hit `LegacyPiano` → byte-equivalent output. **Voicing path correct**: maps absolute `notes` (0=low C, [0,36]) to keys via `oct*12+pc`, root pc lights accent `#a855f7` + "R", bass key amber-ringed (`#fbbf24` AA), other tones soft accent `#c084fc`; OCTAVES auto-spans 23 to contain `max(notes)`. Worked example `pianoVoicing({rootPc:0,quality:'maj7'})` → default shell, pcs `{0,4,11}`=C-E-B (R-3-7): C lit accent+R, B & E soft purple, C bass-ringed — musically right. `role="img"`+`aria-label`. Design tokens used. No legacy regression, no colour/render bug.
> GATE 2026-06-16 (Critic) · **C-10 PASS** — `node scripts/smoke.mjs` → **776/776 exit 0** (was 71 pre-piano; +705 piano checks). Diff ADDED a piano block, kept ALL prior registry/matcher checks. Sweeps 14 qualities × {C,G} × {root,shell,rootlessA,rootlessB,default} asserting: valid shape (notes/pcs/bass/style/label), `pcs ⊆ voicingToneSet(quality,actualStyle)`, real 3rd (or sus tone) present, true 7th present in shell/rootless when `hasTrueSeventh`, `notes ∈ [0,36]`, `bass===min(notes)`, no-dup-note, determinism, and chain pcs-preservation. **Adversarially proven NON-vacuous**: inject pc1 into pcs → **125 fails, exit 1** (pcs⊆toneSet bites); `bass=max(notes)` → **140 fails, exit 1**; revert L-13 dedupe (`notes=placed`) → the no-dup check fails on exactly `sus2@0 [rootlessB] notes=[26,26,31]` + `sus2@7 [21,21,26]`, **exit 1**. So the suite now passes LEGITIMATELY because L-13 fixed the resolver, not because any check was weakened. piano.js restored to its L-13 diff after each sabotage (git: 9 insertions, clean).
> GATE 2026-06-16 (Critic) · **L-13 PASS** — minimal fix at the single funnel point in `pianoVoicing`: `const notes = [...new Set(placed)]` (dedupe ABSOLUTE notes), `pcs`/`bass` derived from the deduped array so both stay consistent. Verified via a throwaway resolve-hook ESM check (written + deleted): (a) `pianoVoicing({rootPc:0,quality:'sus2'},{style:'rootlessB'})` → `[26,31]` distinct (was `[26,26,31]`); (b) NO default-style voicing across all 14 qualities has a duplicate, so the dedupe is a pure **no-op on the default/chain path** — L-11's render is unaffected; ii-V-I chain `[14,17,24]|[19,23,29]|[24,28,35]` all distinct & voice-led. The full 56-voicing correctness is re-asserted by the now-776-green smoke (pcs⊆toneSet, 3rd, 7th, [0,36], bass for every quality×style). **Safety reasoning — dedupe NEVER drops a needed note**: a JS `Set` of absolute integers merges two entries only when they are the *identical integer*, i.e. identical pc AND identical octave — the *same physical key*, which can sound only one note anyway. Two musically-distinct intended tones (different pc, or same pc a different octave like 14 vs 26) yield different integers and are never merged. The sus2 collision is a genuine unison (pc2 stand-in 3rd at +24=26 vs synthesized 9th at +12=26, both pc2 same octave) — a redundant doubling, safe to drop. No information loss possible. build green; default + chain paths unchanged.
---
## Backlog (future sprints)
- **Retire `EducationPanel.jsx`** — confirmed orphaned (no importer anywhere in `src/`, D-20 gate verified); delete after the Knowledge Center ships. Fold `CurrentJamPanel`'s overlapping content (voicings/scales/similar progressions) into the Knowledge Center and retire it too.
- **Level-tag `FAMOUS_PROGRESSIONS`** (`src/lib/education.js`, Professor): famous-progression cards are exempt from the level filter this sprint (Maestro call 2026-07-08, per D-20 open question 1).
- **Drift guards in smoke (Critic, tiny):** two hand-synced duplications need permanent smoke checks — JamGuide.jsx's copy of the validator's `resolveDegree` (fold in the L-24 gate's 16-degree × 14-quality drift test) and the 8-word technique vocab duplicated between `validate-kb.mjs` `LICK_TECHNIQUES` and `LickCard.jsx` `TECHNIQUE_VOCAB` (C-21 finding).
- **`pianoVoicing` should return `rootPc` (Luthier, tiny):** callers currently must attach it themselves (JamGuide and VoicingBrowser both do); returning it at the source removes the false-"R" foot-gun for future consumers (D-24 gate observation — NOT a live bug, both call sites verified correct 2026-07-08).
- **`docs/kb-backlog.md` is stale (Professor, tiny):** still lists gospel/pop guitar + jazz/gospel piano as "todo" though shipped; P-30 (rnb piano) AND P-31 (blues piano, both 2026-07-10) need done entries — refresh next content iteration (flagged by P-30 + C-31 sweep, outside their locks).
- **`scripts/loop-fixtures.mjs` header comment drift (tiny):** cites "App.jsx:322-324" for adjacent-dup suppression; L-31 shifted it to ~line 364 — comment-only, fix when the file is next touched (C-31 sweep finding).
- **Try-this vs Suggested-progressions should show TWO DIFFERENT things (product direction, user 2026-07-13 — "keep as is for now… revise later"):** today both are chord/loop-relative but overlap conceptually. Intent: **Try this** = per-chord substitutions (an alternative to the CURRENT chord; built via `suggestSubstitutions`). **Suggested progressions** = currently same-style KB siblings (other real progressions in the style); the desired distinction is to make it **loop-level** — propose altered/reharmonized versions of the USER'S ACTUAL loop (apply `suggestSubstitutions` across every loop chord to generate modified progressions), i.e. the "computed modifications" option deferred earlier. The engine (L-73) now exists to power it. Keep same-style-siblings for now; revisit as a distinct feature.
- **TryThis duplicate-name-loop rotation (Luthier, small — L-74 gate 2026-07-13):** `loop.indexOf(currentChord)` returns the FIRST index, so a loop with a repeated chord name (e.g. a collapsed 12-bar where I7 recurs) double-advances the rotation (~2× pacing) and can mislabel Rule D's "next" chord. Subs for the current chord stay correct. Honest fix needs App to pass a true playhead station index (beyond L-74's mount-only lock) — wire it if TryThis ever couples to the loop engine.
- **TryThis/related category-tag contrast (Muse, tiny — L-75/L-76 gate 2026-07-13):** the decorative category tag uses `text-gray-500` at 9px (~3.4:1, under AA for small text) — the app-wide secondary-label idiom (also in section headers/DebugView), so pre-existing and non-load-bearing; consider a bump to `gray-400` system-wide someday.
- **ProgressionBanner strip chips are div-onClick (Muse, small):** pre-existing a11y debt — history/loop chips should be real buttons (L-50 gate 2026-07-11; RelatedProgressions' chips already show the pattern to copy).
- **Test-infra note (any agent writing throwaway SSR harnesses):** a bare `import('esbuild')` inside a `data:` module hook dies silently (ERR_MODULE_NOT_FOUND in the hooks thread, exit 1, zero output) — smoke.mjs:1047's interpolated `import.meta.resolve` pattern is load-bearing; prefer esbuild pre-bundle harnesses (confirmed empirically twice, 2026-07-11).
- **GUITAR_SHAPES self-audit in smoke (Critic, small — P-62 gate suggestion 2026-07-11):** pc-spell every GUITAR_SHAPES entry against its quality in smoke — the validator audits only KB chord steps, never the shape library itself; would have caught both wrong shapes below and guards future additions.
- **Pop piano prose uses absolute note names (Professor, tiny — P-62 gate flag):** ~8 spots (pop/piano.js:88,117,130-133,159,186) say e.g. "the G holds; top C→B" — correct only in the declared reference key; degree-ify before any piano-prose render surface lands (sibling of the bass-tips-surface backlog item).
- **Two wrong GUITAR_SHAPES in live data (Luthier, small — P-62 audit finding 2026-07-11):** (1) `half_dim "E Barre"` offsets `[0,1,2,0,0,'x']` sounds {0,3,6,7} — natural 5th clashing the ♭5, NO ♭7; correct E-form ø7 = `[0,1,0,0,'x','x']`. (2) `add9 "Open Dadd9"` (xx0230 = D-A-D-E) has no 3rd — it's Dsus2, duplicating the sus2 open D. Both pre-existing; fix after P-62 commits (additive lock kept P-62 from editing them).
- **Matcher blues/jazz disambiguation (Luthier, small):** `['C7','A7','Dm7','G7']` matches `jazz-rhythm-a` (identical IVIiiV degree shape, quality tie → jazz), so `blues-turnaround`'s bass plays are live-unreachable — pre-existing tie-break in match.js; consider quality-profile weighting (all-dom7 → blues). Evidence-verified by the L-42 gate 2026-07-10.
- **Bass play `tips` have no render surface (Muse/Luthier, small):** the authored teaching prose in bass packs renders nowhere (card shows label/feel/position/note only; the dock has no bass section) — real content-surface gap, L-42 gate 2026-07-10.
- **TransitionChip "2 step down" wording (Muse, one line):** whole-step rails render as "2 step down/up" (52 of 268 real KB transitions) — verbatim port of RoadmapTrack.jsx:59; "whole step down" is the musician's phrase (D-41 gate note 2026-07-10).
- **Fingering view lost at gallery thumb size (Muse, small):** D-30's gallery renders ChordDiagram at `size="thumb"`, which never draws finger numbers — nothing in the browser shows fingering anymore (D-30 gate note 2026-07-10). If pedagogically wanted: tap-to-enlarge to `size="full"` inside a gallery cell.
- **Negative-fret shape handling inconsistency (Luthier, small):** `voicings.js` skips shapes that compute negative frets while `chordAudio.guitarShapeToNotes` slides them up an octave — pre-existing, flagged at the L-23 gate; unify someday.
- **Jam Guide phase 3:** bass pattern renderer (guitar → piano → **bass** roadmap; MiniPiano + piano recipe resolver shipped in sprint-knowledge-center).
- **Content:** piano packs (jazz → gospel → neo-soul first), then bass packs (blues → jazz → funk first) — see `docs/kb-backlog.md`.
- **`guideTones` third bug (L-12, Luthier — small):** `guideTones` takes `ints[1]` as the "third", so `add9` `[0,2,4,7]` reports its **9th (pc 2)** as the 3rd instead of the major 3rd (pc 4) — wrong "3rd" lane/badge for add9 (live in gospel + pop-axis Cadd9). Pre-existing since L-01b; flagged by Critic during the D-03 re-gate. Fix: pick the actual 3rd/4th interval (3 or 4, or sus 2/5) rather than positional `ints[1]`. Smoke + a guideTones truth-table check.
- **Learning features (Professor + Luthier):** drills tab seeded from `docs/learn-curriculum.md`; target-note highlighting; ear-training quiz on own chord history; pocket report from the onset pipeline.
- **Progression Builder (GOAL G3):** key-relative palette, drag-reorder, Nashville-number toggle, voicing alternatives.
- **Platform (Herald):** GitHub Pages docs site; "you're playing the Creep progression" engagement hook; contributor leaderboard for styles added.
---
## Iteration log
_(Maestro appends one line per completed iteration: `<date> · <task ids done> · <next>`.)_
- 2026-07-13 · **sprint-dashboard-polish — direct push (user "push everything now")** · done: L-78 (`d543b98` Try-this 3×3 ways-to-play — up to 3 guitar grips / 1 piano per suggestion, fixed anti-jump 3-slot frame; verified build+validate-KB+smoke 903/903; full independent Critic gate waived at user request) · L-77 re-scoped SAME DAY per user: rail should HIGHLIGHT loop chords when a loop is found AND list the other recent chords underneath, ≥4 total once history exists (was: replace-with-history). Rebuilding + pushing per "add this to the branch also and push when its done" · next: build L-77 (hybrid loop+history rail) → verify → push both remotes
- 2026-07-13 · **L-77 done + pushed** (`9415daf`) · hybrid voicings rail: loop group highlighted ("the loop") + "also played" recent-distinct chords underneath (most-recent-first, ≥4 once history exists), no-loop → history rail replaces the single-chord fallback; GlanceRail gains `showTransitions` (default true, loop byte-unchanged). Maestro verified build+validate+smoke 903/903 and folded 2 honesty fixes on the shared GlanceRail (history group no longer says "loop"/"playhead"; history rows non-focusable → no inert button). App.jsx/audio untouched. Pushed both remotes · next: C-70 sprint-end sweep (aria one-liner + PR updates) when user confirms the rail looks right
- 2026-06-14 · done: M-01 · in-review (awaiting user pick): D-00a/b/c viz concepts · next: D-SEL (user chooses) → then L-01/D-01/D-02 implement chosen concept
- 2026-06-15 · done: D-00a/b/c, D-SEL (Roadmap chosen), L-01 (match.js + banner refactor), L-01b (guideTones/voiceLeadingPairs/soloScale) — Critic PASS both · next: L-02 (JamGuide shell) → D-01 (RoadmapTrack) ‖ D-01b (ChordDiagram)
- 2026-06-15 · done: L-02 (JamGuide shell + App mount), D-01 (RoadmapTrack), D-01b (ChordDiagram), D-02 (assembly + playhead rotation + thumbnails) — Critic PASS all 4, audio contract intact (App.jsx +10/0) · **Roadmap Jam Guide MVP is live & builds green** · next: D-03 (fretboard cross-link, backlog) ‖ P-01 (gospel content) ‖ H-01 (README reframe)
- 2026-06-15 · done: P-01 (gospel guitar pack — 5 progs × 2 plays, validator 9 styles/45/90), H-01 (README reframed as learning platform, stale frontend/ paths fixed) — Critic PASS both · next ready: P-02 (pop pack) ‖ H-02 (CONTRIBUTING) ‖ C-01 (smoke harness) ‖ D-03 (fretboard cross-link)
- 2026-06-15 · done: P-02 (pop guitar pack — KB now 10 styles/50/100), H-02 (CONTRIBUTING.md + issue templates), C-01 (scripts/smoke.mjs — 71/71, adversarially proven to catch a broken matcher) — Critic PASS all 3 · **SPRINT `sprint-jam-guide` COMPLETE** → opening PR to main · remaining (next sprint): D-03 fretboard cross-link, piano/bass packs, drills
- 2026-06-15 · done: D-03 (tap station → guide tones on the main Fretboard; root-cause fix to `guideTones` hasSeventh + badge hardening) — Critic **returned once** (add9/maj6/min6 mislabeled 5th/6th as "7"), fixed, **PASS on re-gate** · audio contract intact · folded into PR #2 (completes the flagship) · filed L-12 (guideTones third bug) to backlog · next: seed piano phase-2 sprint (resolver + MiniPiano + wire)
- 2026-06-15 · **new sprint `sprint-jamguide-piano`** cut off sprint-jam-guide (keeps PR #2 stable) · done: M-02 (seed), L-10 (`src/lib/piano.js` voicing resolver — shells/rootless A·B/root, voice-leading threading; Critic PASS, 56 voicings, 0 wrong notes) · next ready: D-10 (MiniPiano) ‖ C-10 (smoke piano) → then L-11 (wire piano tab) · L-10 chosen as a new unimported lib so the user's live frontend review stayed undisturbed
- 2026-06-16 · done: D-10 (extended existing `MiniPiano.jsx` with additive `voicing` prop — legacy lh/rh path for ChordDetailModal/ExplorePanel byte-unchanged), C-10 (smoke +705 piano checks → 776 total), L-13 (resolver dedupe — `[...new Set]`, fixes sus2 dup-note C-10 caught) — Critic PASS all 3 (adversarially proved C-10 checks bite + dedupe never drops a needed note) · **mid-iteration corrections:** D-10's "new file" premise was wrong (MiniPiano already existed + imported) → re-scoped to additive extend; C-10 correctly turned the branch red surfacing a real wart → filed+fixed L-13; 3 subagents hit API errors (2 produced nothing, 1 landed its diff before dying) · **L-11 (wire piano tab) intentionally HELD** — it's the first UI-visible change; waiting until the user finishes reviewing localhost:5173 · next: L-11 on the user's go
- 2026-07-08 · **new sprint `sprint-knowledge-center`** seeded on the SAME branch (user directive: continue on `sprint-jamguide-piano`) · user asks: playable voicings per chord, lick/technique cards, intermediate progressions (easiest in-app surface = level tags + filter), Knowledge Center visual restructure, keep expanding KB · L-11 hold LIFTED, carried forward · loop scheduled: /jam-loop every 30 min × 24 iterations (12 h) · ready now (file-disjoint): L-11 ‖ D-20 ‖ L-20 ‖ C-20
- 2026-07-08 · **iteration 1/24** · done: M-03, L-20 (`4b0f0c8` audio engine), L-11 (`7b669f8` piano tab LIVE), D-20 (`96dda6a` Knowledge Center concept), C-20 (`793e60a` lick/level schema, smoke 787) — Critic PASS all four, zero returns · findings folded into the board: D-21 lock += `voicings.js` export-only (GUITAR_SHAPES private); L-22 deps += P-21; P-21 serialized behind P-20 (`jazz/**` overlap); filed L-23 (pre-existing `getGuitarVoicings` rootStr fret-label bug, found by L-20); D-20 discovered ExplorePanel + EducationPanel are ORPHANED (never mounted) → retirement backlogged; famous-progressions level-filter exemption recorded · next ready (file-disjoint): D-21 ‖ P-20 ‖ D-22 (D-22 may build against the SCHEMA fixture until P-21 lands)
- 2026-07-08 · **iteration 2/24** · done: D-22 (`44d9c4f` LickCard), D-21 (`3c903ad` VoicingBrowser — returned once: rootless voicings badged lowest voice as "R", one-line rootPc fix, PASS on re-gate), P-20 (`c08b334` — returned once: 3 caption theory misstatements, string fixes, PASS on re-gate; KB 56 progs/112 plays, all jazz/gospel/rnb progressions level-tagged) · incident: both first-round gates stalled on API watchdog (600s) twice for P-20 — fresh critic instances completed them; one cron fire absorbed into gate completion · Critic gate quality note: both returns were real musical defects caught before commit
- 2026-07-08 · **iteration 4/24** · done: P-21 (`6ea1089` 12 licks blues/jazz/funk — every note pitch-verified), P-22 (`9e2567c` jazz piano cell, KB's first authored piano pack, 126 plays — returned once: 6 prose voice-leading overclaims on fifths-apart dominants, fixed + arithmetic-verified, PASS on re-gate), L-22 (`78706ce` **Knowledge Center shell LIVE** — 4-section dock, level filter, licks grid; App.jsx +1 line, audio contract grep-clean) · filed: C-22 (validator span check), L-24 scoped out of P-22 (authored-pack rendering) · promoted: L-24, C-22, P-23 · iteration 5 batch already in flight: D-23 ‖ D-24 ‖ P-24
- 2026-07-09 · **iteration 8/24 — SPRINT `sprint-knowledge-center` COMPLETE** · done: C-21 (sprint-end sweep — build/validator/smoke all green on 72c6d45; full-App SSR renders; authored vs computed piano paths both proven; zero dead imports; audio contract +1 line since seed) · **PR #3 opened: https://github.com/whattheflat/JamBuddy/pull/3** (supersedes PR #2 — main hadn't absorbed it) · all 21 sprint tasks done, 4 returned-then-fixed by the gate, 0 unresolved · loop cron deleted after 8 of 24 budgeted iterations (board empty) · remaining backlog: EducationPanel retirement, FAMOUS_PROGRESSIONS level tags, smoke drift guards, pianoVoicing rootPc, negative-fret unify, L-12, bass renderer
- 2026-07-09 · **iterations 67/24** · done: L-25 (`e24aa4b` instrument-scoped modal tabs), C-22 (`b4e8f12` validator hand-span rule, smoke 799), P-23 (`564a9e0` gospel piano cell, 140 plays — returned once: one improv-row scale claim false for vi7/iii7, split into exact rows, PASS re-gate; 39/40 first-pass claims held), L-24 (`2165bb5` authored piano packs render at stations — implementer agent hung at verification after ~1 h, killed, completion-pass agent audited + finished; Critic PASS with 0 resolver drift) · incidents: P-23 stalled once mid-authoring (resumed from transcript, no loss); L-24 hung silently (diff intact, completed by fresh agent) · backlog: resolveDegree drift guard filed · **board empty except C-21 → sprint-end sweep + PR**
- 2026-07-08/09 · **iteration 5/24** · done: D-23 (`db397f6` VoicingBrowser show prop + LickCard stack-guard), D-24 (`e2110ae` MiniPiano thumbs crop to voicing span, 266→142 px), P-24 (11 licks rock/country/reggae — KB now **23 licks across 6 styles**, every note pitch-verified) — Critic PASS all three, zero returns · D-24 gate raised a false alarm on the D-21 rootPc fix (its harness bypassed VoicingBrowser; Maestro verified line 297 intact — no regression); hardening idea backlogged (`pianoVoicing` return rootPc) · promoted L-25 · next ready (all file-disjoint): L-24 ‖ L-25 ‖ C-22 ‖ P-23, then C-21 closes the sprint
- 2026-07-10 · **sprint-integrated-glance iteration 4/24 — SPRINT COMPLETE** · done: L-42 (`af7c3cc` **BASS real end-to-end** — BassPatternCard tab cards with playback; gate re-realized all 912 placements exact, byte-identity on untouched paths, import cycle proven safe), C-42 (`218c0ba` smoke §7 sweeps BOTH resolveDegree copies, 866/866 — the sweep agent authored the wiring then died on the ACCOUNT MONTHLY SPEND LIMIT; Maestro completed the sweep inline: build/validator/smoke green at HEAD, sabotage-proved the new guard [b13 perturbation → red naming the cell → restored green], whole-sprint App.jsx contract grep = 0 hits; per-instrument SSR relied on the L-42 gate's run minutes earlier — only smoke.mjs changed since) · backlogged: matcher blues/jazz tie-break (turnaround bass plays live-unreachable), bass tips surface · all 11 sprint tasks done, 2 returned-then-fixed (D-40, and D-41's predecessor D-31 pattern held: zero returns this sprint besides D-40), 0 unresolved · PR #3 updated; cron deleted (4 of 24 iterations) · ⚠️ NOTE: the Anthropic monthly spend limit is HIT — no further subagent work possible until raised
- 2026-07-11 · **sprint-roulette-kb iterations 1-2/12** (notification-driven; hourly cron as fallback) · done: M-07, C-60 (`5f4e2b7` piano lick schema — enclosures native, 25-cap proven tight, dormant renderer guard), P-62 (`ffc1bb1` pop piano cell 182 plays + 8 shapes; found 2 WRONG pre-existing shapes → backlog), D-61 (`c999c95` circle of fifths — returned once on modal hub signature, now teaches parent-major relation), P-60 (`70263e2` first piano licks, jazz+blues — PASS first try 35/35), D-60 (`a7dbd6a` PianoLickCard piano-roll renderer — PASS, 41/41 realization audit), D-62 (`e87b2bb` jam-roulette spec — returned TWICE, round-3 literal-implementation test passed; surfaced the pre-existing live bug: 10 progressions incl. blues-12bar never match detection; fix (a) specced into L-60), P-61 (`2c18c71` gospel+rnb licks, 39 total — returned once on one interval claim, gate-prescribed fix verified) · KB today: 172→182 plays, 23→39 licks, 6th piano style, circle of fifths · remaining: L-60 (blocked on one-screen C-50) → C-61
- 2026-07-11 · **BOTH SPRINTS COMPLETE** · sprint-roulette-kb: L-60 (`8d74e54`+`1df6fe8` **Jam Roulette LIVE** + the matcher collapse fix repairing the pre-existing live 12-bar/8-bar empty-JamGuide bug — Critic PASS on Opus: pool sweep reproduced from spec 4/52, fix-(a) additivity proven registry-wide, seed timeline hand-traced), C-61 (combined sweep — build/validator 182·39/smoke 891 all green, full-App SSR ×6 combos, whole-branch audio contract clean; PASS) · gate stats across both sprints: 9 first-try passes, 5 returns across 4 tasks (D-50, P-61, D-61, D-62×2) all re-gated to PASS · cron deleted · PR #3 updated with the combined summary · backlog: PianoLickCard LicksStrip wiring (needs shared sequencer-stop), 2 wrong GUITAR_SHAPES, strip-chip a11y, matcher blues/jazz tie-break, bass tips surface, 6 pre-existing orphan components
- 2026-07-11 · **sprint-one-screen iterations 2-3 + roulette-kb progress** · one-screen COMPLETE: L-50 (`800fd43`+`e58a7a6` dashboard grid, slim strip, jam view), D-51 (`d5a45f4` rail column adaptation — verified to the built CSS), L-51 (`6e8d8f4` RelatedProgressions — collapse step proven load-bearing), C-50 (`4deba7e` sweep, smoke 886, ranking pinned + registry id-uniqueness) — all Critic PASS · roulette-kb: P-61 (`2c18c71` gospel+rnb licks, 39 total) · **incident:** the L-60 (Jam Roulette) dispatch hit the account MONTHLY SPEND LIMIT on Fable 5 mid-read (no files written, clean tree); user switched the session to Opus 4.8 and L-60 re-dispatched fresh on Opus — proceeding · remaining: L-60 → C-61 closes both sprints
- 2026-07-11 · **sprint-one-screen iteration 1** (notification-driven) · done: M-06, D-50 (`d24bf35` one-screen dashboard + jam-view concept — returned once: strip height, geometrically-inert sticky, double-counted padding, collapse-blind ranking; all fixed, re-gate PASS with recomputed budgets) · L-50 (the build) in flight · then D-51 ‖ L-51 → C-50 → unlocks L-60
- 2026-07-10 · **sprint-integrated-glance iteration 3/24** · done: D-41 (`677d7b9` **all-expanded rail LIVE** — every station a permanently expanded row with education header [solo-scale, aim dots, voice-leading chips incl. wrap-around] + full gallery; playhead highlight-only proven byte-equal modulo highlight artifacts; focus toggle keeps the onFocusChord contract; show='bass' fall-through fixed; dense byte-identity proven across 336 SSR combos; black-on-accent 5.31:1 beats the old sub-AA white) — gate PASS, 19/19 SSR incl. independent theory recompute of a row's education · backlogged: TransitionChip "2 step down"→"whole step" wording (52 of 268 transitions) · L-42 (bass pattern renderer) dispatched — then C-42 closes
- 2026-07-10 · **sprint-integrated-glance iteration 2/24** · done: P-41 (`01a7c32` **the KB's first bass cell** — blues, 8 plays/172 total; gate machine-realized all 76 patterns in C AND A, 12 identities hold key-agnostically; PASS first try), L-40 (`c899132` **the restructure is live** — band below the main module, banner = the single loop display, RoadmapTrack/CurrentJamPanel unmounted, App's one GUITAR/PIANO/BASS selector drives band + dock, honest bass rows, GlanceRail yank-effect deleted; gate SSR 22/22, audio contract grep-clean, deletion sweep clean) · folded: smoke §7 resolveDegree wiring → C-42; VoicingBrowser show='bass' fall-through fix → D-41 (lock extended) · D-41 (all-rows-expanded rail) dispatched — then L-42 → C-42 closes
- 2026-07-10 · **sprint-integrated-glance iteration 1/24** · done: M-05, P-40 (`6f59add` kb-backlog refreshed — gate audited all 14 cells + 10 dates), C-40 (`090d3a9` drift guards, smoke 836 — gate recomputed all 224 truth-table cells), D-40 (`7d1f64c` integrated-glance concept — returned once: Dm7-specific piano math + 3 factual fixes incl. the interim page-yank, fixed, PASS re-gate with pixel-exact recompute), C-41 (`996218f` bass play schema, smoke 849 — degree-based, typed approaches, PASS with 19-semitone bound proven exactly maximal) · in flight: L-40 (App restructure — band up top, single loop display, one selector) ‖ P-41 (blues bass, first bass cell) · then D-41 → L-42 → C-42 closes
- 2026-07-10 · **iteration 4/24 — SPRINT `sprint-glance-and-loop` COMPLETE** · done: P-31 (`81cd230` blues piano cell, 164 plays — returned once: jump-kicks bars 3-4 dyad orientations flipped + 2 prose rewordings, fixed, PASS scoped re-gate), C-31 (sprint-end sweep at `81cd230` — build/validator/smoke 817 all green; full-App SSR renders with rail+gallery+strip coexisting; whole-sprint App.jsx diff = ONE hunk in the progression effect, contract grep 0 hits; no dead imports; every gate-promised follow-up verified filed) · all 11 sprint tasks done, 2 returned-then-fixed (D-31, P-31), 0 unresolved · PR #3 updated with the sprint summary; loop cron deleted after 4 of 24 budgeted iterations (board empty) · new backlog: loop-fixtures header line-ref drift; kb-backlog needs rnb+blues done entries
- 2026-07-10 · **iteration 3/24** · done: L-33 (`c78baf4` **glance mode LIVE** — playhead accordion, licks strip, heard-live fallback; gate SSR 37/37, dense-less VoicingBrowser byte-identical to 0945a08, token matcher proven hostile-proof, App.jsx untouched by construction), L-31 (`ce24d54` commit layer 2/3/6 — gate re-traced all five scenarios independently + 3 hostile traces; REPLACE_VOTES=3 proven load-bearing; audio contract grep-clean) · **all three user asks now end-to-end on the branch** · P-31 (blues piano, 164 plays) authored — gate in flight; its verifier self-caught 3 prose overclaims pre-review · C-31 promoted (holds until P-31 lands so the sweep sees a settled tree) · next: gate P-31 → C-31 closes the sprint
- 2026-07-10 · **iteration 2/24** · done: P-30 (`b51daa1` rnb piano cell, KB 154 plays — PASS first try, a piano-pack first; found+fixed its own 36-key-window stacking defect pre-review), L-30 (`4cc0009` detector rewrite: dup-collapse, weak-period ghost rejection, len 28, ≤1 edit/cycle with ≥2-exact evidence gate, recency-weighted coverage — smoke 817/817, gate ran 15 novel probes, 0.20.7ms/call) · L-33 built (playhead accordion + LicksStrip + heard-live fallback, SSR 24/24 self-checked) — gate in flight · L-31 dispatched with both gates' findings folded (flap-survival constraint, docstring ride-along) · both watchdog-stalled agents recovered cleanly via resume · promoted: P-31 · next: gate L-33, land L-31, then C-31 closes
- 2026-07-10 · **iteration 1/24** · done: M-04, D-30 (`0945a08` VoicingBrowser gallery — all shapes/styles side by side, no chips; PASS first try), C-30 (`fdd93c7` 17 loop fixtures + smoke wiring; PASS — found the len² self-overlap artifact as the root cause of the user's missed 3-chord loops, folded into L-30/L-31 DoDs), D-31 (`6c7a1a7` glance-mode "playhead accordion" doc — returned once on piano-gallery width math, fixed, PASS re-gate) · in flight: L-30 (detector redesign, dispatched early — C-30 contract ready), P-30 (rnb piano) — both stalled once on the 600s API watchdog near completion, both resumed via SendMessage · promoted: L-33 (ready, locks per D-31 doc) · finding worth noting: "5 chords then 2 others" passes at pure-function level — the live failure is the ghost-pattern flapping starving the 2-vote commit layer (L-31's trace case)
- 2026-07-10 · **new sprint `sprint-glance-and-loop`** seeded on the SAME branch (commits extend PR #3) · user asks: all voicing variations side-by-side with no button pushing; fix loop detection (misses a returning 3-chord loop and a 5-chords-then-2-others shape); glanceable zero-click learn session that follows the live jam · loop scheduled: /jam-loop every 30 min × 24 iterations (12 h, cron 13,43) · ready now (file-disjoint): C-30 ‖ D-30 ‖ D-31 ‖ P-30, then C-30→L-30→L-31 and D-30+D-31→L-33
- 2026-07-08 · **iteration 3/24** · done: L-21 (`951d544` VoicingBrowser live in ChordDetailModal Guitar/Piano tabs + JamGuide enlarged stations — the "playable voicings per chord" user ask is now end-to-end), L-23 (`f4e0ac6` getGuitarVoicings base-fret fix — 252 movable-shape placements corrected, A-shape C was labeled fret 1 not 3) — Critic PASS both, zero returns this round · follow-ups filed: VoicingBrowser `show` prop (Muse), negative-fret handling inconsistency (Luthier), stale JamGuide header comment · P-21 lock narrowed to the 3 guitar.js files → P-22 now disjoint · next ready (file-disjoint): P-21 ‖ P-22 ‖ L-22 (licks section may land empty-state-first per D-20 doc)
+123
View File
@@ -0,0 +1,123 @@
# Ensemble Protocol — How the Agents Collaborate
The operating system for the [six-agent ensemble](ROSTER.md). Agents are isolated subagents — they share **no memory**, only **files**: the live ledger ([`LEDGER.md`](LEDGER.md)) and the repo. Everything below makes that file-mediated collaboration safe and productive.
---
## 1. The unit of work: a great task
An iteration is only as good as its tasks. Every ledger task MUST be:
1. **Bounded** — one domain, one definition-of-done, completable in one session.
2. **Owned** — exactly one agent appointed (domain → agent is 1:1).
3. **Locked** — declares the files it will write; that set is its lock.
4. **Justified** — content cites sources, code references the task id, design references tokens.
5. **Gated** — Critic reviews before merge; nothing self-certifies.
6. **Logged** — on completion: ledger updated, commit made, `GOAL.md` touched if scope shifted.
If a task can't be written this way, it's too big — Maestro splits it.
---
## 2. The ledger lifecycle
Status flow, managed in [`LEDGER.md`](LEDGER.md):
```
backlog → ready → claimed → in-review → done
│ │
└───────────┴──→ returned (with findings) → ready
```
- **backlog** — captured, not yet actionable.
- **ready** — dependencies met; Maestro promoted it.
- **claimed** — an agent is working it; its files are now **locked**.
- **in-review** — work done, handed to Critic.
- **done** — Critic passed it; merged.
- **returned** — Critic failed it; carries specific findings; goes back to ready.
**The locking rule (prevents file conflicts):** an agent may only claim a `ready` task whose declared files do **not** overlap any `claimed` or `in-review` task. This serialises conflicting work without a central daemon — the check happens at claim time against the ledger.
---
## 3. File ownership map
Primary owner routes the task; co-reviewers must sign off on cross-domain files.
| Path | Primary | Co-review |
|---|---|---|
| `src/data/kb/**` (content) | Professor | Critic (validator) |
| `src/data/kb/SCHEMA.md`, `scripts/validate-kb.mjs` | Critic | Professor, Luthier |
| `src/components/**`, `src/services/**`, `src/App.jsx`, `electron/**`, build cfg | Luthier | Critic; Muse if visual |
| `tailwind.config.js`, visual layer, SVG renderers | Muse | Luthier (integration), Critic |
| `src/lib/theory.js` | **shared** Professor (music) + Luthier (code) | Critic |
| `docs/learn-curriculum.md`, `docs/progression-repertoire.md`, `docs/kb-*.md` | Professor | Herald (clarity) |
| `README.md`, `CONTRIBUTING.md`, `LICENSE`, `.github/**` | Herald | Maestro |
| `GOAL.md`, `docs/agents/LEDGER.md` | Maestro | all read |
**Shared files** (`theory.js`) get strict task-locking: only one task touching them runs at a time, reviewed by Critic **and** the non-owning domain.
---
## 4. The appointment algorithm (each iteration)
This is what `/jam-loop` (Maestro, run by the main loop) executes:
1. **PLAN** — read `LEDGER.md` + `GOAL.md`. Promote `backlog → ready` where deps are met. Pick the next batch by `priority × cadence-weight` ([weights in ROSTER](ROSTER.md)), ensuring file-disjointness for any parallel batch.
2. **APPOINT** — for each chosen task, dispatch the agent whose domain == `task.domain`.
3. **DISPATCH** — choose the shape:
- **Serial (default, proven):** one task → one agent via the Agent tool. A dependent chain → run in order.
- **Sprint (opt-in / "ultracode"):** independent ready tasks → parallel; dependent tasks → pipeline; via the Workflow tool.
- **Parallel writes to disjoint files** → give each agent `isolation: "worktree"`.
4. **GATE** — every completed worker task → **Critic** reviews (runs `npm run build`, `node scripts/validate-kb.mjs`, tests; applies judgment). Pass → `done`; fail → `returned` with findings.
5. **RECONCILE** — Maestro commits passing work (one commit per task), updates `LEDGER.md` + `GOAL.md`, writes a one-line iteration log.
6. **CONTINUE** — schedule the next iteration, or at sprint end open the PR (see §6).
**Appointing correctly = the five rules of great iterations** (§1) applied at dispatch: bounded scope to one agent, files locked, sources/refs required, Critic gate wired in, honest status on return.
---
## 5. Scheduling
The clean model: **schedule the conductor, not the band.** One recurring loop runs `/jam-loop`; each fire is one orchestrated iteration that appoints whichever agent the next ready task needs.
- **Session loop** (runs while this terminal is open): `/loop 1h /jam-loop` — good for a focused build sprint you're watching.
- **Cloud schedule** (durable, survives closing the session): `/schedule` → e.g. "run /jam-loop every weekday at 09:07" — good for steady background progress. Recommended for a standing ensemble.
Per-domain cadence is the **weight**, not a separate cron: content advances most iterations, OSS/docs every ~4th. To shift emphasis for a stretch (e.g. "design week"), Maestro raises Muse's weight in the ledger header — no schedule change.
**Advanced — true parallel cadences (not default).** You *can* run separate loops per agent (`/loop 1h /jam-loop --only professor`, `/loop 3h /jam-loop --only luthier`). Only do this with **worktree isolation mandatory** and **strictly disjoint file ownership per loop**, or they will collide on shared files (`theory.js`, `App.jsx`, the ledger). The single-conductor model avoids this entirely; prefer it unless you have a specific throughput need.
---
## 6. Branching, review, and PRs
- One **sprint branch** off `main` (e.g. `sprint-jam-guide`); each task is a commit (parallel disjoint work uses worktrees off the branch).
- Critic gates every commit; Maestro opens **one PR per sprint** to `main` summarising all tasks + validator/build status.
- **Known constraint (this machine):** `gh` CLI is not installed. Open PRs via the GitHub API using stored git credentials:
```bash
TOKEN=$(printf 'protocol=https\nhost=github.com\n\n' | git credential fill | sed -n 's/^password=//p')
# POST to https://api.github.com/repos/whattheflat/JamBuddy/pulls with {title, head, base, body}
```
(Repo was renamed `whattheflat` → `JamBuddy`; origin URL still works for push.)
---
## 7. Conflict resolution
- **File clash at claim time** → can't claim; pick another ready task or wait for the lock to clear.
- **Cross-domain disagreement** (e.g. Muse wants a layout Luthier says is infeasible) → Maestro decides, records the call in the ledger, and if it's a product question surfaces it to the human instead of guessing.
- **Critic vs author** → Critic's gate is binding on *correctness/quality*; on *taste/scope*, Maestro arbitrates. Returned work always carries specific, actionable findings — never a bare rejection.
- **Scope creep** → if a task grows mid-flight, the agent stops, notes it in the ledger, and Maestro re-splits. Silent scope expansion is the cardinal sin.
---
## 8. State lives in files (because agents don't share memory)
Every iteration must leave perfect context for the next, since the next agent starts fresh:
- the **ledger** carries task status, locks, and findings;
- the **commit** carries the change and its rationale;
- **`GOAL.md`** carries shifts in direction;
- a recalled **memory** file (`project_ensemble`) carries the standing setup.
Write as if the next agent has never seen this conversation — because it hasn't.
+63
View File
@@ -0,0 +1,63 @@
# The JamBuddy Ensemble — Agent Roster
Six specialised agents build JamBuddy as both a **real-time jam companion** and an **open-source learning platform**. They collaborate through files (a shared ledger + the repo), never through live conversation — exactly like a git-based human team. The conductor (Maestro) appoints; the five workers do; the gate (Critic) approves.
How they run: [`PROTOCOL.md`](PROTOCOL.md). What's queued now: [`LEDGER.md`](LEDGER.md). The product north star: [`../../GOAL.md`](../../GOAL.md).
| Agent | Role | Realised as |
|---|---|---|
| 🎼 **Maestro** | Orchestrator / product lead | the `/jam-loop` skill (run by the main loop) + [`.claude/agents/maestro.md`](../../.claude/agents/maestro.md) for solo planning |
| 🎓 **Professor** | Music & pedagogy | [`.claude/agents/professor.md`](../../.claude/agents/professor.md) |
| 🔧 **Luthier** | Engineering | [`.claude/agents/luthier.md`](../../.claude/agents/luthier.md) |
| 🎨 **Muse** | Design & UX | [`.claude/agents/muse.md`](../../.claude/agents/muse.md) |
| 🔍 **Critic** | Quality & review (the gate) | [`.claude/agents/critic.md`](../../.claude/agents/critic.md) |
| 📣 **Herald** | Open-source & community | [`.claude/agents/herald.md`](../../.claude/agents/herald.md) |
---
## Domains, ownership, and quality bar
### 🎼 Maestro — orchestrator / product lead
- **Mandate:** turn `GOAL.md` into bounded, dependency-ordered tasks; appoint the right agent; reconcile and merge; keep the ledger and goal honest. Writes the plan, not the feature code.
- **Owns (write):** `GOAL.md`, `docs/agents/LEDGER.md`.
- **Quality bar:** every task is single-domain, single-DoD, fits one session, declares files + deps. No task ships without a Critic pass logged.
### 🎓 Professor — music & pedagogy
- **Mandate:** the music brain. Research and author knowledgebase cells (the `/kb-expand` work, now a standing role), learning curricula, drills, and ear-training design; guard music-theory correctness.
- **Owns (write):** `src/data/kb/**` (content), `docs/learn-curriculum.md`, `docs/progression-repertoire.md`; **co-owns** `src/lib/theory.js` (music correctness) with Luthier.
- **Quality bar:** key-agnostic data only; `node scripts/validate-kb.mjs` green; named sources; pedagogically sequenced (intermediate, not step-one).
### 🔧 Luthier — engineering
- **Mandate:** build and revise the app — features, the audio pipeline, wiring the KB into the UI (the Jam Guide panel), refactors, performance, Electron.
- **Owns (write):** `src/components/**`, `src/services/**`, `src/App.jsx`, `electron/**`, build config; **co-owns** `src/lib/theory.js` (code) with Professor.
- **Quality bar:** `npm run build` green; no regressions to the audio callbacks' stability contract (see `CLAUDE.md`); diff matches the task; reuses design tokens, never raw hex.
### 🎨 Muse — design & UX
- **Mandate:** make it come to life on screen — visual design, layout, interaction, the "smart fit to screen" for the Jam Guide, SVG renderers' look, accessibility.
- **Owns (write):** `tailwind.config.js` (design tokens), presentational components and their styling, SVG visual specs (`ChordDiagram`, `MiniPiano`).
- **Quality bar:** uses `bg-surface`/`bg-panel`/`border-border`/`accent` tokens; responsive + fits the target viewport; WCAG-AA contrast; keyboard-reachable.
### 🔍 Critic — quality & review (the gate)
- **Mandate:** review every other agent's work before it merges; run the validator, the build, and any tests; apply judgment; return failing work with specific findings. Veto power.
- **Owns (write):** `scripts/validate-kb.mjs`, test infrastructure, review notes in the ledger. **Never** silently rewrites feature work — returns it.
- **Quality bar:** mechanical checks must actually be run (evidence, not assertion); findings are specific and actionable.
### 📣 Herald — open-source & community
- **Mandate:** make this a *platform*, not just an app — README that frames the learning-platform vision, CONTRIBUTING with the data-contract so musicians (not only coders) can PR a style, issue/PR templates, license, changelog, public roadmap.
- **Owns (write):** `README.md`, `CONTRIBUTING.md`, `LICENSE`, `.github/**`, contributor-facing docs.
- **Quality bar:** links resolve; instructions are runnable as written; a non-coding musician can follow the "add a style" path.
---
## Cadence weights (how the conductor balances the band)
Per-domain rhythm is expressed as how often Maestro is *eligible* to pick that domain each iteration — not as separate schedules (see [`PROTOCOL.md` §Scheduling](PROTOCOL.md)).
| Agent | Weight | Effect |
|---|---|---|
| Professor | 3 | content can advance every iteration |
| Luthier | 3 | engineering every iteration (tasks are larger, span iterations naturally) |
| Muse | 2 | when there is UI pending style (event-driven) |
| Critic | — | mandatory gate stage every iteration, not weighted |
| Herald | 1 | ~every 4th iteration, or when a contributor-facing change lands |
| Maestro | — | plans + reconciles every iteration |
+510
View File
@@ -0,0 +1,510 @@
# Dashboard polish — rail + licks (task D-70)
Concept doc for `sprint-dashboard-polish`. Revises the rail/licks layout that
`docs/design/one-screen.md` §4 and D-51 established, per the user directive of
2026-07-13 ("this looks amazing" + six refinements). No code here — this specs
the two bounded implementation tasks **L-70** (rail) and **L-71** (licks) and
proves the numbers.
Design tokens only (`tailwind.config.js`): `surface` #0f0f0f, `panel` #1a1a1a,
`border` #2a2a2a, `accent` #a855f7, plus the SVG note language already mirrored
in `MiniPiano`/`ChordDiagram`/`LickCard` (amber #f59e0b secondary, ACCENT_SOFT
#c084fc chord-tone, BASS_RING #fbbf24). No new colour is introduced.
The column geometry we build against (from D-51 / one-screen.md §4, unchanged):
```
right column 500px
section border+p-2 18
row border+p-1.5 14
vertical scrollbar 17 (classic Windows) … 8 (the thin bar we add in §2)
= row interior 451px worst case (classic) · 460px (thin) · 468 (none)
```
All fits below are proven against the **conservative 451px** interior; the thin
scrollbar we introduce in §2 only ever makes them more comfortable.
---
## 0. Scope boundary — dashboard only (user refinement 2026-07-13)
> "perhaps within the knowledge center it could be nice but leave it for now as
> is, only in the main JAM FULL SCREEN we need to optimize what we show."
**The net boundary (two settled user clarifications, 2026-07-13):**
- **Dashboard** (always-open band + ⛶ jam-view fullscreen) = **full visual
optimisation**: guitar ≤4, 2×2 smaller piano, uniform licks, dark scoped
scrollbars, no ▶.
- **Knowledge Center dock** (`KnowledgeDock`'s VoicingsSection + LicksSection,
the Circle of Fifths) **and `ChordDetailModal`** = **layout UNCHANGED** (all
shapes, normal piano, current lick size) **except the ▶ play buttons are
removed** — the user decided "then leave them off, better not," so ▶ comes off
**everywhere**, not just the rail.
So there are **two** kinds of change with **two** scopes: the *visual layout*
changes are **dashboard-only** (gated behind the dashboard fork), while the
*▶ removal* is a **deliberate global** change across every mount.
The trap is **shared components**:
| component | dashboard mount | Knowledge Center / modal mount | how they differ today |
|---|---|---|---|
| `VoicingBrowser` | GlanceRail rows + heard-live (`dense`) | VoicingsSection + ChordDetailModal (**no `dense`**) | the `dense` flag already forks them |
| `LickCard` | LicksStrip (`size="thumb"`) | LicksSection (`size="full"`) | the `size` prop already forks them |
| `MiniPiano` | rail thumbs (`size="thumb"`) | modal/ExplorePanel (`size="thumb"`/`"full"`) | needs a **new** `size="mini"` variant |
| `PianoLickCard` | LicksStrip (new wiring) | **never mounted** | no KC concern at all |
**The rule: gate the *visual* optimisations behind the dashboard fork and change
no default there; remove ▶ globally.** Concretely:
- `VoicingBrowser`*visual, dashboard-only:* guitar ≤4 + piano 2×2 apply
**only under `dense`** (the flag only dashboard mounts pass); non-dense
(VoicingsSection + ChordDetailModal) keeps **all shapes + the normal piano
layout**. *Global:* the ▶ is **removed from the component outright** (§3) — no
mount wants it anymore.
- `MiniPiano`: the smaller keyboard is a **new additive `size="mini"`**; `thumb`
and `full` are byte-untouched, so the modal/ExplorePanel render identically.
- `LickCard`: the uniform footprint is imposed **at the dashboard-strip mount**
(a wrapper box), **not** in `LickCard` — its default footprint is unchanged.
`LickCard` itself is edited only if it must lose a ▶ (it has none — see §3.3),
so the dock's LicksSection (`size="full"`) renders unchanged. `PianoLickCard`
is all-new to the strip.
- Scrollbar CSS: a **scoped `.dark-scroll` class** on the dashboard scrollers
only — the KC's own scrolling keeps the OS default.
**Restated L-70/L-71 byte-identity DoD:** the dock's VoicingsSection /
LicksSection and `ChordDetailModal` render **byte-identical to today EXCEPT the
▶ buttons are gone** (the D-41/D-51 non-dense-mount precedent — Critic
diff-checks it: the only permitted diff in those mounts is the removed play
button + its now-dead wiring).
---
## 1. Guitar: ≤4 shapes, recommended-first (dashboard `dense` only)
### 1.1 What changes structurally
Today the rail's guitar station shows a **separate own-cell** (the KB play's
recommended shape, accent border, "play" badge — `GlanceRail` StationRow
:215-231) **plus** `VoicingBrowser`'s full gallery of *every* placeable shape
(`matchingShapes` :76 returns all). Two problems: (a) the recommended shape is
usually also in `matchingShapes`, so it renders **twice**; (b) `maj`/`min`/`dom7`
have 5-6 placeable shapes, so own-cell + gallery = 6-7 cells that wrap to a
second line.
**Decision:** centralise the ≤4 rule inside `VoicingBrowser` and **delete the
separate own-cell**. `GlanceRail` passes the recommended shape down; the browser
renders it as the badged first cell and caps the total.
- New `VoicingBrowser` props (additive, default-off so modal/dock stay
byte-identical): `recommended` (a shape object) and `max` (number).
- `GlanceRail` (dense rail) passes `recommended={st.shape}` and `max={4}`.
- Non-dense mounts (`ChordDetailModal` Guitar tab, `KnowledgeDock` VoicingsSection)
pass neither → they keep showing **all** shapes with no cap (a detail view
should be exhaustive; the ≤4 fit constraint is the rail's alone).
This removes the pre-existing duplicate and guarantees ≤4 in one place.
### 1.2 The top-4 selection rule (exact ordering + tiebreak)
`matchingShapes(quality, rootPc)` still returns every placeable shape. The rail
then orders and slices:
1. **Recommended first** — the KB play's shape (`recommended`, matched into the
list by `label`; if it was filtered out as unplaceable, prepend it anyway).
Badged `play`, accent border — "the answer" prominence the old own-cell had,
now cell #1 of the row.
2. **Open-position forms** — shapes with an `Array.isArray(shape.frets)` grip
(open chords). They sit at the nut, sound the most idiomatic, and are what a
player reaches for first.
3. **Movable / barre forms by lowest base fret ascending** — closest to the nut
first (easiest hand position, most common voicing). Base fret is the value
`matchingShapes` already computes (`mod12(rootPc OPEN_PCS[idx])`, 0→12).
4. **Tiebreak** at equal category/base fret: **fewer muted strings first**
(count of `'x'` in `frets`/`offsets` — a fuller voicing wins), then the
shape's **declared order in `GUITAR_SHAPES[quality]`** (stable, honours the
KB author's priority). Deterministic — no reflow flicker as the root moves.
Take the first **4** (recommended + up to 3 more, recommended deduped so it
never repeats). **Qualities with <4 placeable shapes just show what they have**
— the rule is a cap, never padding; nothing is invented to reach four.
### 1.3 It fits one line
Guitar `GalleryCell` (dense, **no play button** — see §3): `ChordDiagram` thumb
75px + p-1.5 (12) + border (2) = **89px** box. Four across:
```
4×89 + 3×6 (gap-1.5) = 356 + 18 = 374 ≤ 451 ✓ (a 5th would be 469 ✗)
```
Four shapes on **one horizontal line, no wrap, no scroll** — exactly the user's
"4 guitar options visible so it would fit without scrolling."
---
## 2. Piano: 2×2 of compact MiniPianos (dashboard `dense` only)
### 2.1 The grid
**Under `dense`** the four `pianoVoicing` styles (`root` / `shell` / `rootlessA`
/ `rootlessB`, `PIANO_STYLES` :67) render as a **2-column × 2-row CSS grid**
(`grid-cols-2 gap-1.5`) — one clean 2×2 per chord. **Non-dense** (VoicingsSection,
ChordDetailModal) keeps today's flex-wrap gallery at `MiniPiano size="thumb"`
(0.8) with ▶ — byte-identical. As with guitar, the **separate own-cell is
dropped for piano**; the 2×2 *is* the chord's voicings. If the station's
authored voicing corresponds to one of the four styles (match on
`voicing.style`), that cell gets the accent border — the "recommended" signal,
for free, without a fifth cell. (Fuzzy-authored voicings that match no style →
no highlight; honest.)
Because the own-cell is gone, the piano grid spans the **full row interior**
(the `basis-[320px] flex-1` gallery column grows to ~451px), so each of the two
grid columns is `(451 6)/2 = 222.5px`.
### 2.2 The scale — arithmetic
`MiniPiano` VOICING thumb geometry: `baseW = 22·(7·OCTAVES + 1) + 2`,
`SVG_W = baseW · scale`, `SVG_H = (60 + 4)·scale`. Today `thumb` scale = **0.8**:
| crop | baseW | SVG_W @0.8 | cell box @0.8 (+14) | two-up + gap |
|---|---|---|---|---|
| 1-octave | 178 | 142.4 | 156.4 | 318.8 ≤ 451 ✓ |
| 2-octave | 332 | 265.6 | 279.6 | **565.2 > 451 ✗** |
So 0.8 **cannot** put two 2-octave crops side by side (the brief's 532>456). The
2-octave crop (the rootless 7th-chord voicings — `rootlessA/B` of `min7`/`dom7`/
`maj7` whose span pushes past one octave) dictates the scale. Solve for a column
of 222.5px:
```
332·scale + 14 ≤ 222.5 → scale ≤ 208.5 / 332 = 0.628 (the ceiling)
```
**Chosen: a new uniform `size="mini"` at scale 0.60** — below the 0.628 ceiling,
leaving a robust ~19px margin for sub-pixel rounding and the classic-scrollbar
worst case:
| crop @ **0.60** | SVG_W | cell box (+14) | two-up + gap (6) | fits 451? |
|---|---|---|---|---|
| 1-octave | 106.8 | 120.8 | 247.6 | ✓ (203 spare) |
| 2-octave | 199.2 | 213.2 | **432.4** | ✓ (18.6 spare) |
`grid-cols-2` sizes every cell to the 222.5px column, so 1- and 2-octave cells
share one uniform grid — a true 2×2 at both crops. A thumb crop never exceeds
**2 octaves** (a 4-note `pianoVoicing` spans ≤24 semitones; `OCTAVES =
ceil((maxNote octStart·12)/12) ≤ 2`), so 2-octave is the proven worst case —
no 3-octave escape hatch needed.
### 2.3 Legibility at 0.60 — the marks stay honest
White key = 22·0.60 = **13.2px** wide (vs `ChordDiagram`'s 11px string gap —
comparable, legibly playable). The root/bass signal is carried **primarily by
colour**, which does not shrink in meaning: root key = full accent #a855f7, other
tones = ACCENT_SOFT #c084fc, bass = amber ring #fbbf24 — the established tier
language. The "R" glyph and the amber ring are secondary reinforcement. Because
the SVG viewBox scales text with the keys, at 0.60 the `R` renders ~4.8px and the
ring ~1.2px — thin. **So `size="mini"` bumps the in-SVG `R` fontSize (8→10 in
viewBox units) and the bass-ring `strokeWidth` (2→2.5)** so both stay readable at
the smaller render. This is an additive branch in `MiniPiano.jsx` (Muse-owned SVG
renderer); the existing `thumb`/`full` paths are byte-untouched, so the modal and
dock render identically.
### 2.4 Row height (piano)
`MiniPiano` mini SVG_H = 64·0.60 = **38.4px**. Piano `GalleryCell` (dense, no
play): caption ~13 + gap-1.5 (6) + SVG 38.4 + p-1.5 (12) + border (2) = **71.4px**.
Two rows + grid row-gap (6) = **148.8px** for the 2×2 block — versus the old
gallery's ~3 wrapped cell-lines of ~118px each (~366px). Nearly halved (§6).
---
## 3. Remove ▶ everywhere (deliberate global removal)
Standing principle (memory): **glance over audio.** The user settled it — "then
leave them off, better not." So ▶ comes off **every mount**: the dashboard rail,
the dashboard strip, **and** the Knowledge Center + `ChordDetailModal`. Because no
mount wants playback, the machinery is **deleted outright**, not gated — this is
intended, not a side-effect.
### 3.1 `VoicingBrowser.jsx` (L-70) — delete the play machinery
- The `PlayButton` component (:103-121).
- `import { playVoicing, guitarShapeToNotes } from '../lib/chordAudio'` (:62).
- `handleRef` + `stopCurrent` (:184-188) and the `useEffect(() => stopCurrent,
[chordKey])` cleanup (:191) — both now dead.
- `playGuitar` / `playPiano` handlers (:197-211).
- The `<PlayButton>` inside `GalleryCell` (:149) and its `playLabel`/`onPlay`
props; the `playLabel`/`onPlay` passed at each call site (:243-244, :280-281).
- The mic-feedback microcopy (:300-309) — nothing plays anywhere now, so the
caveat is false; delete it.
- Now-unused after the above: the `useRef`/`useEffect` imports and the `chordKey`
local (only the deleted effect read it). Update the file-header comment.
This is the **only** permitted change to the non-dense (VoicingsSection /
ChordDetailModal) render — those mounts are otherwise byte-identical (all shapes,
normal piano layout); the visual `dense`-fork of §1/§2 leaves them alone.
### 3.2 `GlanceRail.jsx` (L-70) — dashboard-exclusive
`GlanceRail` is mounted **only** by the JamGuide rail, so its edits never leak:
- Delete the footer microcopy "▶ previews play through your speakers…"
(:292-295); replace with nothing (or a quiet "voicings follow the loop").
- Delete the own-cell `<figure>` block (:215-231) — folded into `VoicingBrowser`
per §1; pass `recommended={st.shape}` + `max={4}`.
- Update the header comment (":45 …every ▶ lives inside the gallery").
### 3.3 The licks strip (L-71)
- **`LickCard.jsx` has no play path** — the guitar tab card never had a ▶
(verified: no `PlayButton`, no `chordAudio` import). Nothing to remove there;
the dock's `size="full"` LickCards are unchanged.
- **`PianoLickCard.jsx` is the only lick ▶.** Remove: `import { playVoicing,
stopAll } from '../lib/chordAudio'` (:73); the `PREVIEW_BPM`/`currentSeq`/
`stopLick`/`playLick` sequencer (:167-198); the `PlayButton` component
(:484-502) and its render (:606-609); the `useEffect(() => () => stopLick(),
[])` unmount silence (:530, then drop the now-unused `useEffect` import). Keep
the `resolveDegree` import — realization needs it.
### 3.4 `chordAudio.js` stays — verified importers
`grep chordAudio src/**` → importers are `VoicingBrowser.jsx` (▶ deleted in
§3.1), `PianoLickCard.jsx` (▶ deleted in §3.3), and **`BassPatternCard.jsx`**
(untouched — the bass-rail pattern previews the user did **not** ask to remove,
out of both locks); the rest are doc comments in `voicings.js`.
`ChordDetailModal.jsx` does **not** import it directly — it plays via
`VoicingBrowser`, so deleting that ▶ removes the modal's too, exactly as the
user's global decision intends. So `chordAudio.js` stays (for `BassPatternCard`),
but nothing in the voicing/lick UI plays.
### 3.5 The shared-sequencer blocker is eliminated
D-60 flagged that `BassPatternCard` and `PianoLickCard` each hold a **private
module-level `currentSeq`**, so their previews could layer once both mount — the
reason PianoLickCard was never wired into the strip. Removing PianoLickCard's
playback deletes its `currentSeq` entirely: **there is no piano sequencer left to
conflict with.** The strip becomes purely visual; `BassPatternCard`'s sequencer
lives only under the BASS selector (where the strip is hidden anyway). So
PianoLickCard wires into the strip (§5) with **no `currentSeq` collision** —
confirmed.
---
## 4. Hidden-but-scrollable dark scrollbars
### 4.1 Mechanism — a scoped utility, defined once in `index.css` (L-70)
```css
/* Thin, dark, overlay-feel scrollbars for the jam dashboard's scrollers.
Scoped (a class), NOT global — the KnowledgeDock/Debug/Tuner/Settings
below keep the OS default. Raw hex is unavoidable here: ::-webkit-scrollbar
pseudo-elements are not reachable by Tailwind utilities. The values mirror
the design tokens (border #2a2a2a, panel #1a1a1a). */
.dark-scroll {
scrollbar-width: thin; /* Firefox */
scrollbar-color: #2a2a2a transparent; /* thumb=border token · track transparent */
}
.dark-scroll::-webkit-scrollbar { width: 8px; height: 8px; } /* WebKit/Blink */
.dark-scroll::-webkit-scrollbar-track { background: transparent; }
.dark-scroll::-webkit-scrollbar-thumb {
background: #2a2a2a; border-radius: 4px; /* border token */
}
.dark-scroll::-webkit-scrollbar-thumb:hover { background: #3a3a3a; }
```
- **Scoped, not global** (`*`): the recommendation is a `.dark-scroll` opt-in
class. Global would restyle every scroller in the app (the whole normal-mode
page, the dock, Settings' full-screen scroller). The user's ask is about the
dashboard's rail; keep the blast radius there.
- **Raw-hex exception, flagged to Maestro:** the DoD says "no raw hex outside
`tailwind.config.js`," but `::-webkit-scrollbar` cannot consume a Tailwind
class. `index.css` (which already carries the raw `#0f0f0f` body background)
is the correct home; the values are documented as mirroring the `border`
token. No *new* colour — #3a3a3a hover is a one-step lift of the same family;
if Maestro prefers, use `panel` #1a1a1a for the base and `border` #2a2a2a for
hover instead (both existing tokens). Either is fine.
- Contrast: a #2a2a2a thumb on the #0f0f0f/#1a1a1a surface is intentionally
quiet — it is chrome, not content, so it is exempt from AA text contrast; it
is still clearly grabbable (the point of "make them black or something").
### 4.2 Where it applies — every dashboard scroll container
| # | scroller | file:line | task | note |
|---|---|---|---|---|
| 1 | **rail right column** `xl:overflow-y-auto` | `JamGuide.jsx:484` | **L-71** | the headline visible bar |
| 2 | left column (jam-view) `xl:overflow-y-auto` | `JamGuide.jsx:475` | L-71 | consistency |
| 3 | LicksStrip horizontal `overflow-x-auto` | `JamGuide.jsx:888` | L-71 | the licks row |
| 4 | per-cell `overflow-x-auto` (voicing) | `VoicingBrowser.jsx:148` | L-70 | rarely triggers now (§2) — apply for the edge case |
| 5 | timeline/keyboard `overflow-x-auto` | `PianoLickCard.jsx:576,585` | L-71 | wide-lick edge case |
**File-collision resolution (the brief's ask):** the rail's *outer vertical
scroller lives in `JamGuide.jsx`*, which is **L-71's exclusive lock** — not
`GlanceRail`, not `App.jsx`. So the class **definition** ships in `index.css`
(L-70), and each `className="… dark-scroll"` **application** is made by whichever
task owns the file it lives in: L-70 applies it in `VoicingBrowser` (#4), L-71
applies it in `JamGuide` (#1-3) and `PianoLickCard` (#5). The class exists before
L-71 runs because **L-71 depends-on L-70** (already in the ledger). Zero shared
files. The visible rail bar is styled in L-71 — acceptable, because that scroller
was always a JamGuide-column concern, not a `GlanceRail` one.
---
## 5. Licks: uniform size + follow the instrument
### 5.1 The strip follows the global instrument
`instrument` already reaches the strip: App's global selector → `JamGuide`
`instrument` prop (:177) → `LicksStrip({ …, instrument })` (:433-445, :863).
Today the strip **always renders `LickCard`** (guitar), even under PIANO, with an
apologetic heading "(no piano licks in the KB yet)" (:885). Change:
- `guitar` → `LickCard` (unchanged renderer).
- `piano` → `PianoLickCard` (wire it in — the D-60 component, never mounted).
Needs `rootPc` + `chordLabel` from the playhead `context` station (which
carries `rootPc`/`quality`/`label`), and each lick carries its own `quality`.
- `bass` → the strip is already gated off (:432/:439 `instrument !== 'bass'`);
render a slim honest line "No bass licks in the KB yet" instead of nothing, so
the section doesn't silently vanish when a bassist is selected.
The licks reader `licksFor(id)` (:136) is **hardcoded to
`instruments.guitar.licks`** — L-71 generalises it to
`licksFor(id, instrument)`, reading `instruments.piano.licks` under piano, and
**filtering piano licks to the structured ones** (those with a `notes` array) so
prose-only entries don't render as `PianoLickCard` placeholders (see §5.3).
### 5.2 Uniform footprint — measure, target, change
Both are wrapped by the strip in `w-[220px]` (closed) / `w-[340px]` (open)
(:894), so **width is already uniform**. The gap is **height** — the two SVGs
auto-size by different aspect ratios:
- **`LickCard` thumb** (`layoutTab`): viewBox 96 units tall (17 + 5·14 + 9),
`TabSvg` `maxWidth = width·1.3`; inside a 204px inner box it renders ~125px
tall. Card ≈ 163px.
- **`PianoLickCard` thumb** (`layoutLick`): height = 14 + `plotH` + 8 (+10 beat
row), `plotH = max(26, range·semi)` — **varies with the lick's pitch range**,
so a wide lick is much taller than a narrow one and neither matches LickCard.
**Target: a shared thumb card of `220 × 150px`** (closed), `340px` wide (open).
**Imposed at the dashboard-strip mount, not inside the cards** (per the scope
refinement — do not touch `LickCard`'s default footprint). The `LicksStrip`
wrapper (JamGuide, L-71) that already sets `w-[220px]`/`w-[340px]` (:894) also
sets a **fixed content height** and normalises the card's SVG to fill it, e.g.
`class="… h-[150px] [&_svg]:!h-[104px] [&_svg]:!w-full"`. The cards' SVGs already
carry a `viewBox`, so `preserveAspectRatio="xMidYMid meet"` (the SVG default)
scales the tab / timeline to the 104px box and centres it — **zero edit to
`LickCard` or `PianoLickCard` internals.** Every card — guitar tab or piano roll —
then occupies the **same box**, "all the same size," and flips instrument in
place. (The `maxWidth: width·1.3/1.4` inline caps mean a short lick renders
narrower than 220 and centres — the card *box* is uniform; content is centred.)
**Scope proof (KC untouched):** the fixed-box CSS lives on the **`LicksStrip`
wrapper only** — a dashboard-exclusive element. `LickCard`'s and `PianoLickCard`'s
own geometry is unchanged, so the dock's LicksSection `size="full"` LickCards
(:817) render **byte-identical** (the L-71 DoD asserts it). `PianoLickCard` has no
KC mount at all.
### 5.3 KB coverage + empty-per-style behaviour
Verified against the KB (`instruments.piano.licks` with a structured `notes`
array — PianoLickCard-renderable):
| style | guitar licks | piano licks (structured) |
|---|---|---|
| jazz, blues, gospel, rnb | ✓ | ✓ (P-60/P-61) |
| pop | ✓ | **prose only** (`over`/`description`) — not renderable |
| bossa, country, funk, reggae, rock | ✓ | ✗ |
- **Guitar:** all 10 styles have tab licks — the strip works everywhere.
- **Piano:** structured, renderable licks exist for **jazz, blues, gospel, rnb**
only. Pop's `piano.licks` are the old prose education entries (no `notes`) —
the structured filter drops them, so pop reads as empty under piano too.
- **Empty-per-style:** today the strip returns `null` when empty (hides). Keep
hide-on-empty for **guitar** (the default; a silent gap is fine). For **piano
with zero structured licks** (pop + the 5 styles above), show a **slim honest
line** — "No {style} piano licks yet" — because the user *actively switched to
piano* and a vanished section is confusing there. Same slim line for bass.
---
## 6. Recomputed budget
Per-station row (row p-1.5 12 + border 2 + header block ~54 + gallery):
| | gallery block | **new row** | pre-polish row |
|---|---|---|---|
| Guitar | 4 cells ×1 line, no ▶ = **105px** | **~173px** | ~207px (5-6 cells, ▶, wraps) |
| Piano | 2×2 mini, no ▶ = **148.8px** | **~217px** | ~445px (0.8, ▶, 3 wrapped lines) |
Rail overhead (section p-2 16 + border 2 + h4 title ~22 + footer ~40) ≈ 80px;
rows joined by `gap-2` (8px).
| loop | instrument | **new total** | pre-polish | Δ |
|---|---|---|---|---|
| 4-chord | guitar | 80 + 4·173 + 24 = **796** | ~932 | 15% |
| 4-chord | piano | 80 + 4·217 + 24 = **972** | ~1884 | **48%** |
| 8-chord | guitar | 80 + 8·173 + 56 = **1520** | ~1720 | 12% |
| 8-chord | piano | 80 + 8·217 + 56 = **1872** | ~3640 | **49%** |
**Headline: the piano rail nearly halves (48%), and the guitar row is now a
guaranteed single line (≤4, never wraps).** Every total still exceeds the 500px
column, so **the rail remains the dashboard's one vertical scroller** — which is
exactly what §2's dark thin scrollbar dresses, and what the user licensed ("it
can scroll if we need to"). The polish makes each row compact and the scroll
pretty; it does not (and need not) fit a whole loop in 500px.
---
## 7. Migration order + bounded scopes
**L-70 — the rail.** Files (file-disjoint from L-71):
`src/components/GlanceRail.jsx`, `src/components/VoicingBrowser.jsx`,
`src/components/MiniPiano.jsx` (new `size="mini"` + R/ring bump — additive),
`src/index.css` (define `.dark-scroll`).
Does: guitar ≤4 recommended-first, **dense-only** (§1); piano 2×2 mini @0.60,
**dense-only** (§2); ▶ **deleted globally** from `VoicingBrowser`, own-cell +
footer from `GlanceRail` (§3.1-3.2); `.dark-scroll` defined + applied to
VoicingBrowser's cell scroller (§4 #4). `MiniPiano.jsx` is safe to lock here — no
other polish task touches it (`PianoLickCard`/`LickCard` carry their **own**
keyboard geometry and do not import `MiniPiano`).
**DoD byte-identity:** the non-dense `VoicingBrowser` render (VoicingsSection +
ChordDetailModal) is byte-identical to today **except the ▶ is removed**;
`MiniPiano` `thumb`/`full` byte-untouched (new `mini` is additive).
**L-71 — the licks.** Files: `src/components/JamGuide.jsx` (LicksStrip +
`licksFor` + the fixed-box wrapper + the scroller classNames),
`src/components/PianoLickCard.jsx`. **`LickCard.jsx` is *not* edited** — it has no
▶ and its footprint is imposed from the strip wrapper (§5.2), so it drops out of
the lock (dock LicksSection unaffected).
Does: uniform 220×150 thumb via the **strip wrapper** (§5.2); instrument branch +
PianoLickCard wiring + piano/bass empty states (§5.1/5.3); ▶ deleted from
`PianoLickCard` (§3.3); `.dark-scroll` applied to JamGuide's three scrollers +
PianoLickCard's (§4 #1-3,5).
**DoD byte-identity:** the dock LicksSection's `size="full"` LickCards render
byte-identical to today (no ▶ existed to remove there).
**Serialise L-70 → L-71** (already the ledger's `depends-on`): they are
**file-disjoint** (no shared file — the `.dark-scroll` *class* is defined in
L-70's `index.css` and merely *referenced* by L-71's JSX, which is not a file
edit collision), and L-71 needs L-70's class to exist. `JamGuide.jsx` belongs to
**exactly one** task (L-71), so the rail-column scrollbar has a single owner — no
shared-file clash. Critic gates each; `C-70` closes the sprint.
### Rejected alternatives
1. **Shrink `MiniPiano`'s global `thumb` scale (0.8→0.6) instead of a new
`mini`.** Rejected — it also shrinks the `ChordDetailModal` and dock thumbs,
which have room to spare and benefit from the larger keys; a scoped `mini`
variant keeps those byte-identical and confines the change to the rail.
2. **Give 2-octave piano crops their own full-width row (mixed cell sizes) at a
larger scale (~0.7).** Rejected — it breaks the clean "2×2 for each chord" the
user asked for; a uniform 0.60 grid keeps every chord a tidy 2×2 and 0.60 is
still legibly playable (13.2px keys ≈ the guitar diagram's string gap).
3. **Keep the separate own-cell and cap the gallery to 3.** Rejected — it leaves
the ≤4 rule split across two components (own-cell in `GlanceRail`, cap in
`VoicingBrowser`) and preserves the today's recommended/gallery duplicate;
centralising in `VoicingBrowser` (§1.1) is one place, one rule, no dupe.
4. **Global `*` scrollbar styling.** Rejected — restyles the entire app
(dock/Debug/Tuner/Settings) for a dashboard-scoped ask; a `.dark-scroll`
opt-in class is surgical.
+314
View File
@@ -0,0 +1,314 @@
# Glance Mode — the Knowledge Center while the jam plays (task D-31)
> **Thesis:** while a loop is live, the Jam Guide section stops being "Roadmap + one
> thumbnail per chord, tap to see more" and becomes a **playhead accordion**: a
> station-aligned rail under the Roadmap where the *current* station's column is
> expanded to the full D-30 voicing gallery (every placeable guitar shape, or every
> piano style, side by side) and every other station shows its recommended thumb.
> The expansion **follows the playhead** — over one loop cycle you see every
> variation of every chord with **zero clicks**. A licks strip for the matched style
> sits directly below, auto-sorted to the chord you're on.
>
> User directive (2026-07-10, verbatim): *"expand the learn session so we see as
> much as possible in voicing variations and styles without having to click buttons,
> the idea is to have it open as the jam is playing."*
**Decision authority:** per the sprint header (user away, no user gate), Muse picks
the strongest layout and records rationale + rejected alternatives (§6).
Implementation is task **L-33**; this doc is its blueprint. Depends on **D-30**
(VoicingBrowser becomes an all-variations gallery — chips removed, every
shape/style rendered simultaneously, each with its own ▶).
---
## 0. What exists today (read from the code, not assumed)
- `JamGuide.jsx` §jam renders `RoadmapAssembly`: `RoadmapTrack` on top, then a
**voicing strip** — ONE thumb per station (ChordDiagram thumb 75×72 px, or
MiniPiano D-24 cropped thumb ≈142 px for a 1-octave voicing / ≈266 px for a
2-octave one), tap-to-enlarge → full diagram + a `VoicingBrowser` mount.
Variations are therefore **one click away per chord** — the exact thing the
directive kills.
- `canonicalPos` (playhead station index, canonical KB order) already exists and
already drives `scrollIntoView` on the strip. **All glance data is already in
the component.**
- `VoicingBrowser` (post-D-30) renders ALL matching guitar shapes side by side
(cells ≈90120 px wide) and all four piano styles side by side (cropped
MiniPiano thumbs ≈140 px+), each independently playable. Placeable guitar
shapes per chord: **35** (maj: 4 movable + 1 native open; min7/dom7/maj7: 34;
dim/half_dim: 2). Piano styles: always **4** (root/shell/rootlessA/rootlessB),
or the authored recipe (L-24) plus the computed four.
- `LickCard` has `size="thumb"` and `LicksSection` already knows how to read
`kb[style].instruments.guitar.licks` defensively.
---
## 1. Chosen layout — the playhead accordion
```
┌ KNOWLEDGE CENTER — iiVI in C major ────────────────────────────────── ▲ ┐
│ [▶ Jam Guide ●] [Explore] [Voicings] [Licks & Techniques] │
│ [🎸 Guitar][🎹 Piano][🎵 Bass] · [Jazz●][Blues][Rock]… │
│ ┌─ ROADMAP ──────────────────────────────────────────────────────────────┐ │
│ │ Dm7 (ii) ──C→B── G7 (V) «NOW» ──F→E── Cmaj7 (I) ▁▁▁▂█▂▁▁▁ beat │ │
│ └────────────────────────────────────────────────────────────────────────┘ │
│ ┌─ VARIATIONS · follows the playhead ────────────────────────────────────┐ │
│ │ Dm7 ┃ G7 — every shape ┃ Cmaj7 │ │
│ │ [thumb] ┃ [E Barre][A7 Barre][D Shape][Open G7] ┃ [thumb] │ │
│ │ (recmd.) ┃ ▶ ▶ ▶ ▶ ┃ (recmd.) │ │
│ └─────────────┸───────────────────────────────────────┸───────────────────┘ │
│ ┌─ JAZZ LICKS · over the V7 first ─────────────────────────── (scroll) ──┐ │
│ │ [lick thumb «fits G7»] [lick thumb] [lick thumb] … │ │
│ └────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
```
- **Columns = stations** (canonical KB order — the kb-plan §4 grid intent,
finally literal): the rail's columns sit under the Roadmap's stations, same
order, same labels/rn.
- **Active column = expanded**: the station at `canonicalPos` renders the full
D-30 gallery (`<VoicingBrowser rootPc quality show={instrument}/>`). Collapsed
columns render today's recommended thumb (the KB play's shape / the threaded
piano voicing) — so the loop context and lookahead never disappear.
- **The accordion advances with the playhead.** Chord changes are the animation;
nothing else moves. Constant footprint: expanding one column collapses the
previous one, so the rail never grows taller mid-jam.
- **Licks strip** below: thumb LickCards for the active style, level-filtered,
sorted current-chord-context first (see §2.4).
Why this wins: it satisfies "as much as possible without clicking" *without*
pretending everything fits at once (§3 shows it can't) — across one loop cycle
the player is shown 100% of the variations, always for the chord their hands are
on, which is when a variation is actually learnable.
---
## 2. Auto-follow rules (zero clicks, precisely)
1. **Driver = `canonicalPos`** (already computed in JamGuide from
`findLoopPosition` + `match.rotation`). Expanded column = `canonicalPos`;
`position === -1` (loop known but playhead unknown) → station 0 expands, so
the rail is never all-collapsed. The active column auto-scrolls into view
(`scrollIntoView({inline:'center'})` — the existing strip pattern, prop-driven
off `position`, **no rAF, nothing tied to the audio thread**). Respect
`prefers-reduced-motion`: `behavior: 'auto'` instead of `'smooth'` (new —
today's strip smooth-scrolls unconditionally; fix while in there).
2. **Instrument tab** (existing) selects the gallery family — guitar shapes vs
piano styles. It's a mode preference, not a per-chord click; it keeps its
current default/behaviour.
3. **Loop change** (`match.id` / style / instrument change): rail re-derives from
the new `stationVoicings`, any pin (§4) resets — this is the *existing*
`selectedStation` reset effect, renamed. **No loop matched but chords are
committing** (`currentChord` set, `match.matched` false): the rail degrades to
a single "heard live" gallery — `parseChord(currentChord)` (the same
`src/lib/voicings.js` parser `VoicingsSection` uses) → one expanded
VoicingBrowser, re-aimed on every chord commit. **Nothing heard at all**: the
existing dashed empty state; no rail, no licks strip.
4. **Licks strip**: `kb[activeStyle].instruments.guitar.licks` (the defensive
read `LicksSection`'s local `licksFor` helper already implements), shared
level filter applied. Sort: licks whose `chordContext` matches the current
station's rn or quality first, with an accent ring + "fits G7 — now"
microcopy on those; re-sorts as the playhead advances (a reorder of ≤4 thumb
cards, cheap). `chordContext` is **free text** — the match MUST be
token-boundary on rn/quality (a naive substring makes rn "I" match "♭VII",
"Imaj7", "I7"); never ship "fits G7" on a ♭VII lick. The ring + "fits — now"
microcopy are **strip-owned chrome** rendered around the card — LickCard
itself shows `chordContext` only at `size="full"` and stays untouched, as §5
promises. Licks are **guitar-only in the KB**: when the instrument tab is
piano, the strip still shows the guitar licks (consistent with the existing
Licks & Techniques section, which does the same) and says so in its heading
("guitar licks"). Style has no licks → the strip **hides entirely**; an
empty state would steal glance space to say nothing.
5. **No auto-sound, ever.** Auto-follow never triggers `chordAudio` — speaker
output feeds the live mic and would poison the detection that drives the
playhead (the L-20 caveat becomes a feedback loop). Every ▶ stays a gesture.
The rail shows the mic-feedback microcopy once, not per gallery.
6. **`onFocusChord` (D-03 Fretboard link) stays gesture-driven.** Auto-follow
does NOT emit focus-chord — repainting the main fretboard every 2 s
uninvited would fight the player's own key view. Only a pin (§4) emits it,
preserving today's semantics exactly.
---
## 3. Density & space budget — honest math
Geometry sources: dock body = 70vh; RoadmapTrack station min-width 168 px + 34 px
rail; ChordDiagram thumb 75×72 px (+label); MiniPiano cropped thumb 142 px
(1-octave voicing) to 266 px (2-octave, e.g. most rootless voicings) × ~51 px
tall; D-30 gallery cells ≈ 90120 px (guitar) / ≈ 140280 px (piano) wide,
≈ 140 px (guitar) / ≈ 125 px (piano) tall including label + ▶.
### 1280 × 900 (the target the task names)
Vertical: dock body 630 px section nav ≈ 49 instrument/style row ≈ 47
content padding 32 RoadmapTrack ≈ 230 gap 16 = **≈ 256 px glance budget**.
- Guitar rail (heading + one row of cells ≈ 190 px): **fits**. ~66 px spare.
- Piano rail (≈ 175 px): **fits**.
- Licks strip (thumb LickCard ≈ 165 px; heading + thumb row ≈ 190 px): does
**NOT** also fit — 190 + 190 = 380 > 256. It sits just below the fold,
reachable by the dock's existing vertical scroll (a flick, not a click).
Fully above the fold only from ≈ 1070 px window height. Said plainly:
**at 1280×900 you get Roadmap + the full variations rail without scrolling;
licks are one scroll-flick down.**
Horizontal (~1200 px usable): collapsed guitar column ≈ 95 px; collapsed piano
column ≈ 160280 px (D-24 crop width varies with voicing span); expanded guitar
gallery 35 cells ≈ 340540 px. **Expanded piano gallery — the honest figure:**
root/shell cells are 1-octave crops ≈ 160 px, but **rootless A/B of any true-7th
chord span past one octave** (e.g. Dm7 rootlessA → notes [17, 21, 24, 28]), so
D-24's crop gives them a 2-octave keyboard = 266 px thumb ≈ 284 px cell. The
gallery is therefore 160 + 160 + 284 + 284 + gaps + section p-3 ≈ **940 px**
not the ~640 px four 1-octave cells would suggest.
| Loop | Guitar rail width | Piano rail width | One row? |
|---|---|---|---|
| 34 stations | 23×95 + ~450 ≈ **640740 px** | 23×~200 + ~940 ≈ **13501550 px** | guitar ✓ · piano ✗ (scrolls at ~1200 usable) |
| 8 stations (post-L-30) | 7×95 + ~450 ≈ **1115 px** | 7×~200 + ~940 ≈ **2300 px** | guitar ✓ (just) · piano ✗ |
**Cut order (what goes first):**
1. **Licks strip drops below the fold** (never cut, just deferred to scroll).
2. **Rail scrolls horizontally** with the active column auto-centred (the
existing strip pattern) — cells are **never shrunk** below the D-30 sizes;
a diagram you can't read is worth less than one you scroll to. This is the
piano rail's **normal state on any loop containing 7th chords — i.e. most
of them** (a rootless gallery is ~940 px on its own), not just long loops;
L-33's commit-5 viewport check must expect the piano rail to scroll, never
assert "one row fits".
3. **Narrow only (§ below): collapsed columns reduce to "next" only.**
### ~640 px wide (half-snapped window)
~576 px usable. The rail flips to the kb-plan §4 narrow rule — one thing per row:
- Row 1: the expanded gallery for the current station (guitar: 5 cells wrap to
2 rows ≈ 300 px; piano: 4 cells wrap to 2 rows ≈ 260 px).
- Row 2: a single **"next: Cmaj7"** collapsed thumb (lookahead is the one piece
of context worth its pixels at this width); other stations are dropped — the
Roadmap above still shows the whole loop.
- Licks strip: single-column, below, via vertical scroll.
Glance guarantee at narrow = **current chord's full gallery + the next chord's
thumb**, no interaction.
### 1280 × 800 (the older Electron-default figure in D-20)
Budget shrinks to ≈ 186 px — the guitar rail (~190 px) is 1 row of cells with the
heading merged into the rail's top edge (drop the standalone heading line,
18 px) and fits; everything else as at 900.
---
## 4. Interaction stays optional (but stays)
Nothing essential is behind a click; everything useful still responds to one:
- **▶ per gallery cell** (D-30): audition that voicing. Keyboard-reachable,
descriptive `aria-label`s, one-at-a-time playback (D-30's stop-previous
contract).
- **Pin a station**: tapping a *collapsed* column pins its gallery open,
overriding auto-follow (the accordion stops moving) — this **replaces**
today's tap-to-enlarge and inherits its semantics: the pinned station emits
`{rootPc, quality}` via `onFocusChord` (D-03 Fretboard guide tones), and the
existing reset effect (loop/style/instrument change → null) clears it.
Unpin = tap again or tap the visible "follow the jam" chip that appears while
pinned. `aria-pressed` on columns, `aria-current` on the live one.
- **Tap a lick thumb** → the card enlarges inline (`size="full"`); tap again to
collapse. The thumb already shows the full tab shape — enlarging is comfort,
not information.
- **Chord label tap** → `onChordClick` → ChordDetailModal, as everywhere else.
Focus order follows DOM order (columns left→right, then licks); all targets keep
`focus-visible:ring-2 ring-accent`, min 32 px height. Tokens only — everything
here uses existing `surface/panel/border/accent` + amber; **no new colour**.
Contrast inherits the measured D-20 §8 commitments (accent small text on
`bg-surface` cards; gray-400 floor for load-bearing labels; gray-500 microcopy
only).
---
## 5. Migration order for L-33 (green at every commit)
**App.jsx contract: UNTOUCHED — zero changes, not even additive.** Every input
glance mode needs (`detectedProgression`, `keyInfo`, `chordHistory`, `bpm`,
`currentChord`, `onFocusChord`, `onChordClick`) already flows into JamGuide.
Audio callbacks are therefore untouched by construction. If L-33 finds a gap,
the rule is prop-addition-only on the existing mount, never a callback/ref edit.
Files (for Maestro to re-lock at promotion):
| File | Kind of change |
|---|---|
| `src/components/GlanceRail.jsx` | **NEW** — pure presentational: props `{ stations, activeIndex, pinnedIndex, onPin, instrument, keyRoot }`; composes collapsed thumbs (existing ChordDiagram/MiniPiano) + one `<VoicingBrowser show={instrument}/>` for the expanded column |
| `src/components/JamGuide.jsx` | **Restructured (jam section only)** — RoadmapAssembly's voicing strip + enlarge block replaced by GlanceRail + LicksStrip; `selectedStation` becomes `pinnedStation` (same reset effect, same `onFocusChord` wiring); `licksFor` — today a closure-local function inside `LicksSection` (JamGuide.jsx:489), not an export — is **lifted out during the restructure** and shared with the strip. Sections 24, the shell, nav, and collapsed bar untouched |
| `src/components/VoicingBrowser.jsx` | **Additive-optional** — a `dense` prop (trim section padding, suppress the per-mount mic microcopy since the rail shows it once). Skip entirely if the D-30 cells already sit within the §3 budget |
| `src/components/LickCard.jsx` | **Untouched** (`thumb`/`full` already exist) |
| `src/App.jsx`, `RoadmapTrack.jsx`, `MiniPiano.jsx`, `ChordDiagram.jsx`, all `src/lib/**` | **Untouched** |
Commit order:
1. **Extract `GlanceRail.jsx`** rendering *today's* strip behaviour verbatim
(thumbs + tap-to-enlarge), JamGuide mounts it — a pure move, zero visual diff.
2. **Accordion**: expanded column = `activeIndex` (auto-follow off
`canonicalPos`), pin/unpin replaces tap-to-enlarge, the VoicingBrowser mount
moves from the enlarge block into the expanded column; reduced-motion guard
on the auto-scroll.
3. **No-loop fallback**: `parseChord(currentChord)` single gallery.
4. **LicksStrip**: thumb cards, level filter, context-first sort + live ring,
hide-when-empty, tap-to-enlarge.
5. **Narrow reflow + cut rules** (§3): horizontal-scroll behaviour, ≤640 px
next-only collapse; check 1280×900, 1280×800, ~640 px.
Each commit: `npm run build` + `node scripts/smoke.mjs` green; Critic gates.
---
## 6. Rationale + rejected alternatives (no user gate this sprint)
**Chosen — playhead accordion**, because: (a) it is the kb-plan §4 grid
(columns = chords, active-column highlight, narrow → one-per-row) applied to
variations; (b) constant footprint that survives 8-station loops (L-30) instead
of degrading; (c) 100% of variations shown per loop cycle with zero clicks, and
always for the chord under the player's hands — the moment a grip is learnable;
(d) it *reuses* D-30's gallery as-is and App.jsx needs nothing.
**Rejected A — "everything expanded" grid** (every station × every variation at
once — the literal maximal reading of the directive). Killed by §3's math: piano
is 4 stations × 4 styles = 16 cells at the honest §3 sizes (rootless cells
≈ 284 px) ≈ **3,500+ px** wide, or 3+ wrapped rows ≈ 480 px
tall — both force scrolling *while playing*, which is worse than zero clicks:
it's continuous manual tracking. At 8-station loops it's hopeless on any
viewport. Guitar-only at exactly 3 stations barely fits — a layout that only
works for its demo case is not a design.
**Rejected B — "Now panel"** (full-width mega-view of only the current chord:
giant gallery + licks + scale, no station columns). Maximum per-chord detail,
but it discards lookahead — mid-jam the *next* chord matters more than the one
already sounding — and at 120 BPM a 4-chord loop swaps the entire panel every
~2 s: visually violent, nothing is on screen long enough to read. The accordion
keeps 80% of the detail and all of the context.
**Rejected C — side-by-side split** (Roadmap left, variations dock right).
A 4-station track already needs 4×168 + 3×34 ≈ 774 px; splitting 1280 gives it
~640 — the flagship Roadmap gains a permanent horizontal scrollbar to make room
for a panel that duplicates its station order 90° rotated. Collapses entirely at
narrow. Rejected on viewport economics.
**Rejected D — timed carousel** (auto-cycle variations for the current chord
every N seconds). Zero clicks, technically — but motion untied to the music is
the most distracting thing a stage display can do, and it invents a second clock
next to the playhead. The music already provides the rhythm of change; follow it.
---
## 7. Out of scope / flags for Maestro
- **Explore/Voicings/Licks sections**: unchanged; glance mode lives entirely in
the jam section. (The Voicings section already follows `currentChord` — that
behaviour is untouched.)
- **Piano collapsed-thumb width variance** (142266 px per D-24's span-crop) is
the piano rail's main width pressure; if Critic finds real loops where it
reads badly, a future D-task could cap collapsed piano thumbs to a 1-octave
window around the bass — **not** in L-33's scope.
- **`dense` prop on VoicingBrowser** is optional and Muse-owned; L-33 should
attempt the rail with plain D-30 cells first.
- No new tokens, no new dependencies, no KB/theory/audio changes anywhere in
this design.
+422
View File
@@ -0,0 +1,422 @@
# Integrated Glance — the Jam Guide joins the main module (task D-40)
> **Thesis:** the Jam Guide stops being the last collapsible at the bottom of the
> page and becomes a **full-width, always-open band directly below the instrument
> view** — the third element of the main module. The loop is shown **once**, in
> ProgressionBanner (where the user says it already lives); the Roadmap track
> retires and its education (solo scales, guide tones, voice-leading) folds into
> the rail's station headers. The rail itself flips from the D-31 playhead
> accordion to **all stations expanded at once, as vertical rows** — every loop
> chord's full voicing gallery permanently visible, the playhead highlighting
> (never revealing) the active row. One global GUITAR/PIANO/BASS selector — App's
> existing `instrument` state — drives everything.
>
> User directive (2026-07-10, verbatim): *"i would like to move it up and
> integrate it somewhat in the space of the main module up top. or maybe right
> below it as it is super important. … i would like to be able to see the loop
> clearly, no need to have this repeated again. as its already in the main module
> … only one selection for GUITAR/PIANO/BASS and everything should show in that
> instrument. … i'd like to see all the chords and their voicings in a specific
> way in case a loop is detected (or at least just like 4 chords or something at
> least, so you can follow and potentially learn new ways to play it while you
> are playing the loop.) scrolling is easier then clicking"*
**Decision authority:** per the sprint header (no user gate), Muse picks the
strongest option and records rejected alternatives (§7). Implementation is
**L-40** (App restructure, §6.1) then **D-41** (rail rework, §6.2). This doc
supersedes `glance-mode.md` §1's accordion where they conflict — the user's
scroll license overturns D-31's "everything expanded" rejection (Rejected A
there), with the axis flipped to vertical (§4).
---
## 0. What exists today (read from the code)
App.jsx mount order: `ProgressionBanner` (~609) → instrument row (~618630:
`Fretboard`/`BassFretboard`/`Piano` at 70% + `ProgressionSuggestions` 30%) →
`CurrentJamPanel` (~634) → `LoopStation` (~642) → Debug/Drum/Tuner collapsibles →
**`JamGuide` last (~712)**. The global `instrument` state (App.jsx:58,
`'piano'|'guitar'|'bass'`) has its selector in the controls bar (~484) and drives
the main instrument views + DebugView — but **JamGuide ignores it** and runs its
own internal Guitar/Piano/Bass tabs (JamGuide.jsx ~405434, local state ~208).
The detected loop renders **twice**: ProgressionBanner's loop row (compact chips,
active chip highlighted via `findLoopPosition`) and `RoadmapTrack` inside the
JamGuide jam section (stations with solo-scale labels, guide-tone dots,
voice-leading rails, playhead + beat grid). Below the Roadmap, `GlanceRail`
(L-33) is a playhead **accordion**: one station's gallery expanded at a time —
the exact "it changes when the chord is not playing" complaint.
---
## 1. Placement — a full-width band directly below the instrument view
**Chosen: the Jam Guide content mounts as a full-width, always-open band
immediately below the instrument row, replacing `CurrentJamPanel`'s slot (before
`LoopStation`).** The four-section Knowledge Center dock stays at the bottom as
the browse/study area, minus its jam section (§5).
Why *below* the main module and not *inside* it:
- **Width math kills "inside".** The only free space inside the main module is
the 30% `ProgressionSuggestions` column (~360px at 1280) and the banner's
interior. A single piano station's gallery is **~1,178px** worst case: the
gallery calls `pianoVoicing` with no `prev` (VoicingBrowser.jsx:161), and
MiniPiano's D-24 crop is C-aligned (`octStart = floor(minNote/12)`), so any
station rooted **above D** crosses the C boundary even in root position and
shell — recomputed G7: root [7,11,14,17], shell [19,23,29], rootlessA
[23,26,29,33], rootlessB [17,21,23,26] → **all four cells are 2-octave 284px
crops** ≈ 4×284 + 24 gaps + 18 chrome ≈ 1,178px. (glance-mode.md's ~940px was
the Dm7-specific figure; 1-octave root/shell crops exist only for roots CD.)
Nothing gallery-shaped fits inside the module without crushing the neck/keys —
the surface the player's eyes track continuously.
- **"The main module" to the user = banner + big instrument view** — the
real-time detection surface. The guide answers a different question ("what
can I play on each chord of this loop") at a different rhythm (study-while-
looping). Directly below = one saccade down, same screenful top edge, no
competition for the detection pixels. The user himself offered "or maybe
right below it" — and the space math makes that the only honest reading.
- **Always open, zero chrome.** No collapse header (scroll past it if unwanted
— scroll > click), no section nav, no internal instrument tabs, no style
tabs, no level chips. The band is a pure auto surface: detection picks the
loop and style, the ONE controls-bar selector picks the instrument. The
`styleOverride`/style-tab machinery (JamGuide.jsx ~210212, ~438458) **dies
with the tabs**: the band always follows `match.style`; the heard-live
LicksStrip's `styleId` falls back to `styles[0]` when nothing is matched;
browsing OTHER styles stays reachable via the dock's own style chips
(LicksSection and ExploreSection each keep theirs). When no loop is matched
the band degrades to the existing "heard live" single gallery for
`currentChord`; when nothing is heard, a slim one-line hint (~40px) so it
never wastes main-module space.
- The band gets a micro-header line (`JAM GUIDE — {matched name} · in C major`,
uppercase tracking-widest gray-500 style), not a button.
Vertical position at 1280×900 (~860px usable): header ≈56 + controls bar ≈52 +
banner ≈140 + instrument row ≈300 + margins ≈24 → **the band starts ≈570px
down**; its first ≈290px are visible at rest, and one scroll-flick puts the
whole rail at the top of the viewport (§4 math). Estimates for the module
heights; verified figures for the rail.
---
## 2. The single loop display — ProgressionBanner survives, RoadmapTrack retires
**Call: ProgressionBanner's loop row is THE loop display. RoadmapTrack is
unmounted** (L-40 removes the import/mount; the file stays in place like the
EducationPanel precedent — deletion filed to backlog).
The user told us where the loop lives: *"no need to have this repeated again.
as its already in the main module"* — i.e. the banner. The banner is compact,
up top, always visible, and **already carries the playhead**: `findLoopPosition`
highlights the active loop chip (accent glow + amber rn). There is nothing to
absorb on that front — the beat grid's "current beat" was chord-accurate anyway
(RoadmapTrack's own comment: "coarse, chord-accurate — matches
ProgressionBanner"). **ProgressionBanner.jsx needs zero edits.**
Honest disposition of RoadmapTrack's unique value:
| RoadmapTrack feature | Disposition |
|---|---|
| Playhead (active station) | Already in the banner's loop chips — nothing lost |
| Beat grid + progress bar | **Dropped.** It never showed sub-chord progress (chord-accurate by construction); the BPM readout already lives in the controls-bar badge. Loss: the downbeat tick visual. If missed, a slim progress underline beneath the banner's loop chips is a future 1-point polish — explicitly NOT in L-40/D-41 |
| Solo-scale label per station ("G mixolydian") | **Folds into each rail row's header** (§4) via `soloScale` from theory.js |
| Guide-tone lane (3rd filled / 7th hollow dots) | **Folds into each rail row's header** ("aim" dots, same accent-filled/hollow language) via `guideTones` |
| Voice-leading rails (7→3 half-step arrows) | **Folds into a compact transition chip** at the end of each row header: "next: F→E · ½ step down" (via `voiceLeadingPairs`; wrap-around chip on the last row says "loop"). The between-columns arrow SVG dies; the information survives |
| Station "next" lookahead glow | Superseded: next row gets a small "next" tag; the whole loop is visible anyway |
Interim honesty: L-40 unmounts RoadmapTrack **before** D-41 builds the row
headers, so for one gate cycle the solo-scale/guide-tone/voice-leading education
is absent from the page (the banner still shows the loop; the accordion rail
still shows voicings). Accepted — D-41 follows immediately in the same serialized
chain; Critic should not flag the gap as a regression.
---
## 3. Instrument threading — one selector, honest bass
JamGuide's internal `INSTRUMENTS` tabs, `COMPUTED_INSTRUMENTS`,
`availableInstruments`, and local `instrument` state (JamGuide.jsx ~4247, ~178
184, ~208, ~405434) are **deleted**. App's existing `instrument` flows down as
a prop. Full prop paths to every consumer:
| Consumer | Path |
|---|---|
| GlanceRail (band) | `App.jsx instrument` (line 58) → `<JamGuide instrument={instrument}>``<GlanceRail instrument={instrument}>` (prop already exists; only its source changes) |
| VoicingBrowser, heard-live fallback (band) | App → JamGuide → `<VoicingBrowser show={instrument}>` (JamGuide.jsx ~494) |
| LicksStrip (band) | App → JamGuide → `<LicksStrip instrument={instrument}>` (both mounts, ~498 and ~757) |
| `stationVoicings` memo (band) | App → JamGuide — the memo's `instrument` dependency reads the prop |
| VoicingsSection (dock) | App → `<KnowledgeDock instrument={instrument}>` (§5) → `<VoicingsSection instrument={instrument}>` → its `<VoicingBrowser show={instrument}>` (ExplorePanel.jsx:425, today defaulting to `'both'`) |
| LicksSection (dock) | **No prop** — LicksSection is a module-local function in **JamGuide.jsx:562** (NOT an ExplorePanel export), and its heading is already statically honest ("Guitar licks · tab reads high e on top…"); licks are guitar-only in the KB (C-20 schema), so an `instrument` prop would be dead on arrival. Recorded so nobody threads it |
| ExploreSection (dock) | **No prop needed** — it renders progression chips + famous progressions, no instrument-specific renderer; chord taps open ChordDetailModal, which has its own user-driven Guitar/Piano tabs. Recorded so nobody threads a dead prop |
| DebugView | Already receives `instrument` (App.jsx ~676) — untouched |
The only `ExplorePanel.jsx` signature change is
`VoicingsSection({ keyInfo, chordHistory, currentChord, instrument })`
(its named exports are LevelChips / ChordPickerToolbar / GuitarGrid / PianoGrid /
ExploreSection / VoicingsSection — no LicksSection there).
### The honest bass state (until C-41/P-41/L-42 land)
BassFretboard covers the main view; the KB has **zero bass content** and both
gallery generators are wrong for bass (guitar shapes are not bass patterns;
`pianoVoicing` is piano). Showing guitar diagrams under BASS would break the
one-selector promise the user just made. Instead, when `instrument === 'bass'`
and a loop is matched:
- Station rows still render their full headers — chord, rn, solo scale, aim
dots. **Guide tones ARE the bassist's target notes**; none of this is
instrument-specific.
- The gallery slot renders a computed **root · fifth · approach** line per
station: root name, fifth name, and the chromatic approach into the NEXT
station's root ("approach: G♯ → A", computed from `stations[i+1].rootPc 1`
semitone — pure arithmetic on data the component already has; **no theory.js
change**). This is the honest useful minimum, not a placeholder.
- ONE notice for the whole rail (not per row): *"Authored bass patterns are on
the way (blues first) — meanwhile: roots, fifths, and the approach into the
next chord."*
- The licks strip hides under bass (guitar tab licks are noise to a bassist
mid-jam; under piano the strip keeps today's honest "guitar licks" heading).
**What L-42 slots in:** a per-station `<BassPatternCard>` (new component,
Luthier/Muse per the C-41 schema — 4-string, frets 015) mounted in the same
gallery slot of each row, replacing the computed line **when the matched style
ships a bass cell**; the computed root/fifth/approach line remains the
per-station fallback for styles without bass content. The rail's row structure,
highlight, and header need zero changes for L-42 — that's the contract.
---
## 4. The all-stations-expanded rail — vertical rows, playhead highlights
**Axis call: stations are VERTICAL ROWS** — one row per loop chord, each row =
station header + that chord's full horizontal voicing gallery; the page scrolls
down. All rows render all cells, always. **The playhead HIGHLIGHTS the active
row and never hides, collapses, or reveals content.**
Why vertical beats all-horizontal: a 4-station piano loop laid out as expanded
columns is ≈4 × 1,470px ≈ **5,900px wide** — continuous sideways tracking while
playing, on the axis mouse wheels don't scroll. Vertically, the worst piano row
is ≈ 284 (threaded cell — an authored LH 3-5-7-9 also crops 2 octaves) + 8 +
1,178 (§1 gallery) ≈ **1,470px of cells**, which does NOT fit 1,240px usable —
the gallery **flex-wraps to a second cell line** (~300px row height). **No
horizontal scroll survives because rows wrap, not because they fit.** Rows stack
~170300px tall and ≥4 chords sit within one to one-and-a-half screenfuls —
the "at least 4 chords so you can follow" ask, under the user's scroll license.
### Row anatomy (canonical KB order, same as the banner's loop after rotation)
- **Header (~30px):** chord label (gray-100 bold) + rn + "now" badge (accent,
when active) / "next" tag · solo-scale label ("solo · G mixolydian") · aim
dots (3rd filled accent, 7th hollow — RoadmapTrack's GuideDot language,
honest "5th" fallback kept) · transition chip ("next: F→E · ½ step down";
last row: "loop"). Header data via theory.js `guideTones` /
`voiceLeadingPairs` / `soloScale` — read-only imports.
- **Gallery:** first cell = the *station's own* voicing — guitar: the KB play's
recommended shape badged "play" (when present); piano: the threaded/authored
`stationVoicings[i].voicing` labeled honestly (e.g. "LH 3-5-7-9") — this is
where the accordion's collapsed-thumb value survives. Then the full
VoicingBrowser gallery (`show={instrument}`, `dense`): every placeable guitar
shape / all four piano styles, each with its own ▶ (D-30 one-at-a-time
playback contract). Bass: the §3 computed line (later the L-42 pattern card).
- **Active row:** `border-accent ring-2 ring-accent bg-accent/10` + "now" badge
+ `aria-current="true"`. Inactive rows `border-border bg-surface`, opacity
floor 0.85 (never dim below AA). Tokens only; no new colour.
- **Mic-feedback microcopy** once below the last row (rail-owned; galleries run
`dense`), as today.
### Focus semantics — pin simplified
With everything always expanded, the pin has nothing to hold open. It collapses
to a **focus toggle**: tapping a row header toggles that station as
`focusedStation` (renamed from `pinnedStation`, same JamGuide-owned state, same
reset-on-loop/style/instrument-change effect, same `onFocusChord({rootPc,
quality})` emission — the D-03 fretboard guide-tone contract is byte-compatible).
A focused row shows an "aim on fretboard" chip; tap again (or the loop changes)
to clear. `aria-pressed` on the header button, min 32px target,
`focus-visible:ring-2 ring-accent` everywhere.
**No auto-scroll.** The band lives in page flow, so `scrollIntoView` would yank
the whole page while the user reads the looper below — the accordion's
auto-centre effect is **removed**, not ported (deleted in the same L-40 commit
that promotes the band, §6.1 step 2 — today it is contained only by the dock's
70vh scroller, which the band no longer has). The playhead highlight travels;
the user owns the scrollbar (their explicit preference). On 4-row loops the
whole rail is one screenful anyway; on 8-row loops the banner up top always
shows the position. (Internal-scroll variant rejected: a nested scrollbar caps
the rail at ~62vh ≈ 3 rows — breaks the ≥4-visible goal at 900px.)
### Licks strip
Directly below the last station row, unchanged in behaviour: thumb LickCards
(~165px wide, strip ≈190px tall with heading), context-sorted to the playhead
station via the token-boundary matcher, strip-owned "fits X — now" ring, hides
entirely when the style has no licks, hidden under bass (§3). One flick below
the rows — consistent with its D-31 position in the scroll order.
### Space math (verified numbers: guitar cell ~93px, piano cells 160284px, piano gallery ~1,178px worst — §1, licks thumb ~165px)
Row heights: guitar row ≈ header 30 + cells ~140 + padding ≈ **185px**; piano
row ≈ 30 + one cell line ~125 + padding ≈ **170px** single-line, ≈ **300px**
when the gallery wraps to two cell lines. Row widths (cells): guitar ≈ play
cell + 35 gallery cells ≈ **460650px**; piano ≈ threaded cell up to ~284 +
gallery up to ~1,178 ≈ **~1,470px worst case**. Piano rows rooted above D with
a true 7th — i.e. most stations of most jazz/gospel loops — exceed 1,240px and
**wrap** (single-line piano rows exist only for roots CD or triad qualities);
rows never scroll horizontally.
| Scenario | 1280×900 (~1,240×860 usable) | ~640px wide (~576 usable) |
|---|---|---|
| 4-chord loop, guitar | 4×185 = **740px** — all 4 rows in one screenful (band scrolled to top); +190 licks strip = one flick more | cells fit one line (5×93+gaps ≈ 500); 4 rows ≈ 740px ≈ 1.3 screenfuls |
| 4-chord loop, piano | best case (roots CD / triads) 4×170 = **680px** ≈ one screenful; honest 7th-chord case (the jazz flagship): rows wrap → up to 4×300 ≈ **1,200px ≈ 1.4 screenfuls** — still zero clicks; the scroll license covers it | gallery wraps to 23 cell-lines → row ≈ 300430px; 4 rows ≈ 1,2001,700px ≈ 23 screenfuls, zero clicks |
| 8-chord loop (post-L-30) | guitar ≈ 1,480px ≈ **1.7 screenfuls** / piano ≈ up to 2,400px ≈ **2.8 screenfuls** — scroll, highlight travels, banner keeps the position | ≈ 2.56 screenfuls; still zero clicks |
At rest (no scroll) the band's visible ≈290px shows the header line + ~11.5
rows — enough to see the "now" row when it's early in the loop; one flick brings
the rail to the top. The user licensed exactly this trade.
---
## 5. What remains below — the dock slims to three sections, CurrentJamPanel retires
- **`KnowledgeDock`** (named export from JamGuide.jsx, §6.1): the bottom
collapsible keeps **Explore / Voicings / Licks & Techniques** — the browse
and study area (chord picker, KB progression browser, full lick grids, the
shared level filter). The **jam section is removed** (it IS the band now);
the dock's header drops the live match label and becomes static ("Knowledge
Center — browse & study"). Level-filter chips stay dock-only; the band shows
all levels (a glance surface filters nothing — directive 4).
- **`CurrentJamPanel` is unmounted by L-40.** The backlog already flags folding
it; the band moving into its exact slot makes its duplication terminal
(voicing strips → the rail; similar progressions → Explore; per-chord scale
labels → row headers). Honest loss: its mode-level `SCALE_IDEAS` prose and
`STYLE_VARIATIONS` cards exist nowhere else — the existing backlog item
("fold CurrentJamPanel's unique bits into the Knowledge Center") stays open
for Professor/Muse; the file is retired-in-place, deletion filed with
EducationPanel's. Note for Maestro: only `RiffDiagram.jsx` goes orphaned with
it — `ChordBox.jsx` is still imported by ChordDetailModal.jsx (lines 2, 58)
and ExplorePanel.jsx (lines 18, 170) and must **NOT** be deleted.
- **LoopStation** does not move — the band replaces `CurrentJamPanel` directly
above it, so it ends up right below the jam surface it feeds for free.
Debug/Drum/Tuner collapsibles unchanged.
- **ChordDetailModal, ProgressionSuggestions, Fretboard/Piano/BassFretboard,
ProgressionBanner:** zero edits.
Resulting App.jsx order: banner → instrument row → **Jam Guide band**
LoopStation → Debug → Drum → Tuner → **KnowledgeDock**.
---
## 6. Migration order — bounded scopes, green at every commit
Serialized: L-40 → D-41 (same surfaces). Each commit: `npm run build` +
`node scripts/smoke.mjs` green; Critic gates.
### 6.1 L-40 (Luthier) — App restructure + instrument threading + single loop display
**Files:** `src/App.jsx` (mounts + prop pass ONLY — 🚨 audio callbacks, refs,
AudioCapture props untouched, grep-gated), `src/components/JamGuide.jsx`,
`src/components/ExplorePanel.jsx` (VoicingsSection signature only — LicksSection
lives in JamGuide.jsx), `src/components/GlanceRail.jsx` (**one-line effect
deletion only**, see step 2 — re-lock at promotion per the ledger row).
**Not touched:** RoadmapTrack.jsx / CurrentJamPanel.jsx (unmounted, not edited),
ProgressionBanner.jsx, VoicingBrowser.jsx, all `src/lib/**`.
1. **Thread the instrument.** App passes `instrument` to the JamGuide mount;
JamGuide deletes its internal tabs/state/availability gating and consumes
the prop everywhere (§3 table); VoicingsSection gains the prop. Guide still
at the bottom, four sections intact. Green.
2. **Split and promote.** JamGuide.jsx → default export `JamGuide` (the band:
micro-header + jam content, always open, no section nav) + named export
`KnowledgeDock` (collapsible, 3 sections, level filter). App mounts the band
in CurrentJamPanel's slot, retires the CurrentJamPanel mount, keeps the dock
last. **RoadmapTrack unmounted** (loop now shown exactly once — the banner).
The band body for now = existing GlanceRail accordion + LicksStrip +
heard-live/empty fallbacks. **Same commit, mandatory:** delete GlanceRail's
auto-centre effect (GlanceRail.jsx:5667 `scrollIntoView`) — it is contained
today only by the dock's 70vh `overflow-auto` body; in page flow the nearest
scroller is the DOCUMENT, so every playhead advance would yank the whole
page — the exact failure §4 forbids. Promoting the band and deleting the
effect must land together. Green.
3. **Honest bass state.** `instrument === 'bass'` + loop matched → the §3
computed root/fifth/approach rows + single notice (band-level; no further
GlanceRail edits). Green.
### 6.2 D-41 (Muse) — the all-expanded rail
**Files:** `src/components/GlanceRail.jsx` (rework), `src/components/JamGuide.jsx`
(band wiring: pass `keyMode`, `pinnedStation``focusedStation` rename,
LicksStrip/bass-slot composition into rows), `src/components/VoicingBrowser.jsx`
(**optional**, `dense`-path styling only). **Not touched:** App.jsx,
RoadmapTrack.jsx, ProgressionBanner.jsx, MiniPiano/ChordDiagram/LickCard, libs.
1. **Rows.** Accordion → all-expanded vertical rows: every station renders
header + full gallery permanently; active row highlight (`aria-current`);
pin → focus toggle (same onFocusChord contract). The `scrollIntoView`
effect is already gone (L-40 step 2) — verify none is reintroduced. Green.
2. **Absorb the roadmap.** Row headers gain solo-scale, aim dots, transition
chip (theory.js read-only imports); gallery gains the "play"/threaded first
cell. Green.
3. **Reflow + verify.** Narrow (~640px) cell-wrap per row; eyeball 1280×900,
1280×800, ~640; AA/focus audit; verify **rows wrap and never scroll
horizontally** (the piano worst case ≈1,470px of cells does NOT fit 1,240 —
§4), and recompute the honest screenful counts against the §4 table. Green.
---
## 7. Rejected alternatives
**Rejected A — the guide inside the main module** (banner absorbs the rail, or
the rail replaces the 30% ProgressionSuggestions column). Killed by width math —
and the corrected worst case only strengthens it: ~360px column vs a ~1,178px
piano gallery (§1); inside the banner it competes with the
key/history/now-chord — the one surface that must stay instantly readable. The
user's "or maybe right below it" is the version of his own ask that survives
arithmetic. Also rejected structurally: ProgressionBanner doing loops + history
+ now-chord + galleries is a god-component.
**Rejected B — all-horizontal expanded rail** (stations as columns, every column
expanded). The literal reading of "all voicings at once", and the axis the old
accordion already had. With the corrected cell widths it gets worse, not better:
4-station piano ≈ 5,900px wide; 8-station ≈ 11,800px; continuous sideways
tracking on the axis wheels don't scroll, whole stations hidden off-edge at any
moment — the directive's "follow while playing" fails exactly when it matters.
Vertical rows carry the same content with zero horizontal scroll (rows wrap,
§4).
**Rejected C — RoadmapTrack survives as the single loop display** (banner's loop
row dies instead). Keeps the education-dense artefact, but contradicts the
user's own account of where the loop lives ("it's already in the main module"),
costs ~230px of premium height above the rail, and the banner would still show
near-loop-shaped history chips — the "repeated again" feeling survives its own
fix. Folding the education into row headers (§2) keeps ~90% of the value at
~30px per row.
**Rejected D — keep the pin/accordion semantics inside the expanded rail**
(pinned row grows a bigger gallery). With everything expanded there is nothing
left to reveal; a "bigger on pin" state reintroduces layout shift mid-jam — the
exact complaint. The pin's two real jobs (fretboard guide tones, "hold still")
survive as the focus toggle.
**Rejected E — internal max-height scroller for the band** (~5062vh, contained
auto-scroll). Caps visible rows at ~3 (< the user's "at least 4"), adds a nested
scrollbar inside the page scroll, and only exists to enable auto-scroll the
design doesn't want. Page flow + user-owned scrolling is simpler and matches
"scrolling is easier than clicking".
---
## 8. Out of scope / flags for Maestro
- **ProgressionBanner polish** (progress underline beneath loop chips) — future
1-pointer, only if the beat grid is missed. Not in L-40/D-41.
- **Cleanup ticket:** RoadmapTrack.jsx, CurrentJamPanel.jsx and its now-orphaned
RiffDiagram.jsx join EducationPanel.jsx in the retire-then-delete backlog
item. ChordBox.jsx stays — it is live in ChordDetailModal + ExplorePanel (§5).
- **`SCALE_IDEAS`/`STYLE_VARIATIONS` prose** (CurrentJamPanel's unique content)
— the existing fold-into-Knowledge-Center backlog item stays open.
- **L-42 contract** (§3): bass pattern card mounts in the row gallery slot;
rail structure frozen for it.
- No new tokens, no new dependencies, no KB/theory/audio changes anywhere in
this design. All figures either verified (guitar/licks cells from the D-31
gate; piano worst case recomputed at the D-40 gate — G7 all-284px, §1) or
marked as estimates (module heights).
+82
View File
@@ -0,0 +1,82 @@
# Jam Guide — Concept A: "Stage"
> Design concept for the Jam Guide panel (ledger task **D-00a**). One of three concepts; the user picks. Tokens: `bg-surface` #0f0f0f, `bg-panel` #1a1a1a, `border-border` #2a2a2a, accent #a855f7, amber #f59e0b. Colour language inherited from `Fretboard.jsx`: **chord tone = accent purple**, **now-playing = amber**, scale = gray.
## 1. Name + thesis
**Stage** — a stage-monitor for your hands. It optimises for the **half-second glance mid-jam**: the current chord huge and unmistakable, the *next* chord pre-loaded so you can move in time, and exactly **one** big recommended voicing to put your fingers on. Everything a textbook would add collapses away. For the player who is already playing and just needs to be *told the next move*, readable across a rehearsal room.
## 2. Mockup — realistic panel proportions (full-width, short)
Real example: **Standard 12-bar blues in A** (`blues-12bar`, detected loop `A7→D7→E7`), play **"Barre-chord shuffle"** from `blues/guitar.js`. The big diagram is the `E_BARRE7` grip — `{ rootStr:6, offsets:[0,2,0,1,0,0] }` — placed in A: root on low E at fret 5, so the barre sits at fret 5.
```
┌─ JAM GUIDE ──── Blues · 12-bar in A ────────────────── [Guitar▾] [Blues▾] [Stage|Playbook|Roadmap] ⌃collapse ─┐
│ │
│ NOW ░░░ NEXT ░░░ ── Barre-chord shuffle ── I7 IV7 V7 │
│ ┌────────────┐ shuffle · root on 6th str ● ○ ○ ○ │
│ │ │ ┌────────┐ bar 5 of 12 ┌──5fr──────────────┐ ○ ○ · · │
│ │ A7 │ → │ D7 │ ╾╾╾╾╾╾╾╾╾╾╾○╾╾╾ ── loop ── e│ ● │ ← R ● ○ · ○ │
│ │ │ └────────┘ ▮▮▮▮▮▮▮▮▮▮░░░░░ B│ ● │ ← 5 ○ ○ · │
│ │ I7 │ IV7 2 bars → change G│ ● │ ← 3 │
│ └────────────┘ D│ ● │ ← R │
│ ↑ playing now prep this A│ ● │ ← 5 │
│ E│ ● (5fr, barre) │ ← R "Strum short │
│ ▸ improv: A mixolydian · target the 3 (C♯) └───────────────────┘ — shuffle's in │
│ R=purple 3=amber accent the damp hand" │
└────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
```
The `NOW` block is the loudest thing on screen — a single giant amber chord name with its Nashville/Roman number under it. `NEXT` is a smaller ghosted card to its right with an arrow and a literal countdown ("2 bars → change") fed by the loop-position logic. The right two-thirds is **one** large `ChordDiagram` (the recommended voicing for the *current* chord) plus a 12-bar position strip (`I7 IV7 V7` mini-map) so the eye can confirm where it is in the form without reading the whole grid.
## 3. Interaction & live-sync model
- **Chord change (detection):** when `currentChord` flips, the `NOW` card cross-fades (reuse the 200 ms `scale(0.85)→1` animation already in `ProgressionBanner.jsx`), the old `NOW` slides left into a brief "just played" ghost, and `NEXT` promotes into `NOW`. The big diagram swaps to the new chord's recommended voicing.
- **Loop detected:** the position strip (`▮▮▮▮▮░░░`) and "bar N of 12" appear; without a loop, Stage still works — `NEXT` simply shows the most-likely next chord from `ProgressionSuggestions` and the bar-counter hides.
- **Position in loop:** drives the `NEXT` card and the countdown ("2 bars → change"). The countdown is the differentiator — it lets the player *prepare the grip* before the change lands, which is the whole point of a stage monitor.
- **Animates:** only the `NOW`/`NEXT` swap and the position-strip fill. Deliberately almost nothing else moves, so the panel never competes with playing.
- **Taps:** tap `NOW` diagram → cycle to the *next way to play* this chord (the other plays in the same `plays[id]` array, e.g. "9th-chord stabs"). Tap `NEXT` → make it the focus (peek ahead). Tap the improv line → expand the one-line scale/target hint into the lick. Tap the collapse chevron → shrink to a one-line header (chord + next), the always-visible resting state.
## 4. KB-data mapping (buildable from data we already have — guitar packs exist)
| Panel part | KB source |
|---|---|
| `NOW` / `NEXT` chord names + numerals | detected `currentChord` + matched progression `degrees`/`rn` rendered in the live key (rotation-invariant match, L-01 util) |
| Which progression + "12-bar in A" label | matched `progressions[].id` + `name` + `keyInfo.root` |
| Position strip `I7 IV7 V7` + bar counter | progression `rn` + `bars` arrays; active index from `findLoopPosition` |
| "2 bars → change" countdown | sum of `bars` from active step to the next chord change |
| Big chord diagram | `plays[id][playIndex].chords[step].shape` — movable `rootStr`+`offsets` placed by key (or open `frets`+`onlyRoot`); rendered by `ChordDiagram.jsx` (D-01) |
| "Barre-chord shuffle" label + tip | `plays[id][playIndex].label` + `.tips`; per-chord caption from `chords[step].note` |
| Finger dots / R·3·5 labels | `shape.offsets` → pitch classes vs `getChordTones(currentChord)`; root + 3rd get the colour tier |
| Improv one-liner | `improv.scales[].scale` matched to current chord + `improv.targetNotes` |
| "more ways" on tap | length of `plays[id]` array |
Every field above exists today in the eight shipped guitar packs. Piano/bass packs don't exist yet; Stage degrades cleanly — the instrument tab only lists instruments present in `kb/index.js`, exactly as L-02 specifies.
## 5. Pros / cons / sacrifices
**Pros**
- **Fastest possible read** mid-jam: one chord, one next, one grip — no scanning. The thing the user actually needs in the half-second is the biggest thing on screen.
- **Preparation, not just status:** the `NEXT` card + bar countdown is unique to this concept — it tells you the move *before* it happens, which is what a live monitor is for.
- **Cheapest to build & cheapest to animate:** renders one `ChordDiagram` at a time (vs a full grid), so it's the lightest on the audio thread and the simplest D-01/D-02 surface.
**Cons**
- Shows **one voicing at a time** — you can't compare three ways to play A7 side by side without tapping.
- Less of a "study" surface; a player who wants to learn the whole form's options at rest gets less here than in Playbook.
**Sacrifices:** the full progression grid (all chords × all plays visible at once). Stage trades breadth for legibility — it assumes you'll learn the catalogue at home and use Stage to *perform*.
```PREVIEW
STAGE — one chord, the next, one grip. A stage-monitor for your hands.
┌─ JAM GUIDE · Blues 12-bar in A ················· [Guitar][Blues] ─┐
│ NOW NEXT Barre-chord shuffle I7 IV7 V7 │
│ ┌──────────┐ ┌──────┐ ┌──5fr──────────┐ ▮▮▮▮▮░░░ │
│ │ │ → │ D7 │ e│ ● │ bar 5 / 12 │
│ │ A7 │ └──────┘ B│ ● │ │
│ │ │ 2 bars → G│ ● ←3 │ ↑ amber = now │
│ │ I7 │ change D│ ● │ ● purple = root │
│ └──────────┘ E│ ● 5fr barre │ │
│ ↑ playing prep this └───────────────┘ │
│ ▸ A mixolydian · target the 3 (C♯) │
└───────────────────────────────────────────────────────────────────┘
```
+116
View File
@@ -0,0 +1,116 @@
# Jam Guide — Concept B: "Playbook"
> Ledger task **D-00b** · domain: design · author: Muse
> Tokens: `bg-surface` #0f0f0f · `bg-panel` #1a1a1a · `border-border` #2a2a2a · `accent` #a855f7 · `amber` #f59e0b
## 1. Name + thesis
**"The Playbook"** — the whole loop opened flat like a method-book page: a grid where **columns are the chords of the progression** and **rows are different ways to voice it**, so you can read *across* the loop and *down* the voicings in a single glance and choose how you want to play it.
This is the **deepest-information** of the three concepts. Stage answers "what do I play *right now*"; Roadmap answers "where am I going". Playbook answers **"how is this whole thing played, and what are my options"** — the panel you open between choruses to study, then internalise.
---
## 2. Mockup — Blues 12-bar in A (real KB data, full-width ~70vh)
Rendered from `kb/blues/progressions.js` (`blues-12bar`) + `kb/blues/guitar.js` (`plays['blues-12bar']`). The 12-bar form collapses to its **3 distinct chords (I7 · IV7 · V7)** as columns — the grid teaches the *vocabulary*, the bar map (top strip) teaches the *form*. Each cell is a `ChordDiagram` (D-01). `●` = fretted/finger, `○` = root, `×` = muted, numbers above = barre fret.
```
┌─ JAM GUIDE ────────────────────────────── [ Guitar ▸ Piano Bass ] [ Jazz ‖ BLUES ‖ Rock Bossa Funk … ] ──┐
│ │
│ Matched: Standard 12-bar · A major your loop: A7 → D7 → E7 ♻ bar 5 / 12 · 96 BPM shuffle │
│ form: ┃A7┃A7┃A7┃A7┃D7┃D7▸┃A7┃A7┃E7┃D7┃A7┃E7┃ ← active bar pulses amber, sweeps L→R with the band │
│ ───────────────────────────────────────────────────────────────────────────────────────────────────────────── │
│ I7 · A7 IV7 · D7 ◀ playing now V7 · E7 │
│ │
│ Barre shuffle ●○ ● ● ● ● fr5 ●× ●○ ● ● ● ● fr5 ◀━━━━━ ●○ ● ● ● ● fr7 │
│ ▸ beginner-safe │○│ │ │ │ │ │×│○│ │ │ │ │ ◀ active col │○│ │ │ │ │ │
│ R-5-♭7-3 E-shape A7 A-shape D7 (glows) E-shape E7 │
│ "root on 6th str" "same fret, root str up" "two frets above IV" │
│ ───────────────────────────────────────────────────────────────────────────────────────────────────────────── │
│ 9th stabs ×○♭7 ● ● ● fr5 ×○♭7 ● ● ● fr5 ×○♭7 ● ● 13 fr7 (V13) │
│ ▸ intermediate │×│○│♭│●│●│●│ │×│○│♭│●│●│●│ │×│○│♭│●│●│●│ pinky → 13 │
│ R-3-♭7-9 (Texas) "slide in ½-step below" "IV9" "V13 — horn-section hook" │
│ ───────────────────────────────────────────────────────────────────────────────────────────────────────────── │
│ Tritone shells ×○ ● ● × × fr5 ×○ ● ● × × fr5 ×○ ● ● × × fr7 │
│ ▸ minimal/comp R-♭7-3 only "inner pair drops 1 fret → IV" "Chicago grip" │
│ │
│ ⌄ more ways (2) — Jimmy Reed boogie · Stormy Monday walk-up │
│ ═══════════════════════════════════════════════════════════════════════════════════════════════════════════── │
│ IMPROV over I7 → A Mixolydian · over IV7 → D Mixo · target the 3rds C♯→F♯→G♯ · the blues curl: ♭3↗3 │
│ lick ▸ B.B. box in C: e|8 10b12 10 8 · D bent to E (the 3rd) tap a cell to hear it ♪ │
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
```
Header reads tokens directly: panel `bg-panel`, hairlines `border-border`, the matched-style tab and active highlights `accent` (#a855f7), the live bar/now-playing pulse `amber` (#f59e0b) — matching `ProgressionBanner`'s existing "active = accent ring, numeral = amber" language so the two panels feel like one instrument.
---
## 3. Interaction & live-sync model
**Active-column highlight (the live thread).** The detected `currentChord` maps to a *column*, not a single cell. Reusing `findLoopPosition` (extracted to `src/lib/match.js` per L-01), the panel finds the loop index, looks up which of the 3 chord-columns that bar belongs to, and lights the whole column: an `accent` left-border rail, a faint `bg-accent/8` column wash, and an `◀ playing now` caret over the header. Because Playbook shows the *whole* loop at rest, the highlight is a **moving spotlight over a static page** — your eye already knows where the next column is, so you read ahead in rhythm. The top **bar-map strip** carries the finer-grained pulse (which of 12 bars), sweeping amber L→R; the grid columns carry the coarser "which chord". Two clocks, one glance.
**"More ways ▾" expansion.** Each cell stack shows the first **23 plays** that fit the panel height; remaining plays (the KB has up to 45 per progression — Jimmy Reed boogie, Stormy Monday walk-up, etc.) collapse behind a single `⌄ more ways (N)` row at the grid foot, labelled with their play titles so you know what you're expanding. Click → the grid grows new rows in place (panel scrolls internally, header + bar-map stay pinned). Per-row, a small `▸` chevron on the row label toggles that row's **tips** line (the `tips` string) and per-cell `note`/`extensions` annotations from collapsed to shown — dense by default, denser on demand.
**Instrument / style tabs.** Top-right: style tabs generated from `kb/index.js` keys (`jazz blues rock bossa funk reggae country rnb` today, growing as the loop fills cells) — the matched style is auto-selected and shown `accent`-filled; the others are quiet `text-gray-400` and switch the whole grid (re-voicing the same detected loop in another idiom — the core "Jazz→Bossa over one iiVI" payoff). Top-left: instrument segmented control (Guitar live; Piano/Bass dimmed until those packs exist, driven by `instruments` keys present in the registry). Both persist to settings.
**Scroll vs collapse.** Collapsed, the panel is a **single header strip** (`Matched: … · your loop · ♻ bar n/12`) always visible at the bottom of the app scroll — identical resting footprint to the other two concepts. Click the header (or scroll into it) → expands to ~70vh. Inside, the grid scrolls **vertically** (more rows than fit) with the header, bar-map, and improv footer pinned; on narrow viewports it reflows (see §5) so columns never crush.
---
## 4. KB-data mapping (proves it's buildable today)
Every cell is driven by existing fields in the shipped guitar packs — nothing new is invented:
| UI element | KB source (`kb/blues/…`) |
|---|---|
| Column headers (I7 · IV7 · V7) + `name`, key chip | `progressions.js``rn`, `name`, `mode`; deduped against `degrees`/`qualities` to the distinct chords |
| Top bar-map strip `┃A7┃A7┃…┃` | `progressions.js` → full `degrees` × `bars`, rendered absolute in the detected key |
| Row labels ("Barre shuffle", "9th stabs", "Tritone shells") | `guitar.js``plays['blues-12bar'][].label` |
| Row level badge (`▸ intermediate`) | `plays[][].level` |
| Each diagram cell | `plays[][].chords[stepForThisColumn].shape``ChordDiagram` (D-01); movable `rootStr`+`offsets` placed at the column chord's fret in the detected key; open shapes via `frets`+`onlyRoot` |
| Cell colour-tone label (`R-3-♭7-9`), `13`/`♭7` glyphs | `chords[].extensions` + the shape's computed pitch classes (chord-tone tier = `accent`, same as Fretboard) |
| Per-cell caption | `chords[].note` ("same fret, root str up", "V13 — pinky reaches the 13") |
| Per-row tips (▸ reveal) | `plays[][].tips` |
| "more ways (N)" titles | the remaining `plays['blues-12bar']` entries beyond the visible rows |
| IMPROV footer | `improv.scales[].over/scale`, `improv.targetNotes`, `improv.licks[].tab/description` |
| Style/instrument tabs | `kb/index.js` registry keys + each style's `instruments` keys |
Because a 12-bar has many bars but few distinct chords, the **column reducer** (distinct `degree`+`quality` pairs, order of first appearance) keeps the grid to 34 columns even for a 12-bar — exactly what makes "down the voicings" legible. A 4-chord loop (Axis IVviIV) yields 4 columns; the same component, no special-casing.
---
## 5. Pros / cons / what it sacrifices
**Pros**
- **Most information per screen.** You see the entire loop *and* 35 ways to voice each chord at once — the only concept that supports true *comparison* ("shells vs barres vs 9ths") side by side. This is the deepest-study option, the method-book page.
- **Teaches vocabulary, not just the moment.** Reading *down* a column is a voicing lesson; reading *across* a row is the form. Level badges (beginner→advanced grips in one stack) let a player climb difficulty in place.
- **Reuses every KB field with zero waste** — multiple `plays`, `level`, `tips`, `extensions`, `note`, improv — so the agent-authored content is fully surfaced (Stage/Roadmap show a slice; Playbook shows the book).
- **Grid is reflow-friendly:** narrow → one play per row, columns scroll horizontally (the kb-plan §4 "smart fit" fallback) without changing the mental model.
**Cons**
- **Density is the cost.** It is *not* a glance-and-go panel mid-solo — there's a lot on screen, and the moving column-spotlight is the only thing that's instant. A player needs a beat to study it; if they want "just tell me the one chord now," Stage wins.
- **Diagram real-estate pressure.** 35 rows × 34 columns of SVG diagrams is the heaviest render of the three; cells must shrink on small windows (mitigated by collapse + reflow, but a 13" laptop shows ~3 rows before scroll).
- **Bar-form abstraction.** Collapsing 12 bars to 3 columns is powerful but hides bar-by-bar order *in the grid* — recovered by the top bar-map strip, but that's a second thing to read.
**What it sacrifices:** *immediacy*. The whole design trades instant glanceability for completeness — a deliberate inversion of Stage. It assumes the musician has a moment (a turnaround, a verse they know, a teacher's pause) to look down and *study*, then look up and play. The active-column spotlight is the lifeline that keeps it usable even mid-jam, but the panel's centre of gravity is **learning the loop**, not surviving the next bar.
---
```PREVIEW
┌ JAM GUIDE · Playbook ──────────[Guitar][Jazz‖BLUES‖Rock…]┐
│ Matched: 12-bar · A maj loop A7→D7→E7 ♻ bar5/12 96BPM │
│ form ┃A7┃A7┃A7┃A7┃D7┃D7▸┃A7┃A7┃E7┃D7┃A7┃E7┃ (amber sweep) │
│ ──────────── I7·A7 ──────── IV7·D7 ◀now ──── V7·E7 ────── │
│ Barre shuffle ●○●●●● fr5 ×●○●●● fr5 ●○●●●● fr7 │
│ ▸ beginner E-shape A7 A-shape (glows) E-shape E7 │
│ 9th stabs ▸ ×○♭7●●● fr5 ×○♭7●●● fr5 ×○♭7●●13 V13 │
│ int (Texas) R-3-♭7-9 "IV9" horn hook │
│ Tritone shell ×○●●×× fr5 ×○●●×× fr5 ×○●●×× fr7 │
│ minimal/comp R-♭7-3 inner pair 1 Chicago grip │
│ ⌄ more ways (2): Jimmy Reed · Stormy │
│ ═════════════════════════════════════════════════════════ │
│ IMPROV I7→A Mixo · target 3rds C♯→F♯→G♯ · curl ♭3↗3 ♪tap │
│ ▲ columns = loop chords · rows = ways to voice · scan ↕ │
└──────────────────────────────────────────────────────────┘
```
+130
View File
@@ -0,0 +1,130 @@
# Jam Guide — Concept C: "Roadmap"
> **Thesis:** Don't show chords — show the *journey through the loop* and what to solo over it. A horizontal timeline with a live "you are here" playhead, each station previewing its guide tones (3rds & 7ths) and the scale to blow over, with voice-leading rails drawn *between* the chords so the player sees the next note coming before it arrives.
Concept C is the **improv-first** option. Where Concept A optimises for *playing the chord in front of you* and Concept B for *comparing voicings at rest*, Concept C optimises for the soloist's question: **"the loop is turning — what do I aim at next, and what scale carries me there?"** The chord *voicing* diagram is present but demoted to a thin strip; the hero is the **improv map**: a lane of guide-tone targets and a lane of voice-leading arrows running left-to-right under a moving playhead.
It leans hardest into the learning-platform vision in `GOAL.md` Part 2 (L2 "next-chord preview tier", target-note highlighting) and the curriculum's **Tier B — Playing the Changes** (guide tones, the 7th-falls-to-the-3rd rail) and **Tier D — Functional Ears** (seeing the loop as motion, predicting the V).
---
## 1. Name + thesis
**Roadmap** — the live progression as a horizontal highway: a playhead drives left-to-right through the loop, each chord is a station showing its **target tones + scale**, and **voice-leading rails** connect each station to the next so you read the change one beat early.
---
## 2. Mockup (full-width panel, iiVI in C — the gold-standard `jazz-251-major`)
Detected loop `Dm7 → G7 → Cmaj7`, key C major, mode major. Playhead currently over G7, leaning into Cmaj7. Active station glows accent-purple; the rest are dimmed by age exactly like the existing `ProgressionBanner` opacity tiers.
```
┌─ JAM GUIDE ───────────────────────────────────────────── [Guitar ▾] · Jazz │ Blues │ Rock │ Bossa … ─┐
│ iiVI in C major · your loop: Dm7 → G7 → Cmaj7 · ♻ 2 bars/chord · ~132 BPM │
│ │
│ ┌──── bar 1 ───────────┬──── bar 2 ───────────┬──── bars 3-4 ──────────────┐ ◀ lookahead 1 beat │
│ │ Dm7 (ii7) │ ▶ G7 (V7) ◀ now │ Cmaj7 (Imaj7) │ │
│ │ D dorian │ G mixolydian │ C major (avoid 4) │ ← SCALE lane │
│ ├──────────────────────┼──────────────────────┼────────────────────────────┤ │
│ │ guide tones │ guide tones │ guide tones │ │
│ │ 3rd ● F 7th ○ C │ 3rd ● B 7th ○ F │ 3rd ● E 7th ○ B │ ← TARGET lane │
│ │ ╲ │ ╲ │ │ (land these on 1) │
│ │ C ─────────▶ B │ F ─────────▶ E │ ( B holds → next loop ) │ ← VOICE-LEADING │
│ │ 7th of ii falls ½ │ 7th of V falls ½ │ resolved — get light │ rails (7→3) │
│ ├──────────────────────┼──────────────────────┼────────────────────────────┤ │
│ │ ▣▣·▣· shell │ ▣·▣▣· shell │ ▣▣·▣· shell │ ← voicing strip │
│ │ R–♭3–♭7 (tap ▸) │ R3–♭7 (tap ▸) │ R37 (tap ▸) │ (secondary) │
│ └──────────────────────┴──────────────────────┴────────────────────────────┘ │
│ ◐──────────────────────────────●───────────────────────────────────────── loop playhead │
│ │·····│·····│·····│·····│·····│●····│·····│·····│·····│·····│·····│·····│ ← beat grid (you here) │
│ │
│ TIP In any iiVI the 7th of one chord falls a half-step to the 3rd of the next — C→B, F→E. │
│ That two-note rail is the whole map. · tap a station → its guide tones light the fretboard ▸ │
└───────────────────────────────────────────────────────────────────────────────────────────────────────┘
```
The same panel over a **minor blues** (`blues-minor`-style, key A minor) reads as a longer highway — 12 stations scroll horizontally under the fixed playhead, the TARGET lane showing the ♭3/♭7 of each i7/iv7/V7 and the VOICE-LEADING rail highlighting the chromatic approach into bar 11's return home. The lookahead flag always sits one chord to the right of the playhead so the soloist sees the *incoming* target before the band gets there.
**Why this layout:** the three stacked lanes (SCALE / TARGET / VOICE-LEADING) are the literal pedagogy of "playing the changes" turned into a picture you read at a glance. The voicing strip is one row, not the hero — a soloist needs *where to aim*, not *how to grip*, and can tap to expand a grip when comping.
---
## 3. Interaction & live-sync model
**Playhead = loop position, continuously.** The `●` rides the beat grid driven by the onset/BPM pipeline (`handleOnset` tempo histogram → BPM) and the `findLoopPosition` util (extracted in L-01). Two sync layers:
- **Coarse (chord-accurate, ships first):** the active *station* is whatever `findLoopPosition(chordHistory, detectedProgression)` returns — exactly how `ProgressionBanner` already highlights the loop. Re-uses proven logic; no new timing risk. The playhead snaps station-to-station on each detected change.
- **Fine (beat-interpolated, phase 5 polish):** between detected changes, advance the `●` across the station's beat cells by interpolating `(now lastOnsetTime) × BPM/60`, clamped to the station's `bars × 4` beats. Purely visual easing — if detection corrects the position, the playhead re-snaps. Degrades gracefully to coarse when BPM is unknown.
**Lookahead.** The station immediately right of the playhead carries a persistent **lookahead flag** ("◀ lookahead"). Its TARGET lane is pre-lit at ~60% brightness a configurable lead (default 1 beat) before the playhead crosses the barline — this is L2's "next-chord preview tier" and the bassist's walking-line scaffold. The flag answers "what's coming" without the player losing the current station.
**Tap to drill deeper (progressive disclosure):**
- **Tap a station** → emits `onChordClick(chord)` (the prop `ProgressionBanner` already fires) so the existing `Fretboard`/`Piano` views light that chord's tones, *plus* a Roadmap-specific extra: the station's two guide tones render in the accent tier and its scale in the pentatonic/scale tiers — i.e. "show me where to aim on the neck."
- **Tap the SCALE label** → toggles the fretboard between the full scale and the chord-tone-only skeleton for that chord (the curriculum's "chord inside the scale" drill).
- **Tap the voicing strip `▸`** → expands that one cell into a full `ChordDiagram` (D-01) inline, without leaving the roadmap. This is the only place Concept C surfaces a real grip; it stays out of the way until asked.
- **Tap TIP** → expands the progression's `tip` plus any `lick.tab` whose `over` matches this progression id, rendered as monospace tab under the highway.
**Live behaviour when no loop is matched.** Fallback to a single-station roadmap centred on `currentChord`: its guide tones, a `getCompatibleScales`-derived scale, and the voicing strip — so the panel is never empty (same fallback contract as the kb-plan §4 matching note).
**Keyboard / a11y.** Left/Right arrows move focus station-to-station (independent of the playhead); Enter = tap; the active station carries `aria-current="true"` and a visible focus ring (`ring-accent`). The playhead has `role="progressbar"` with `aria-valuetext` = current chord + beat. All lane colours meet AA against `bg-panel` (the accent `#a855f7` on `#1a1a1a` and amber `#f59e0b` for the held/secondary tone both clear 4.5:1; dimmed stations never drop below the 0.25 opacity floor the banner already uses for legibility).
---
## 4. KB-data mapping — what's data vs. what's computed
| Roadmap element | Source | Data field / helper |
|---|---|---|
| Station chord names (`Dm7 G7 Cmaj7`) | **derived at runtime** | detected loop → key root + `progression.degrees` + `qualities`, resolved like `getSuggestedProgressions` already does |
| Roman numerals (`ii7 V7 Imaj7`) | **data** | `progression.rn` (display) — falls back to computed `toRomanNumeral` for the no-match case |
| Bars per station (`bar 1 / bars 3-4`) | **data** | `progression.bars` — drives station width on the highway |
| SCALE lane (`D dorian`, `G mixolydian`) | **data, with computed fallback** | KB `improv.scales[{over, scale, why}]` keyed by the chord's `rn`. If a style's pack has no `improv.scales` entry for a degree → **compute** a default from `SCALES`/`getCompatibleScales` (e.g. Mixolydian over a dom7) |
| "avoid 4" / scale caveats | **data** | `improv.scales[].why` (the jazz pack literally says "avoid sitting on the 4th over the maj7") |
| TARGET lane — 3rd & 7th tones | **fully computed** | `getChordTones(chord)` → index 1 = 3rd, last = 7th (per `CHORD_TYPES.intervals` ordering). *No KB field stores guide tones; theory.js derives them.* |
| VOICE-LEADING rails (`C ▶ B`, `F ▶ E`) | **computed** | for adjacent stations, find the 7th of chord *n* and the 3rd of chord *n+1*; draw a rail when they're a half/whole step apart. The "7→3 falls ½" relationship comes from comparing `getChordTones` outputs — pure interval math |
| TARGET-lane prose hint | **data** | `improv.targetNotes` ("Land the 3rd of each chord on the downbeat") |
| Voicing strip (mini grid + `R3–♭7`) | **data** | `plays[progId][0].chords[i].shape` (rendered tiny) + `.note` label; full grip on tap via `ChordDiagram` |
| TIP line | **data** | `progression.tip`; lick tab from `improv.licks[].tab` filtered by `over === progId` |
| Playhead position | **computed (live)** | `findLoopPosition` (L-01) + BPM from `handleOnset`; no KB data |
| BPM / feel label | **data + live** | `meta.tempoRange` / `meta.feel` for context; live BPM from the onset pipeline |
**Honesty note — the load-bearing computed pieces.** Concept C's two hero lanes are *not in the KB at all*:
1. **Guide tones** (3rd/7th badges) are computed from `getChordTones`. The KB stores *that* a scale fits and *that* the 7th resolves (prose), but never the literal pitches — those are derived per detected key. This is a feature: it stays key-agnostic (kb-plan principle 1) and works in all 12 keys for free.
2. **Voice-leading rails** are computed by diffing consecutive chords' tone sets. No new `theory.js` function is strictly required — `getChordTones` + a small `voiceLeadingPairs(chordA, chordB)` helper (≤15 lines: match each tone of A to its nearest tone in B, keep moves ≤2 semitones) covers it. I'd flag this helper to Maestro as a tiny shared `theory.js`/`match.js` addition Luthier owns; Muse only consumes its output.
Everything else is straight KB reads. The scale lane degrades gracefully: data-driven where a pack authored `improv.scales`, computed-default where it didn't — so the roadmap renders for *any* style cell, even a minimal one.
---
## 5. Pros / cons / what it sacrifices
**Pros**
1. **Directly teaches improv** — guide tones + scale + voice-leading rails are the curriculum's "playing the changes" pillar rendered literally; this is the only concept that answers *"what do I solo with?"* rather than *"what's the chord?"*
2. **Lookahead is built in** — the one-beat-early next-target preview is L2's headline learning feature and the thing a soloist physically needs; it's structural here, bolted-on elsewhere.
3. **Maximises the KB's prose assets**`improv.scales[].why`, `targetNotes`, `tip`, and `licks` (rich, sourced text the Professor wrote) get top billing instead of being buried under diagrams.
4. **Key-agnostic by construction** — the two hero lanes are computed, so one KB cell drives a correct roadmap in all 12 keys with zero extra data.
**Cons**
1. **Two computed subsystems** (guide-tone extraction, voice-leading pairing) before it looks "real" — more theory.js surface than A or B, which mostly *display* stored data. Mitigated: both are tiny and reuse `getChordTones`.
2. **Horizontal scroll on long forms** — a 12-bar blues exceeds one screen; stations must shrink or scroll. The fixed-playhead / scrolling-highway pattern solves it but is more layout work than a static grid.
3. **Voicing is genuinely secondary** — a player who opened the panel to *find a grip* has to tap to get it. That's the deliberate trade (see below).
**What it sacrifices**
- **Voicing comparison.** Concept B shows 3 ways to grip every chord side-by-side; Concept C shows *one* grip per station as a thumbnail and makes you tap for the rest. A jammer whose actual need is "give me a chord shape right now" is better served by A or B. Roadmap bets that the higher-value, harder-to-find guidance is *where to aim your solo* — and that voicings, being concrete and well-served elsewhere in the app, can wait behind a tap.
---
```PREVIEW
ROADMAP — improv-first: the loop as a highway you solo across
iiVI in C Dm7 → G7 → Cmaj7 ♻ 2 bars/chord ~132 BPM
┌── Dm7 (ii7) ──┬─▶ G7 (V7) ◀now ─┬── Cmaj7 (Imaj7) ──┐ ◀ look-
│ D dorian │ G mixolydian │ C major (avoid 4) │ ahead
│ 3rd●F 7th○C │ 3rd●B 7th○F │ 3rd●E 7th○B │ ← targets
│ C ──▶ B │ F ──▶ E │ ( B holds → loop )│ ← 7→3 rail
│ ▣▣·▣· shell ▸ │ ▣·▣▣· shell ▸ │ ▣▣·▣· shell ▸ │ ← voicing
└───────────────┴─────────────────┴────────────────────┘
◐────────────────●────────────────────────────────── playhead
│··│··│··│··│··│●·│··│··│··│··│··│··│ beat grid (here)
TIP 7th of one chord falls ½-step to the 3rd of the next:
C→B, F→E — that two-note rail is the whole map.
tap a station → its guide tones light up the fretboard ▸
```
+658
View File
@@ -0,0 +1,658 @@
# Jam Roulette — design spec (task D-62)
> **Thesis:** one button, two clicks, a jam. "Jam roulette" in the controls bar
> opens a genre menu (the 10 KB styles + Surprise me); picking one instantly
> rolls a random key + an interesting KB progression and **seeds the exact
> state live detection already writes** — `lockedKey`, `detectedProgression`,
> and a committed-shape `progressionVoteRef` — so the loop strip, the voicing
> rail, the licks strip, and the related-progressions card all populate
> **exactly as if the loop had been detected**. Musicians read the screen and
> start playing; the L-31 commit layer then treats the seed like any committed
> loop: agreeing detections confirm it, a genuinely different loop replaces it
> after `REPLACE_VOTES`, and New Song clears it. **No new parallel state**
> the seed is a writer into the existing machine, not a second machine.
>
> User ask (verbatim, sprint goal 2026-07-11): *"one button that would be a
> random chord progression selection. a button up top 'jam roulette' and then
> select a genre (like we have jazz, blues rock etc) and then have a random key
> chosen and an interesting progression show up as a loop in the screen. it
> would fill in the loop section and a 4 bar progression or something so that
> everyone can see the key and the chords to be played with different voicing
> so they can start playing… then musicians can start playing and it continues
> from it"*
**Dependency note:** L-60 is dep-blocked on **C-50** (one-screen close-out).
This spec is written against `docs/design/one-screen.md`'s **target** layout
(controls bar per §1.1, slim loop strip per §1.2, the two-column dashboard),
which L-50 is building concurrently. Everything here that names the controls
bar or the strip means the *post-L-50* versions; the seed mechanism (§3) is
layout-independent and verified against App.jsx as it stands today (~b753b58).
Standing principles honoured: reuse, don't duplicate; nothing shown twice;
scroll > click; tokens only, no raw hex; the 🚨 App.jsx audio contract
(callbacks / ref-sync / AudioCapture untouched).
---
## 1. UX flow
### 1.1 The button
- **Where:** right end of the controls bar, in the global-chrome cluster next
to one-screen §1.1's `⛶ Jam view` toggle ("a button up top" — the controls
bar is the app's persistent top chrome; the header row stays reserved for
Settings / New Song / Start).
- **What:** `🎲 Jam roulette` — same button language as the existing controls:
`px-3 py-1 rounded-lg border border-border text-sm text-gray-200
hover:border-gray-500 focus-visible:ring-2 focus-visible:ring-accent
transition-colors`. While a seed is active (unconfirmed, §1.3) the button
carries the seeded accent: `border-accent/40 text-accent bg-accent/10` +
`aria-pressed="true"` — same active treatment as the locked-key pill.
- **Keyboard:** real `<button>`, Tab-reachable, Enter/Space opens the menu.
### 1.2 The genre menu
Click → an anchored popover (not a page takeover; the jam never leaves the
screen): `absolute` panel under the button, `bg-panel border border-border
rounded-xl shadow-lg p-1 z-20`, one column of `<button>` rows
(`w-full text-left px-3 py-1.5 rounded-lg text-sm text-gray-200
hover:bg-accent/10 focus-visible:ring-2 focus-visible:ring-accent`):
1. **`✨ Surprise me`** — first row, divider under it (`border-b border-border`)
— uniform pick over the 10 styles, then §2 as normal.
2. **The 10 KB styles**, straight from the registry:
`Object.entries(kb).map(([id, s]) => s.meta.label)` — never a hard-coded
list; an 11th style appears here for free.
3. When a seed is active, row 0 becomes **`⟳ Re-roll — {styleLabel}`** (same
style, fresh key + progression, honouring §2's no-repeat memory) and
`✨ Surprise me` moves to row 1.
Escape / click-outside / picking a row closes it. Focus returns to the button.
Picking a genre seeds **instantly** — two clicks from cold to a full jam
dashboard. No confirmation step: re-rolling is cheaper than confirming.
### 1.3 The seeded indicator — honest provenance
The dashboard must not pretend the roulette loop was *heard*. Until live
detection confirms it, the slim loop strip's loop row swaps its chrome:
- The `♻` glyph becomes `🎲`; the `→ loop` tail becomes an amber provenance
chip: **`rolled · {styleLabel} · {progression.name} · {Σbars} bars — play
it!`** (`text-amber-400 text-xs` — amber is the app's established secondary
accent, the rn colour; no new token). Σbars comes from the KB `bars` array —
this is where "a 4 bar progression" is made visible.
- The loop chips themselves render **identically** to a detected loop (same
chip anatomy, chord + rn) — the chords are real instructions, only the
*provenance* differs.
- The moment the commit layer confirms the seed (§3.4 — first agreeing live
detection), the indicator flips to the normal `♻ … → loop` with no other
visual change: the honest signal that "the band is now playing what was
rolled". If a *different* loop replaces the seed, the indicator vanishes
with the seed (the new loop is detection-owned).
Empty-state note: pre-first-note the history slot still shows "Start
listening…" — correct and honest (nothing has been heard); the key chip shows
the rolled key immediately (it's a real `lockedKey`, rendered with the 🔒 pill
in the controls bar too, mode dropdown and unlock included — the rolled key is
a first-class key lock, not a special display).
### 1.4 Flow summary
Cold start: **🎲 → genre → the dashboard fills** (key chip + locked-key pill,
loop chips with rn, voicing rail with every station's shapes/voicings, licks
strip aimed at station 0, related progressions) → band reads, plays → playhead
lights on the first committed loop chord → detection confirms after ~2 cycles
→ 🎲 indicator becomes ♻ → the jam continues under pure live detection.
Mid-session: 🎲 acts as **New Song + seed** (§3.6) — one gesture, clean slate,
new card.
---
## 2. Randomization rules
All randomness lives in the seed function (plain `Math.random()`; no audio
contact). Inputs: the KB registry only.
### 2.1 Key
- **Root:** uniform over the 12 pitch classes, spelled from **`NOTES` (sharp
spellings)** — mandatory, not stylistic: `matchChordFromChroma` names every
committed chord via `noteName(r)` with `preferFlat=false` (theory.js:112,
445 — the live naming path), so only sharp spellings string-match detection
later (§3.3).
- **Mode:** taken directly from the rolled progression's `mode` field —
verified: **every KB progression encodes `mode`**, vocabulary
`major | minor | dorian | mixolydian` (grep across all 10
`progressions.js`), all four already present in the key-lock mode dropdown
and `SCALES`. No inference, no default needed.
- **Confidence:** `1` (the `applyLock` convention).
- Session memory: don't repeat the previous roll's root (re-draw once).
### 2.2 Progression pool ("interesting" AND seedable)
Per style, from `kb[style].progressions`, each entry realized + collapsed per
§3.2 first. **Pool membership = the hard bounds ∩ the round-trip invariant**
— a progression only rolls if the machine can genuinely confirm it:
- **Hard length bounds: collapsed length must be 28.**
- `< 2` — unrepresentable as a detected loop (`detectRepeatingProgression`
min pattern length 2). Today this excludes **nothing**: even
`funk-one-chord` collapses to **two** names (`X7, Xsus4` — its
`['dom7','dom7','sus4','dom7']` qualities survive collapse because a
quality change on the same root is a different name; wrap-dedupe then
drops the trailing `X7`). The rule stays as future-proofing for a true
single-name vamp, and the code comment must say so honestly.
- `> 8` — the detector's candidate loop only sweeps lengths **28**
(theory.js:627). A longer seed is not merely unconfirmable: as the band
plays it, in-window *fragments* of it become the only detectable
structure and **replace the seed after `REPLACE_VOTES` = 3** — the card
self-destructs into a sub-loop. Excludes today: `jazz-blues` (collapsed
10), `blues-quickchange` (9), `bossa-blue` (10).
- **Round-trip invariant (the real gate) — the protocol is load-bearing:**
*a progression passes iff, with the 32-commit window filled with
repetitions of its seeded canonical form (steady state) and truncated at
**every** partial-cycle offset (0…len1 commits past a cycle boundary),
the real `detectRepeatingProgression` returns exactly that form at **all**
offsets.* Steady-state-plus-all-offsets is the honest protocol because a
jam is sampled mid-cycle, not at cycle boundaries — and a naive "feed 2
clean cycles" protocol gets *both* failure modes wrong: it spuriously
fails all 8 two-name vamps (2 cycles × 2 names = 4 commits, under
theory.js:609's history ≥ 6 gate — a ramp artifact, not a steady-state
failure), and it *passes* `blues-8bar`, whose 7-name form actually fails
at exactly **1 of its 7 phase offsets** (4 cycles + 4 extra commits → the
detector prefers the `[C7, G7]` alternation). Round-trip is *empirical,
not constructional* — the detector's recency×occurrence scoring can prefer
an internal alternation over the full form at some phase. The invariant is
**precomputed over the whole registry** (lazy module-level memo on first
roulette open — key-independent per §3.3.3, so one sweep in C covers all
keys; an 11th style or new progression joins the pool automatically) and
**pinned by the L-60 commit-1 smoke sweep** (same protocol verbatim —
§3.4 flag 2).
- **Honest numbers today (Critic gate ran the real matcher + detector under
the protocol above):** **4/56 fail** — the 3 over-length forms plus
`blues-8bar`'s phase-offset failure — so the **expected pool is 52/56**,
pinned exactly by the smoke sweep. (Pre-fix-(a), 10/56 additionally
returned NO MATCH for their own collapsed form and `country-145` matched a
different progression — §3.3.1; all return to the pool with the fix, since
matching post-fix is constructional, §3.3.4.)
- **Weight = levelW × lenW** (over pool members only):
- `levelW`: `level === 'intermediate'`**2**; foundation/untagged → **1**
(the D-20 rule: untagged counts foundation). "Interesting" = intermediate
leans in, foundations still roll.
- `lenW`: collapsed length **37 → 2** (the "4-bar-ish" sweet spot — note
a collapsed 12-bar blues is 7 names, so the genre's staple stays strong);
**2 and 8 → 1**.
- **No-repeat memory:** `rouletteMemoryRef` (plain `useRef([])` in App —
UI-state ref, never read by audio code) keeps the last **6** rolled
progression ids; they're excluded from the pool. If exclusion leaves the
pool empty (small styles — several have 5 entries), fall back to excluding
only the immediately previous id. The ref survives New Song deliberately
(variety across songs is the point) and dies with the session.
- Weighted draw; push id to memory.
---
## 3. The seed mechanism — spec'd against the real App state
### 3.1 What the seed writes (exhaustive)
`rollJam(styleId)` — a plain function in App.jsx, sibling of
`quickLock`/`newSong`:
```
1. newSong() // §3.6 — the clean-slate rule
2. const info = { root: NOTES[rolledPc], mode: prog.mode, confidence: 1 }
setLockedKey(info)
effectiveKeyRef.current = info // the quickLock precedent —
chordVotesRef.current = [] // detection uses the key NOW
3. const loop = seedableLoop(prog, rolledPc) // §3.2 — realize→collapse→canonicalize
4. setDetectedProgression(loop)
5. progressionVoteRef.current = {
committedKey: loop.join(','), // the committed shape, L-31's own
candidateKey: null,
candidateCount: 0,
seeded: true, // §3.4 — the one flag L-60 adds
}
progressionMissRef.current = 0 // (newSong already did; explicit)
6. setSeedInfo({ styleLabel, name, bars }) // §3.5 — display provenance
7. rouletteMemoryRef bookkeeping (§2.2)
```
Nothing else. **Never touched:** `handleNote` / `handleChroma` / `handleOnset`
/ `handleWaveform`, AudioCapture and its props, `noteHistoryRef`,
`keyVotesRef`, `chromaRingRef`, the loop engine. The seed is display state +
the two progression refs the L-31 effect already owns — exactly the audio
contract boundary the L-60 ledger row grep-gates.
Synergy worth stating: `handleChroma` bails while `effectiveKeyRef.current` is
null — a cold session normally can't commit chords until key detection locks.
The seed provides the key up front, so **the very first chroma frames can
commit chords**, and the diatonic bonus in `matchChordFromChroma` is already
biased toward the rolled key. The roulette makes detection *faster*, not
just decorated.
### 3.2 Realizing the loop — `seedableLoop(progression, keyRootPc)`
The chord names must be **byte-identical** to what detection would commit when
the band plays the progression, or the commit layer treats the seed as a rival
forever. Three steps, each forced by a verified code path:
1. **Realize** (the JamGuide `stationVoicings` formula, JamGuide.jsx:262-273):
per station `rootPc = (keyRootPc + degrees[i]) % 12`,
`name = NOTES[rootPc] + (CHORD_TYPES[qualities[i]]?.suffix ?? '')`.
Sharp spellings only (§2.1).
2. **Collapse consecutive duplicate names**, then if `first === last` drop the
last — mirrors `detectRepeatingProgression`'s collapse of back-to-back
commits (theory.js:611-615) *plus* the cyclic wrap (in the live stream the
loop's tail flows into its head; `setChordHistory` also dedupes
consecutive identical commits, App.jsx:363). E.g. `blues-12bar` degrees
`[0,0,0,0,5,5,0,0,7,5,0,7]` → 7 names `[I,IV,I,V,IV,I,V]` realized;
`funk-one-chord` keeps its quality changes (same root, different suffix ≠
duplicate → `[X7, Xsus4]`). Name-collapse is provably **key-independent**
(§3.3.3) — the collapsed *shape* is a property of the progression, which
is what makes fix (a) (§3.3.2) computable once, key-free.
3. **Canonicalize rotation** with **theory.js's own rule** — lexicographically
smallest rotation compared via `join('\0')` (`canonicalize`,
theory.js:579-586, currently private). `detectRepeatingProgression`
returns *its* canonical rotation; the agreement branch compares exact
`join(',')` strings, so the seed must store the same rotation or
confirmation is unreachable (§3.4 flag 2).
**Where it lives:** `seedableLoop` exported from **`src/lib/match.js`**
(loop-identity is that file's mandate; it already imports theory.js
read-only; L-51 is adding adjacent exports there and L-60 runs after C-50, so
no lock overlap). For step 3 it needs `canonicalize`: **preferred — additive
`export` keyword on theory.js's `canonicalize`** (one-word diff; shared-file
lock, flag to Maestro at L-60 promotion; smoke's `loop-fixtures.mjs` already
byte-checks a replica of this function, so a second in-app replica would
triple the drift surface). Fallback if Maestro won't open theory.js: replica
in match.js with a drift comment + smoke guard, the loop-fixtures precedent.
Display note: the banner shows the seeded loop in this canonical rotation —
**identical to how any live-detected loop displays today**; the JamGuide rail
re-rotates to canonical KB order via `match.rotation` regardless, so the
learning surface always reads in textbook order (ii first in a iiVI).
### 3.3 Matching + round-trip — constructional after fix (a)
#### 3.3.1 The bug fix (a) exists for (Critic gate, real matcher run)
`buildLoopIndex` (match.js:126-141) indexes each progression's **raw,
uncollapsed** `degrees` — but the seeded loop (and the *live* commit stream,
which dedupes back-to-back chords) is the **collapsed** form, a different
sequence length whenever a progression repeats a chord across adjacent slots
or across the wrap. The gate ran the real matcher: **10/56 progressions
return NO MATCH for their own collapsed form** — `jazz-blues`, `blues-12bar`,
`blues-quickchange`, `blues-8bar`, `blues-minor`, `bossa-blue`,
`funk-one-chord`, `country-folk-axis`, `gospel-iv-passing-dim`,
`gospel-tonicized-amen` — and `country-145` is worse: its raw 8-shape matches
a *different* progression. Rolling blues would produce a populated banner and
an **empty JamGuide**. This is also a **pre-existing live-detection bug** the
roulette work surfaces: a band playing a real 12-bar blues today commits the
collapsed stream and gets an empty JamGuide — fix (a) repairs both at once.
#### 3.3.2 Fix (a) — collapsed-form indexing (Maestro-directed, mandatory)
`buildLoopIndex` **additionally** indexes each progression's collapsed form:
- **Collapse rule (key-free):** dedupe adjacent stations whose
`(degree, suffix)` pairs are equal, where
`suffix = CHORD_TYPES[quality]?.suffix ?? ''` (compare *suffixes*, not raw
quality tokens — two out-of-vocab qualities both fall back to `''` and
produce equal names, so a token comparison would under-collapse); then
**wrap-dedupe**: if the last pair equals the first, drop the last (one
check suffices post-collapse — only the boundary pair can merge).
- **What's indexed:** `canonicalDegrees(collapsedDegrees)` → an entry whose
`progression` is the **collapsed projection** of the authored one:
`{ ...progression, degrees, qualities, rn (first-of-run), bars (summed per
run), sourceIndex }` where `sourceIndex[i]` = the first raw station index
of collapsed station `i`. Same `id`/`name`/`level`/`mode`/`songs`/`tip`.
- **Only when it differs:** entries are added only where the collapsed shape
≠ the raw shape — **45/56 index once, 11 twice**. The full census (gate,
raw → collapsed): `jazz-blues` 12→10, `blues-12bar` 12→7,
`blues-quickchange` 12→9, `blues-8bar` 8→7, `blues-minor` 12→5,
`bossa-blue` 16→10, `funk-one-chord` 4→2, `country-145` 8→4,
`country-folk-axis` 8→7, `gospel-iv-passing-dim` 4→3,
`gospel-tonicized-amen` 5→4.
- **The true compatibility invariant (stated exactly):** collapsed entries
are **appended after all raw entries**, so `matchLoopToProgression`'s
strict-`>` disambiguation keeps every previously-matching input's winner
**on ties** — but append order never engages on a strict score win, and
one real case exists: for input shape `[0,5,0,7]` with
`maj/maj/maj/dom7` qualities (e.g. `[C, F, C, G7]`), `country-145`'s
collapsed form scores 4×1004 and **strictly beats** the incumbent
`country-bluegrass-cycle` (3×1004 — its quality set lacks `dom7`).
Gate-verified registry-wide (raw + collapsed × 3 keys): this is the
**only** winner change, and it is an **improvement** — the progression
actually being played now self-attributes (pure-triad `[C,F,C,G]` input
still ties and keeps `bluegrass-cycle`). So: **behaviour-preserving except
where a collapsed entry strictly dominates the disambiguation score,
enumerated: `country-145`, desired direction.** Previously-`NO_MATCH`
collapsed streams now match; that is the point.
- **Rotation:** for a collapsed-form hit, `rotationToCanonicalOrder` runs
against the *collapsed* degrees — equal lengths by construction. (Today's
length-mismatch guard, match.js:208, silently returns 0, which is exactly
what would break the playhead if the raw progression were returned
instead.)
Downstream, JamGuide renders the projection's stations naturally — a 12-bar
renders **7 stations, one per distinct change** (the right glance-rail
answer: duplicate consecutive bars add no voicing information; the strip's
loop chips carry position). The one alignment consumers need: **every
authored-play lookup must remap through `sourceIndex`** — otherwise a
collapsed match reads the first N raw play entries against the wrong
stations. There are **four** raw-indexed lookups, not two:
- **guitar** shape path, JamGuide.jsx:280, and **piano** recipe path, :288 —
both inside the `stationVoicings` memo: `play.chords[prog.sourceIndex?.[i]
?? i]`;
- **bass**, inside `BassGuideRows`: `play?.chords?.[i]?.pattern` (:530) and
`…?.note` (:533). Mechanism chosen: the `stationVoicings` memo attaches a
per-station **`sourceIndex` field** (`stations[i].sourceIndex =
prog.sourceIndex?.[i] ?? i`), and the two bass lines read
`play?.chords?.[st.sourceIndex ?? i]` — BassGuideRows already receives the
stations, so **no new prop**; the heard-live path's synthetic station has
no `sourceIndex` and the `?? i` fallback keeps it exact.
Blues ships guitar, piano *and* bass cells, and its bass pack covers **four
collapse-affected progressions** (`blues-12bar`/`quickchange`/`8bar`/
`minor`), two of them pool members (`blues-12bar` 7, `blues-minor` 5) — so
the bass remap is load-bearing for the roulette itself, not just for live
detection. Four bounded lines + the one field attachment; JamGuide.jsx joins
L-60's lock (§5).
#### 3.3.3 Key-independence proof (why the index can be built key-free)
Realized names are `Nᵢ = NOTES[(k + dᵢ) mod 12] + suffix(qᵢ)` for key root
`k`. Adjacent names are equal ⇔ their roots are equal AND their suffixes are
equal. Roots: `(k + dᵢ) ≡ (k + dⱼ) (mod 12) ⇔ dᵢ ≡ dⱼ (mod 12)``k`
cancels, and KB degrees live in 011, so this is plain `dᵢ = dⱼ`. Suffixes:
the 14 `CHORD_TYPES` suffixes are pairwise distinct (verified by inspection,
theory.js:41-55), so equal suffixes ⇔ the same suffix class — identical
quality for in-vocab tokens, the shared `''` fallback for out-of-vocab ones
(hence §3.3.2 compares suffixes). Therefore **name-collapse ≡
(degree, suffix)-pair collapse in every key**: `buildLoopIndex` computes the
collapsed shape once with no key in hand, and `seedableLoop`'s per-key name
collapse always produces that same shape. The same argument makes the §2.2
**round-trip invariant key-independent**: the detector consumes only the name
stream's *equality structure*, which is key-invariant; the lexicographic
rotation choice may differ per key, but seed and detector canonicalize
identically over identical names, so agreement of the two outputs is
preserved — one sweep in C covers all 12 keys.
#### 3.3.4 What is constructional vs what stays empirical
- **Matching is constructional post-fix-(a):** every rolled loop *is* some
progression's collapsed canonical shape, and fix (a) indexes exactly those
`matchLoopToProgression` cannot miss. (It may attribute to a same-shape
sibling — the §4 quirk, now including within-style cases like
`country-145`-collapsed ≡ `country-bluegrass-cycle`.)
- **Detector round-trip stays empirical** — hence §2.2's precomputed
registry-wide invariant (steady-state window, all partial-cycle offsets)
as the pool gate: today 4/56 fail — 3 over-length + `blues-8bar`'s
1-of-7-offsets self-competition; expected pool **52/56**, pinned by smoke.
Worked example of a passer: rolled `jazz-251-major` in A → seeded
`[Bm7, E7, Amaj7]` (canonical rotation) → band plays it → detection
commits the same sharp names from the same `CHORD_TYPES` suffixes → after
2 cycles (6 commits, clearing the history ≥ 6 gate) the detector returns
the identical canonical form at every subsequent commit, whatever the
phase → agreement branch fires. ✓
#### 3.3.5 Honest limit — qualities detection can't name
`MATCH_CHORD_TYPES` (theory.js:59-61) is a *subset* — KB qualities `dim7` and
`min6` (7 progression slots across the KB, counted) can never be committed by
detection under those exact names (it will hear `dim` / `m7`-ish). For such
rolls the seed displays the authored chord, and once the band plays,
detection consistently returns the *as-heard* loop → the `REPLACE_VOTES`
branch swaps in reality after 3 commits. That is the machine working as
designed — the card yields to what's actually played, and the re-match still
lands on the same KB progression (degree shape unchanged, quality is only a
tie-breaker). Same story if the band plays triads where the KB says sevenths.
Not a bug; documented behaviour.
### 3.4 The L-31 commit-layer interplay — branch by branch
The effect (App.jsx:181-213) runs once per chord commit (`[chordHistory]`
deps — seeding itself triggers exactly one run via `newSong`'s
`setChordHistory([])`, landing in the null branch at miss 1). With a seeded
vote `{committedKey: S, candidateKey: null, candidateCount: 0, seeded: true}`:
| Branch | Seeded behaviour | Verdict |
|---|---|---|
| **Agreement** (`vote.committedKey === key`) | Refreshes the loop, drops rivals — **L-60 adds:** `vote.seeded = false` + `setSeedInfo(null)`. The seed is now a normal committed loop; every subsequent rule applies verbatim | works, 2-line addition |
| **Rival counting** (`candidateKey` bookkeeping) | A transient sub-cycle detection during ramp-up (real: a 7-name collapsed 12-bar contains `[I,IV]` twice before the full form recurs) starts a candidate; `committedKey` survives the rebuild — **but the rebuild literal at line 207 drops `seeded`** | 🚩 **flag 3 below** |
| **Replacement** (`candidateCount ≥ REPLACE_VOTES=3`) | A genuinely different, consistently-detected loop replaces the seed; new vote is detection-owned (no `seeded`) — **L-60 adds** `setSeedInfo(null)` here | correct as-is: rolled cards must yield to a real band playing something else |
| **Null branch / miss counter** (`NULL_CLEAR=6`) | **Kills EVERY seed during ramp-up — no length survives.** L-31's "fills never null" reasoning assumed the loop is *in the history window* — a seeded loop isn't yet. Exact timeline: the seed's own effect run (via `newSong`'s history reset) is **miss 1**; commits 15 take the counter to 6 → **the card is wiped at commit 5**. But the earliest *any* detection can land is **commit 6**`detectRepeatingProgression` hard-gates raw history `< 6` (theory.js:609), so even a 2-name loop cannot confirm before then, and a loop of length *len* needs ~2·len commits besides. **Unguarded, every seed dies exactly one commit before the earliest possible confirmation** — the guard is mandatory for every pool member, not a long-loop nicety | 🚩 **flag 1 — the critical fix** |
**Flags for L-60 (each a 1-line change inside the effect — the one licensed
edit in that block):**
1. **Null-clear guard:** `if (progressionMissRef.current >= NULL_CLEAR &&
!progressionVoteRef.current?.seeded) { …clear… }`. Semantics: *a seeded
card is an instruction, not an observation — it stays until confirmed
(then normal rules resume), replaced by a consistently-detected different
loop, re-rolled, or New Song.* A band that noodles structurelessly under a
seeded card keeps the card — intended: it's what they were asked to play.
2. **Rotation equality is constructional** (§3.2/§3.3) — no branch change,
but if `seedableLoop` skipped canonicalization the agreement branch would
be unreachable and the seed would churn-replace with itself (rotated) at
commit 3. L-60's smoke-visible invariant is §2.2's registry-wide sweep,
**protocol verbatim:** *for each of the 56 progressions, fill the
32-commit window with repetitions of the seeded canonical form (steady
state) and truncate at every partial-cycle offset (0…len1 commits past a
cycle boundary); the progression passes only if
`detectRepeatingProgression` returns exactly the seeded canonical form at
ALL offsets.* Expected: 52 passers pinned; the 4 named failures
(`jazz-blues`, `blues-quickchange`, `bossa-blue`, `blues-8bar`) asserted
as excluded from the pool. (A naive 2-clean-cycles feed is wrong in both
directions — §2.2.)
3. **Preserve `seeded` across candidate rebuilds:** line 207 becomes
`{ committedKey, candidateKey: key, candidateCount: 1,
seeded: vote?.seeded ?? false }` — otherwise one transient ghost
sub-cycle strips the flag and flag 1's guard dies with it, resurrecting
the ramp-up kill through the side door.
Nothing else in the effect treats a seed differently — `COMMIT_VOTES` never
applies (a committed key exists), and `progressionMissRef.current = 0` on any
detection keeps the counter honest once structure appears.
### 3.5 The provenance flag — machine truth vs display echo
Two readers need "seeded, unconfirmed": the effect (guard, flag 1) and the
banner/button (indicator, §1.3). The effect reads `vote.seeded` — its own ref,
already in hand, mutation-safe. The **display** cannot read a ref reactively,
so App gains one small UI-state:
`const [seedInfo, setSeedInfo] = useState(null)`
`{ styleLabel, name, bars } | null`, passed to ProgressionBanner as a
presentational prop (and read by the roulette button for its active state +
re-roll row). This is **provenance metadata that exists nowhere else** (style
label, progression name, bar count) — not a duplicate of
`detectedProgression`. Invariant, enforced at every transition: `seedInfo !==
null ⇔ progressionVoteRef.current?.seeded === true`. Sync points: set
together in `rollJam`; cleared together in the agreement branch, the
replacement branch, and `newSong` (one added line — `setSeedInfo(null)`).
### 3.6 New Song & mid-session rolls
`newSong()` (App.jsx:216-241) already clears the whole seed surface:
`progressionVoteRef.current = null`, `progressionMissRef.current = 0`,
`setDetectedProgression(null)`, `setLockedKey(null)`,
`setChordHistory([])` — verified line by line; L-60 adds only
`setSeedInfo(null)`. **The seed clears naturally.**
**Mid-session rule: roulette = New Song + seed** (`rollJam` step 1). Without
it, a 32-commit history still containing the *old* loop keeps re-detecting it
and would replace the fresh seed within 3 commits even after the band
switches — the stale window poisons the handoff. `newSong()` is the
already-tested full reset (history, votes, key, BPM); seeding onto that clean
slate makes ramp-up §3.4's only story. The banner history emptying is honest
("new song" is literally what the button did), and the loop-station audio is
untouched (`newSong` never touched it).
---
## 4. What fills in — every consumer, verified
The seed sets `lockedKey` (→ `effectiveKey`) + `detectedProgression` (+ the
vote ref). Consumers and their honest pre-first-note state (`chordHistory`
empty, `currentChord` undefined):
| Surface | Consumes | Seeded behaviour |
|---|---|---|
| Slim loop strip — key chip | `keyInfo` (= effectiveKey) | Rolled key + mode render immediately |
| Slim loop strip — loop chips | `detectedProgression`, `findLoopPosition(chordHistory, loop)` | All chips render (chord + rn via the rolled key). `findLoopPosition` **returns 1 on empty history** (match.js:75 guard) → **no chip highlighted** — correct: nobody is anywhere yet. 🎲 indicator per §1.3 |
| Strip — history row | `chordHistory` | "Start listening…" — honest |
| JamGuide match | `matchLoopToProgression(loop, kbIndex)` | **Matched by construction — after §3.3.2's fix (a)** (mandatory L-60 scope): the seeded loop is the progression's collapsed canonical shape, which fix (a) indexes. *Without* the fix, 10/56 rolls (all of blues among them) would show a populated banner and an **empty JamGuide** — and the same fix repairs today's live-detection miss for real 12-bar streams. Header shows the progression name + "in {key}" |
| Voicing rail (GlanceRail / BassGuideRows) | `stationVoicings` (match + keyRoot), `activeIndex = canonicalPos` | Every station's shapes/voicings render in canonical KB order — for collapse-affected matches, the **collapsed projection's** stations (a 12-bar renders 7, one per distinct change) with plays remapped via `sourceIndex` (§3.3.2). `canonicalPos` guard (JamGuide.jsx:220-225) → **1** → **no "now" row** — the rail shows the whole map unhighlighted |
| Licks strip | `activeStyle` (= match.style), `contextStation` | Populates; `contextStation` **falls back to station 0** when canonicalPos is 1 (JamGuide.jsx:341-344, existing comment says exactly this) — licks aim at the progression's first chord until the playhead exists |
| Related progressions (L-51) | `{ loop, keyInfo, onChordClick }` | Populates for free — it computes its own match from the loop |
| Instrument view | `keyInfo`, `currentChord` | Scale + pentatonic tiers light in the rolled key; **no chord-tone tier until the first commit** (currentChord undefined) — honest |
| ChordDetailModal | tap any chip | Works — chips pass real chord names |
| Chord detection itself | `effectiveKeyRef` | **Enabled immediately** by the seeded key (§3.1 synergy) |
**The pre-first-note playhead, stated plainly:** there is none — no strip chip
glows, no rail row is "now", and that is the design: a playhead claims
knowledge of where the band is, and the app doesn't have it yet. It lights on
the **first committed chord whose name appears in the loop** (`findLoopPosition`
walks back from the last commit; a first chord outside the loop keeps it
unlit). The 🎲 chip carries the "we're starting" affordance until then.
**Style-attribution quirk (documented, accepted):** same-shape progressions
exist across styles (`rock-axis` / `reggae-nwnc` / `pop-axis` all
`[0,7,9,5]`), and fix (a) adds within-style aliases
(`country-145`-collapsed ≡ `country-bluegrass-cycle`).
`matchLoopToProgression` disambiguates by quality overlap then length; ties
fall to entry order (raw before collapsed, §3.3.2 — incumbents keep winning
on ties), and the one strict-win exception is `country-145`'s collapsed form
over `bluegrass-cycle` for dom7-V input — the desired direction (§3.3.2's
true invariant). So rolling *pop* → Axis may render the rail/licks
attributed to **rock**. The chords, key, rn, and voicings are identical;
only the style label and lick flavour differ. **Re-judged against Maestro's belt-and-braces
offer: with fix (a) mandatory, matching is constructional and a seeded
`styleHint` would correct only the label/lick flavour — cosmetic, not
load-bearing. Declined for v1** (it would plumb a new prop through JamGuide
for no structural gain); noted for Maestro as a user-pulled follow-up if
anyone notices.
---
## 5. L-60 scope — exact files, bounded commits
**The audio-contract boundary (grep-gated, restated):** the seed touches
display state (`lockedKey`, `detectedProgression`, `seedInfo`,
`chordHistory` via `newSong`) + the progression refs
(`progressionVoteRef`, `progressionMissRef`) + UI refs
(`rouletteMemoryRef`, `effectiveKeyRef` per the quickLock precedent) —
**never** `handleNote`/`handleChroma`/`handleOnset`/`handleWaveform`, their
ref-sync effects, or any AudioCapture prop.
**Files:**
1. `src/lib/theory.js`**additive only:** `export` keyword on
`canonicalize` (shared file — flag lock to Maestro at promotion;
Professor+Critic co-review per PROTOCOL §3; fallback per §3.2).
2. `src/lib/match.js` — the sprint's real engineering weight, all additive:
- **`seedableLoop(progression, keyRootPc) → string[] | null`** (realize →
collapse+wrap-dedupe → canonicalize; null for collapsed length < 2);
- **fix (a)** per §3.3.2: `buildLoopIndex` collapsed-form entries
(collapsed projection with `sourceIndex`, appended after raw entries)
+ `matchLoopToProgression` collapsed-hit rotation against collapsed
degrees. Behaviour-preserving except the one enumerated strict win
(§3.3.2 true invariant: `country-145`, desired direction);
previously-`NO_MATCH` collapsed streams now match — this also fixes
the pre-existing live 12-bar miss;
- the **round-trip pool sweep** helper (lazy module-level memo, §2.2).
After C-50, no lock overlap with L-51's exports.
3. `src/App.jsx``rollJam(styleId)` + `seedInfo` state +
`rouletteMemoryRef`; the roulette button + popover menu in the controls
bar; the three 1-line commit-layer edits (§3.4 flags 1 & 3 + the two
`setSeedInfo(null)` clears); one line in `newSong`.
4. `src/components/ProgressionBanner.jsx` — presentational `seedInfo` prop:
🎲 glyph + amber provenance chip on the loop row (§1.3).
5. `src/components/JamGuide.jsx` — **four bounded lines + one field**
(§3.3.2): guitar-shape and piano-recipe lookups remap through
`prog.sourceIndex?.[i] ?? i` (JamGuide.jsx:280, :288); `stationVoicings`
attaches `stations[i].sourceIndex`; BassGuideRows' two raw-indexed
lookups (`pattern` :530, `note` :533) read
`play?.chords?.[st.sourceIndex ?? i]` — no new prop, heard-live falls
back via `?? i`. Re-lock at promotion — JamGuide is one-screen-locked
until C-50, which L-60 already depends on.
**Suggested commits (green at each):**
1. theory.js export + match.js (`seedableLoop` + fix (a)) + the JamGuide
`sourceIndex` remaps (all four paths incl. bass) + the smoke sweep: the
§2.2 round-trip invariant over **all 56** progressions under the
steady-state/all-offsets protocol (§3.4 flag 2 verbatim; expected 52
passers pinned; the 4 named failures asserted excluded) **plus** a
live-stream fixture proving a clean 12-bar history now matches (the
pre-existing bug, pinned fixed).
2. App.jsx commit-layer guard lines + `rollJam` + state/refs (mechanism live,
invokable from a temporary plain button if needed).
3. The controls-bar button + menu + banner indicator (the visible feature).
**Out of L-60 scope:** GlanceRail/VoicingBrowser (untouched — they render
whatever stations JamGuide hands them), JamGuide beyond the four remap lines
+ field, KB content, theory beyond the one export, audio, and the
`styleHint` disambiguation (declined, §4).
---
## 6. Rejected alternatives
**Rejected A — fake `chordHistory` injection** (seed by pushing 2 synthetic
cycles into history so the detector "discovers" the roll naturally). Seductive
— zero commit-layer changes — and dishonest at every surface: the banner
history strip shows eight chords **nobody played**; `findLoopPosition`
immediately lights a playhead asserting the band is mid-loop before a note
sounds; the L-31 cadence reasoning (thresholds are *per real chord commit*)
silently breaks; and the first real commits interleave with the fake tail,
producing corrupted-rep flapping (the exact pathology C-30/L-31 spent a sprint
taming). The seed must write conclusions, not forge evidence.
**Rejected B — a separate `seededProgression` state rendered when
`detectedProgression` is null.** Duplicates the loop's identity across two
states with a priority rule; every consumer (strip, JamGuide, RelatedProgressions,
future ones) must learn the fallback or silently miss the seed; and the
detection handoff becomes a hard visual swap between two objects instead of
the vote ref's smooth confirm/replace. The standing principle exists for
exactly this: one loop, one state, one machine.
**Rejected C — display-only overlay ("ghost card") that never enters the
state machine**, cleared on first detection. Honest-looking, but the screen's
surfaces don't populate from a ghost: the rail, licks, and related
progressions all key off `detectedProgression` — an overlay would either
leave them empty (failing "so that everyone can see the chords with different
voicings") or need Rejected B's plumbing anyway. Also loses the §3.1 synergy
(no `lockedKey` → chord detection stays gated on key detection).
**Rejected D — neutralize the ramp-up with a miss-counter credit**
(`progressionMissRef.current = -(2·len + 4)` at seed time) instead of the
`seeded` flag. One line, no flag — but the credit is a magic number that burns
in real time: a band that chats for eight commits' worth of noodling before
starting spends it on nothing and the card still dies mid-ramp-up; and it
leaves no way for the agreement branch to know confirmation happened (the
indicator can't flip). The flag has clean semantics; the credit has arithmetic
luck.
---
## 7. Flags for Maestro
- **theory.js shared-file lock** (additive `export` on `canonicalize`) — L-60
promotion must note it; Professor co-review per PROTOCOL §3.
- **L-60 lock list** per §5 (App.jsx + ProgressionBanner.jsx + match.js +
theory.js + JamGuide.jsx, four remap lines + one station field) —
supersedes the ledger row's "App.jsx (+ per D-62)".
- **Fix (a) repairs a pre-existing LIVE bug** (§3.3.1: real 12-bar/8-bar
streams — 10 progressions match nothing in JamGuide today, and
`country-145` misattributes; 11 collapse-affected total, §3.3.2 census).
Worth a line in the PR body / Herald's changelog: users get it even if
they never touch the roulette.
- **`styleHint` disambiguation** — re-judged and **declined for v1** (§4:
cosmetic post-fix-(a)); user-pulled follow-up only.
- **Smoke round-trip sweep** (§5 commit 1, all 56 progressions + the live
12-bar fixture) — if Critic prefers it C-owned, it slots into C-61's sweep
instead.
- No new tokens, no new colours (amber + accent are established), no
dependencies, no KB/audio changes anywhere in this design.
+193
View File
@@ -0,0 +1,193 @@
# Knowledge Center — design concept (task D-20)
> **Thesis:** JamBuddy's knowledge should live in **one bottom dock with four sections**, grown out of the existing Jam Guide dock — not three (actually five) competing collapsible panels. The live Roadmap stays the flagship landing section; Explore, Voicings, and Licks & Techniques become sibling sections inside the same shell. One shared level filter (foundation/intermediate), one visual language (the Roadmap's, per `jam-guide-concept-c.md`), zero new top-level chrome.
**Decision authority:** per the sprint header (user away 12 h, no user gate), Muse picks the strongest layout and records rationale + rejected alternatives below (§6). Implementation is task **L-22**; this doc is its blueprint.
---
## 0. Honest audit — what actually exists today
Read directly from `src/App.jsx` and the components before designing. The "three disconnected surfaces" from the user directive are real, but the on-disk truth is messier:
| Surface | File | Mounted in App.jsx? | Content |
|---|---|---|---|
| Jam Guide (Roadmap) | `src/components/JamGuide.jsx` | **Yes** — last, bottom dock | Live loop → KB match → RoadmapTrack + voicing strip; instrument + style tabs |
| Explore panel | `src/components/ExplorePanel.jsx` | **No — orphaned** (verified: no import anywhere in `src/`) | Chord picker (root × quality), guitar voicing grid, piano techniques, famous progressions |
| Education panel | `src/components/EducationPanel.jsx` | **No — orphaned** (same verification) | Session snapshot, similar progressions, "play differently" substitutions, progression variations |
| Current Jam panel | `src/components/CurrentJamPanel.jsx` | **Yes** — mid-page collapsible | Voicings / scales / style options / **similar progressions** — heavy overlap with EducationPanel |
| Chord detail modal | `src/components/ChordDetailModal.jsx` | **Yes** — overlay | 6 tabs: Guitar, Piano, Theory, Learn (playbook + ASCII licks), Progressions, Explore |
So the fragmentation the user feels is: JamGuide (bottom) + CurrentJamPanel (middle) + ChordDetailModal (overlay), with two *dead* panels duplicating slices of both. The Knowledge Center consolidates the browse/learn material into the bottom dock, reuses the orphans as parts, and leaves CurrentJamPanel and the modal shell untouched this sprint (flagged for follow-up, §10).
---
## 1. Chosen structure — one dock, four sections
The existing JamGuide dock (collapsed header → ~70vh body) becomes the **Knowledge Center**. Its body gains a section nav; everything else about the dock chrome (collapsed summary bar, live match label, 70vh expand) is preserved.
```
┌─ KNOWLEDGE CENTER ── iiVI in C major · in C major ──────────────────── ▼ ─┐ (collapsed bar,
└──────────────────────────────────────────────────────────────────────────────┘ unchanged behaviour)
┌─ KNOWLEDGE CENTER ── iiVI in C major ──────────────────────────────── ▲ ─┐
│ ┌───────────────┬─────────┬──────────┬────────────────────┐ │
│ │ ▶ Jam Guide ● │ Explore │ Voicings │ Licks & Techniques │ ← section nav │
│ └───────────────┴─────────┴──────────┴────────────────────┘ (● = live) │
│ │
│ [ Jam Guide (live) — the existing Roadmap body, byte-for-byte: │
│ instrument tabs · style tabs · RoadmapTrack · voicing strip ] │
│ │
│ [ Explore — KB progression browser + famous progressions: │
│ style chips · (Foundation)(Intermediate) level chips · │
│ progression cards with level badge, chords-in-key, tip, songs ] │
│ │
│ [ Voicings — chord picker (root × quality, follows the live chord) → │
│ VoicingBrowser: guitar shapes + piano voicings, each with ▶ play ] │
│ │
│ [ Licks & Techniques — style chips · level chips · │
│ LickCard grid (tab SVG + technique glyphs) · glyph legend ] │
└──────────────────────────────────────────────────────────────────────────────┘
```
**Section semantics:**
1. **Jam Guide (live)** — default landing section; answers *"what do I play over this loop right now?"* The current Roadmap body moves in unchanged (RoadmapTrack, playhead, station voicings strip, piano tab from L-11). The `●` live dot on the nav pill pulses only when a loop is matched, so even from another section you see the guide is hot.
2. **Explore** — answers *"what could we play?"* A **KB progression browser** (new, simple: style chips from the `kb/index.js` registry → progression cards showing name, rn pattern, chords rendered in the current key, `tip`, level badge) plus the famous-progressions cards reused from ExplorePanel. Any chord chip → `ChordDetailModal` via `onChordClick`.
3. **Voicings** — answers *"how do I grip/voice this chord — and what does it sound like?"* ExplorePanel's root × quality picker (defaulting to `currentChord` when live) feeding **VoicingBrowser** (D-21): guitar alternatives via `ChordDiagram`, piano alternatives via `MiniPiano voicing`, each variant with a ▶ button through `src/lib/chordAudio.js`.
4. **Licks & Techniques** — answers *"give me a phrase."* Style chips → **LickCard** (D-22) grid of P-21 licks, level chips shared with Explore, technique-glyph legend once per grid (not per card). Styles without authored licks show an honest empty state ("No licks authored for Pop yet — Blues, Jazz and Funk have them").
**Why the dock and not a new page:** the Knowledge Center must be reachable *mid-jam* without losing the detection UI (key chip, fretboard, banner). The bottom dock already established that contract with the Roadmap; sections extend it. Concept-C's visual language (station cards, accent-on-active, dimmed-by-age tiers, amber for secondary/held tones) carries through all four sections.
---
## 2. IA map — reused / new / retired
| Piece | Fate | Where it lands |
|---|---|---|
| `JamGuide.jsx` Roadmap body (RoadmapTrack, voicing strip, instrument/style tabs, L-11 piano tab) | **Reused unchanged** | Section 1 content; JamGuide.jsx becomes the Knowledge Center shell + section 1 |
| `ExplorePanel.jsx` chord picker + quick-pick chips | **Reused** (refactored to named exports) | Section 3 toolbar |
| `ExplorePanel.jsx` `GuitarGrid` / `PianoGrid` | **Reused as interim**, then superseded by VoicingBrowser | Section 3 body until D-21 merges; kept as the no-audio fallback |
| `ExplorePanel.jsx` `ProgressionCards` (famous progressions) | **Reused** | Section 2, below the KB progression browser |
| KB progression browser (style → progressions with level badges) | **New** (small, data straight from `kb/index.js` which JamGuide already imports) | Section 2 hero |
| `VoicingBrowser.jsx` (D-21) | **New** | Section 3 + `ChordDetailModal` + station-enlarge (see §3) |
| `LickCard.jsx` (D-22) | **New** | Section 4 grid |
| Level filter chips | **New** (one shared component + one shared state in the shell) | Sections 2 and 4 toolbars (§4) |
| `EducationPanel.jsx` | **Retired** — stays unmounted; not edited (not in the L-22 lock). Its unique content (substitutions, variations) already lives in CurrentJamPanel + ChordDetailModal Theory tab. File deletion is a future cleanup task for Maestro to file | — |
| `CurrentJamPanel.jsx` | **Untouched this sprint** — overlap with section 2 acknowledged; folding it in is a follow-up (§10) | mid-page, as today |
| `ChordDetailModal.jsx` | **Shell untouched**; L-21 swaps only its Guitar/Piano tab grids for VoicingBrowser | overlay, as today |
Naming: the collapsed bar reads **"Knowledge Center — 〈live match label〉"**; the flagship keeps its name as section 1, "Jam Guide". No behaviour of the collapsed bar changes.
---
## 3. Where VoicingBrowser and LickCard mount
**VoicingBrowser** (`src/components/VoicingBrowser.jsx`, D-21) — three mount points, one component, prop-driven `{rootPc, quality}`:
1. **Knowledge Center → Voicings section** (L-22, via the ExplorePanel.jsx refactor) — the browse-first entry: pick any chord, audition every voicing.
2. **ChordDetailModal → Guitar/Piano tabs** (L-21) — replaces/extends the static `GuitarGrid`/`PianoGrid` so the modal's voicings become playable.
3. **Jam Guide station-enlarge** (L-21) — tapping a Roadmap station's thumbnail currently enlarges one `ChordDiagram`; it becomes the VoicingBrowser for that station's `{rootPc, quality}`, so mid-jam you can audition alternatives for the chord that's coming.
Data sources: guitar shapes from `src/lib/voicings.js` `GUITAR_SHAPES` (already the `ChordDiagram`-compatible `rootStr`/`offsets` format); piano voicings computed by `src/lib/piano.js` `pianoVoicing` (root / shell / rootlessA / rootlessB) rendered by `MiniPiano voicing`. Audio via `src/lib/chordAudio.js` (L-20). **Mic-feedback caveat surfaced in UI:** a one-line `text-gray-500` hint near the ▶ buttons — "played through your speakers — the mic may hear it" — mirroring the L-20 documentation.
**LickCard** (`src/components/LickCard.jsx`, D-22) — one mount point this sprint:
1. **Knowledge Center → Licks & Techniques section** (L-22): responsive grid, one card per P-21 lick, filtered by style chip + level chips. Card shows name, level badge, `chordContext` chip ("over the V7"), the tab SVG with technique glyphs (h, p, slide ⌒, bend ↑ … per the C-20 vocab), and the technique names it uses. The glyph legend renders once below the grid.
*Not* mounted in ChordDetailModal's Learn tab this sprint — that tab's `CHORD_PLAYBOOK` ASCII licks are a different corpus (`education.js`); converging them is future work, noted for Maestro (§10).
---
## 4. Level filter — placement and default
**Form:** two toggle chips, `Foundation` and `Intermediate`, rendered side by side in a section's toolbar. Both **on by default** (= show everything; badges do the signalling). Tapping one off narrows the list; both can't be off (tapping the last active chip is a no-op with a brief tooltip). This is the "easiest possible surface" per the directive: no new panel, no dropdown, one tap to see only intermediate material.
**State:** one `levels` state in the Knowledge Center shell, shared by both consuming sections — filter once, it holds as you move between Explore and Licks.
**Placement (exactly two spots):**
- **Explore section toolbar**, next to the style chips — filters the KB progression browser (every KB progression carries `level` after P-20).
- **Licks & Techniques toolbar** — filters LickCards (`lick.level` from the C-20 schema).
**Chip styling:** inactive = `bg-surface border-border text-gray-400`; active = `bg-accent/20 border-accent text-accent font-semibold` (the established active-tab treatment). Level *badges* on cards: foundation = `border-border text-gray-400`; intermediate = `border-amber/40 text-amber` (amber is already a token — no new colour needed).
**Honesty:** `FAMOUS_PROGRESSIONS` in `src/lib/education.js` carries **no** `level` field and `education.js` is in no task's lock — the famous-progressions cards in Explore show no badge and are **not affected by the filter** (they sit under their own "Famous progressions" subheading so the filter's scope reads clearly). Tagging that corpus is an open question for Maestro (§10).
---
## 5. Narrow-viewport plan
Target checks at implementation: **1280×800** (default Electron window), **~1024×768**, and **≤420px** width (half-snapped window).
- **Section nav:** horizontal chip row, `overflow-x-auto` + `shrink-0` pills (the pattern ChordDetailModal's tab bar and EducationPanel's nav already use) — never wraps into a tall block, never traps vertical scroll.
- **Dock body:** stays ~70vh with internal vertical scrolling; each section is a vertical stack on narrow.
- **Jam Guide section:** keeps its existing verified reflow (voicing strip wraps via `flex-wrap sm:flex-nowrap`, RoadmapTrack scrolls horizontally under the fixed playhead).
- **Explore:** progression cards are full-width stacked (they already are `flex-col`); chord chips inside cards wrap.
- **Voicings:** voicing-variant chips wrap; diagrams grid uses `repeat(auto-fill, minmax(140px, 1fr))` so thumbnails go 2-up at ~360px and never overflow; the enlarged diagram caps at container width (`max-w-full`, SVG scales via viewBox).
- **Licks:** grid `repeat(auto-fill, minmax(240px, 1fr))` → single column below ~520px; the LickCard SVG scales to card width (viewBox + `width:100%`), glyphs sized in SVG units so they scale with the tab.
- **Toolbars** (style chips + level chips): `flex-wrap` — level chips drop to a second row on narrow rather than shrinking below tap-target size (min 32px height).
---
## 6. Rationale + rejected alternatives (no user gate this sprint)
**Chosen: the four-section bottom dock grown from JamGuide.** Reasons:
1. **Minimum migration risk** — JamGuide already owns the dock chrome, the KB registry import, the live-match plumbing, and passed Critic's audio-contract gates repeatedly. Wrapping its body in a section nav is additive; the flagship Roadmap is never rebuilt.
2. **Mid-jam continuity** — knowledge is reachable while the detection UI stays on screen; the collapsed bar keeps broadcasting the live match even when closed.
3. **One home for the level filter** — shared state across Explore and Licks with zero duplication.
4. **App.jsx stays mount-only** — one additive prop (`onChordClick`, §7); no structural change near the audio callbacks.
**Rejected A — full-screen "Knowledge" mode/route** (top-level toggle Jam ⇄ Knowledge). More room per section, but it hides the detection UI while browsing (breaks the "look at it mid-jam" core promise), needs App.jsx restructuring far beyond mount-only, and adds a navigation concept the app doesn't have. Rejected on risk *and* UX grounds.
**Rejected B — keep three separate collapsible panels, restyled and cross-linked.** Cheapest to build, but it *is* the problem the user named: three headers competing in the scroll, three places for the level filter, no shared state, and the orphaned panels would be resurrected as-is (including EducationPanel's overlap with CurrentJamPanel). Rejected as fragmentation with a fresh coat of paint.
**Rejected C — right-side drawer.** Nice on ultrawide, but the Electron window is frequently narrow; a drawer either crushes the fretboard or overlays it (losing the glance-both-at-once value), and it duplicates the dock pattern the Roadmap already established. Rejected for viewport economics.
---
## 7. Migration order for L-22 (app green between every commit)
Precondition: **L-11** (piano in JamGuide) and ideally **L-21** hold locks on `JamGuide.jsx` — Maestro sequences L-22 after those merge. Order within L-22:
1. **Commit 1 — refactor `ExplorePanel.jsx` into parts.** Split into named exports: `ChordPickerToolbar`, `ExploreSection` (progression browser + famous progressions), `VoicingsSection` (picker + grids), `LevelChips`. Keep the default export as a thin composition of the parts. **Zero user-visible risk — the file is unmounted today.** Build + smoke green trivially.
2. **Commit 2 — Knowledge Center shell in `JamGuide.jsx` + App prop.** Add the section nav; move the existing Roadmap body (verbatim) into section 1; mount `ExploreSection` and `VoicingsSection` (with the interim static grids) from ExplorePanel.jsx; `App.jsx` gains exactly one additive prop on the existing JamGuide mount: `onChordClick={setSelectedChord}` (mount-only, nowhere near the audio callbacks/refs). App renders identically until the dock is opened; the Roadmap section is a code *move*, not a change.
3. **Commit 3 — level filter live.** `LevelChips` wired to the shared `levels` state; KB progression browser reads `progression.level` (P-20 must be merged); level badges on cards; licksless filter scope documented in the empty states.
4. **Commit 4 — Licks & Techniques section.** Mount the LickCard grid (needs D-22 component + P-21 data merged); style chips reuse the registry list section 1 already derives; shared level chips apply; empty state for lick-less styles.
5. **Commit 5 (in-sprint upgrade, may fold into L-21's landing) — Voicings section swaps static grids for `VoicingBrowser`** once D-21 merges: a one-line component swap inside `VoicingsSection`, with the static grids kept as the fallback when `chordAudio` is unavailable.
Every commit: `npm run build` + `node scripts/smoke.mjs` green; at no point does the app lose the Roadmap, the modal, or any mounted panel.
---
## 8. Tokens, contrast, keyboard
**Tokens only** — `bg-surface` #0f0f0f, `bg-panel` #1a1a1a, `border-border` #2a2a2a, `accent` #a855f7, `amber` #f59e0b (all already in `tailwind.config.js`). **No new colour is required** for the Knowledge Center; level badges reuse amber, active states reuse the accent tints already shipped in JamGuide.
**Measured contrast commitments** (computed, not assumed):
- `accent` #a855f7 on `panel` #1a1a1a**4.4:1** — passes AA for large/bold text and UI components, *borderline for small normal text*. Rule: small accent text sits on `bg-surface` cards (**≈4.8:1**, passes) or is ≥ semibold at ≥14px; body copy is never accent.
- `gray-400` #9ca3af on panel ≈ **6.9:1** — the floor for any *essential* label.
- `gray-500` #6b7280 on panel ≈ **3.6:1** — decoration/microcopy only, never load-bearing text (existing app convention, now explicit).
- `amber` #f59e0b on panel ≈ **8.1:1** — level badges and secondary-tone markers are comfortably AA.
**Keyboard:** every section pill, style chip, level chip, voicing variant, ▶ play button, and LickCard is a real `<button>` in DOM order with `focus-visible:ring-2 ring-accent` (the shipped pattern). Section nav uses `aria-pressed`/`aria-current`; level chips `aria-pressed`; the live dot on the Jam Guide pill is decorative (`aria-hidden`) with the liveness conveyed in the pill's `aria-label`. ▶ buttons get descriptive labels ("Play C maj7 — shell voicing"). The dock's expand/collapse button keeps `aria-expanded`.
---
## 9. What stays untouched (explicitly out of scope)
- **The audio/detection pipeline**`AudioCapture.jsx`, `handleNote`/`handleChroma`/`handleOnset`, all refs and `useCallback` contracts in `App.jsx`. The only App.jsx change in this whole plan is one additive prop on an existing mount (§7 commit 2). `chordAudio.js` is a separate, lazily-created context (L-20's contract) and never touches the detection contexts.
- **Detection UI** — key chip, `ProgressionBanner`, `ProgressionSuggestions`, main `Fretboard`/`Piano`/`BassFretboard`, the D-03 guide-tone cross-link.
- **Tuner, Loop Station, DebugView, DrumView** — not part of the Knowledge Center; their mounts and order in App.jsx are unchanged.
- **`CurrentJamPanel`** — remains mounted as-is despite overlapping Explore (§10).
- **`ChordDetailModal` shell** and its Theory/Learn/Progressions/Explore tabs — L-21 touches only the Guitar/Piano voicing grids.
- **Libraries**`theory.js`, `education.js`, `voicings.js`, `match.js`, `piano.js`: read-only from this design.
---
## 10. Open questions for Maestro
1. **`FAMOUS_PROGRESSIONS` level tags** — `education.js` is unlocked and untagged; famous-progression cards are exempt from the level filter (§4). File a small Professor task to tag it, or accept the split scope?
2. **CurrentJamPanel convergence** — its "Similar Progressions"/"Style Options" views largely duplicate Explore. Recommend a follow-up task (post-sprint) to fold its unique bits (per-chord open-voicing strips, scale diagrams) into the Knowledge Center and retire the panel — reduces the main scroll by one header.
3. **EducationPanel.jsx deletion** — confirmed orphaned; retire-in-place this sprint, file a cleanup deletion (Luthier, trivial) later so dead code doesn't confuse future agents.
4. **L-21/L-22 sequencing on `JamGuide.jsx`** — both edit it; this doc assumes L-11 → L-21 → L-22 (or L-22 commits 14 then the §7 commit-5 swap folded into L-21). Maestro to serialize the lock.
5. **Naming check with the user (async, non-blocking):** collapsed bar renamed "Knowledge Center — 〈match〉"; "Jam Guide" lives on as section 1. Cheap to revert if the user prefers the old bar title.
+589
View File
@@ -0,0 +1,589 @@
# One Screen — the jam dashboard (task D-50)
> **Thesis:** the page stops being a tall stack of full-width bands and becomes a
> **viewport-fitting jam dashboard**: a full-width *slim loop strip* (the banner
> minus its big now-playing chord), then LEFT (~744px) the compact instrument
> view, the licks strip, and a new loop-relative *Related progressions* card;
> RIGHT (~500px) the suggested-voicings rail — the design's ONE justified
> internal scroller (§4). The dashboard is a **self-contained unit designed to
> fit 100vh at 1280×900**; a **JAM VIEW toggle** in the controls bar (§1.1)
> locks the page to exactly that unit (and goes browser-fullscreen,
> best-effort) while playing. In normal mode everything that is learning or
> behind-the-scenes (LoopStation, Debug, Drum, Tuner, KnowledgeDock) stays
> below the dashboard on the ordinary page scroll; in jam view it is hidden.
>
> User directive (2026-07-11, verbatim): *"the chord view and the chord loop
> incl the instrument below is too big, it takes up too much space, i want you
> to reconsider the positioning as this main view doesnt really add value:
> seeing the big chord 'now playing' in big is also unnecessary as you already
> see that one in the chords (loop) part. the suggested progressions on the
> right are also almost useless. they are nice but we need to rethink them in
> the form of SUGGESTED VOICINGS and the progressions we add relating to the
> loop. i'd like to have the suggested voicings on the right side of the screen
> (the jam guide). … i wanna see the chords, the loop, the voicings, the
> progressions, the licks all on one screen, everything you need to follow the
> jam correctly"*
>
> Refinement (2026-07-11, verbatim): *"it can still have a scroll down, but the
> main concept needs to be in one screen: potentially we add a fullscreen
> button so we can just show that when we are playing a jam. so that it fits
> the entire screen, everything that is learning and behind the scenes etc you
> can keep below/scrollable but we need one main view for live jams where we
> see everything at once (relating to the jam and the voicings and the licks
> and the chords and the loop)"* — the 100vh fit is a **hard design
> constraint** for the dashboard, not an aspiration; the fullscreen button is
> in scope (L-50 commit 3, §6.1); internal wrap/scroll inside a panel is a
> last resort and every instance below is justified.
**Supersedes** `integrated-glance.md` §1's full-width-band placement (the user
tested it and asked for the right column). That doc's **verified geometry stays
the arithmetic source here**: guitar cell ~93px, piano cells 160/284px, worst
piano gallery ~1,178px of cells, licks thumb card ~165px (in a 220px strip
slot), cell line heights ~140px guitar / ~125130px piano. Standing principles
(user memory): scroll > click; nothing shown twice; ONE global instrument
selector; the playhead highlights, never hides.
**Decision authority:** per the sprint header (no user gate), Muse picks the
strongest option and records rejected alternatives (§9).
---
## 0. What exists today (read from the code)
App.jsx mount order: `ProgressionBanner` (~608) → instrument row (~617629:
`Fretboard`/`BassFretboard`/`Piano` at 70% + `ProgressionSuggestions` at 30%) →
`JamGuide` full-width band (~635: GlanceRail all-expanded rows + LicksStrip) →
`LoopStation` → Debug/Drum/Tuner collapsibles → `KnowledgeDock` last. The band
starts ≈570px down at 1280×900 — voicings never share the screen with the
instrument view, and the licks strip sits another rail-height below that. The
banner burns its right 30% on a text-6xl "Now Playing" chord that duplicates
both the enlarged last history chip and the highlighted loop chip. The
directive kills all of that.
---
## 1. The grid
Assumed usable content box at a 1280×900 window: **~1,256 × ~836px** (Electron
title bar ~32px eats into the 900; App's `p-3` eats 24px each axis — heights
below are estimates, cell geometry is verified).
```
┌──────────────────────────────────────────────────────────────┐ ─┐
│ header (~52) │ │
│ controls bar — instrument · key lock · ⛶ JAM VIEW (~52) │ │
│ SLIM LOOP STRIP — key · history · ♻ loop chips (~76) │ │ the
├───────────────────────────────────────┬──────────────────────┤ │ dashboard
│ LEFT ~744px (flex-1) │ RIGHT 500px, │ │ = 100vh
│ │ own scroll (§4) │ │ in jam
│ compact instrument view (~240) │ │ │ view
│ licks strip (~190) │ SUGGESTED VOICINGS │ │
│ related progressions (~200) │ rail — GlanceRail / │ │
│ │ BassGuideRows rows │ │
├───────────────────────────────────────┴──────────────────────┤ ─┘
│ LoopStation · Behind the Scenes · Rhythm · Tuner · Knowledge │ normal mode
│ (the learning / behind-the-scenes area — page scroll) │ only; hidden
└──────────────────────────────────────────────────────────────┘ in JAM VIEW
```
- The **slim strip stays full width** (not inside the left column): it is the
status line for the whole dashboard — the rail's playhead and the strip's
active loop chip are the same "now", and a full-width one-liner costs only
~76px. (Putting it inside the left column would buy the rail ~88px of
first-paint height; the rail is internally scrollable anyway, and a
~450px-content strip floating in a 744px column looks broken. Not worth it.)
- **Grid:** `flex gap-3 items-start` → left `flex-1 min-w-0`, right
`w-[500px] shrink-0`, active at `xl:` (≥1280); below that the columns stack
(§7). 500px is the top of the licensed 420520 range because piano cells
need it (§4): at 500 the row interior is ~456px, which fits a 284px
two-octave cell **plus** a 160px one-octave cell per line (by ~4px — D-51
hardens the margin, §4); at 420 every two-octave cell rides alone.
- **The rail is height-bounded: `xl:max-h-[calc(100vh-1.5rem)]
xl:overflow-y-auto` — and NOT sticky.** (`sticky top-3` here would be inert:
inside the flex row the rail is the tallest item, so its containing block
equals its own height and there is zero travel to pin against — specifying
it would be a lie in class form.) What the bound actually buys, honestly:
the rail is the one unbounded surface (§4 math — a jazz piano loop is
~3,000px of rows). **(a)** Unbounded, it stretches the *document* to
~3,000px+, pushing the below-grid region (LoopStation, the whole learning
area) thousands of pixels down instead of one flick below the dashboard.
**(b)** The bound is exactly what jam view swaps to `h-full` — an unbounded
rail can never fit `h-screen` (§1.1). The rail's depth scrolls *within* its
column; the left column stays whole; at rest the rail shows ~644px (the
grid height). D-40 Rejected E (internal scroller) was rejected for the
*full-width band*, where it capped visible rows below 4 and nested a
scrollbar inside the page's only axis; in a two-column dashboard, bounding
the one unbounded column is what makes the dashboard a fixed-height unit —
the rejection does not carry over. **No auto-scroll in this sprint** (§4).
Vertical budget, normal mode at rest: 836 52 (header) 52 (controls) 88
(strip + gap) ≈ **644px for the grid**. Left stack ≈ 240 + 190 + ~200 + 24
gaps ≈ **654px** — everything on screen except the last ~1020px of the
related progressions card at exactly 900px window height; a micro-flick shows
it. In normal mode that residue is acceptable (the page scrolls anyway); **in
jam view it is not** — §1.1 makes the fit exact by construction, with the
related card as the left column's flex absorber.
### 1.1 Jam view — the one-screen lock + fullscreen toggle
The refinement's "fullscreen button". **Mechanism chosen: one button, two
layers on one state.**
- **Layer 1 — CSS jam view (the guarantee).** App gains a `jamView` boolean
(pure UI-state — nowhere near the audio callbacks/refs). When true:
- the page root becomes `h-screen overflow-hidden flex flex-col` (normal
mode: today's `min-h-screen` flow);
- **everything below the dashboard is not rendered** — LoopStation, Behind
the Scenes, Rhythm Analyser, Tuner, KnowledgeDock (conditional mount, not
`hidden`, so collapsed-state chrome can't leak height). Header, controls
bar, strip, grid remain — Stop/Start, the instrument selector, and the key
lock are jam-relevant chrome;
- the grid gets `flex-1 min-h-0`; the rail wrapper swaps its normal-mode
`xl:max-h-[calc(100vh-1.5rem)]` bound for `h-full overflow-y-auto` (the
column IS the viewport remainder, so the viewport-calc bound gives way to
the exact column height);
- the left column becomes `flex flex-col min-h-0`: instrument view and
licks strip fixed-height, the related progressions card `flex-1 min-h-0
overflow-y-auto` — the **one flex absorber** that soaks up the ±20px
between window sizes. Internal scroll here is the licensed last resort
and only engages below ~950px-tall windowed viewports (numbers below).
- **Layer 2 — browser fullscreen (the enhancement, best-effort).** The same
toggle calls `document.documentElement.requestFullscreen()` on enter and
`document.exitFullscreen()` on exit. Both return **Promises** — a bare
try/catch does not swallow the rejection; the calls must be
`.catch(() => {})` (or awaited inside try/catch). Electron grants it (plain
renderer, no IPC needed); if a browser build ever refuses, jam view still
works at layer 1. Fullscreen reclaims the ~32px
title bar (and any taskbar), which is exactly what turns "fits minus 20px"
into "fits clean" at 900-high screens.
- **The button** lives at the right end of the controls bar (the global,
always-visible chrome — same reasoning as the instrument selector):
`⛶ Jam view` / `✕ Exit` , `aria-pressed`, min-32px target,
`focus-visible:ring-2 ring-accent`, tokens only.
- **Exit paths, all restoring normal flow:** the button; **Escape** (a
`keydown` listener active only while `jamView` — needed because layer 1 can
exist without layer 2); and the native fullscreen Esc, synced via a
`fullscreenchange` listener (leaving fullscreen by any means switches
`jamView` off — one state, never half-exited). Entering does NOT auto-start
listening; leaving does NOT stop it — the toggle is layout-only.
**Jam-view budget (the hard numbers).** Grid height = viewport p-3 (24)
header 52 controls 52 strip + gap 88:
| Viewport | Grid (= rail height) | Left: fixed 454 (instrument 240 + licks 190 + gaps) → related card gets | Verdict |
|---|---|---|---|
| 1280×900 window (layer 1 only, content ~836) | **644px** | ~190px → heading + ~2.8 of 3 entries | fits; the card's last entry may shave ~20px — its internal scroll absorbs it |
| 1280×900 screen, true fullscreen (content ~876) | **684px** | ~230px → 3 entries fully clear, ~20px spare | **fits clean — the ~20px story is gone** |
| 1280×960+ screen, true fullscreen (content ≥936) | **≥744px** | ≥290px → up to 5 entries | fits with room |
The rail's *depth* still exceeds any of these for piano loops (§4 table — a
4-chord jazz loop is ~2,6003,000px of rows). That is the one place "see
everything at once" and "every voicing, all levels, zero clicks" (D-30)
mathematically collide; the cell strategy compresses first (recommended cell
leads; the 284+160 pair-fit halves mixed-station heights, §4) and the
remainder falls to the rail's contained scroll — the justified internal
scroller. All four *bounded* surfaces (strip, instrument, licks, progressions)
fit whole; guitar and bass rails fit ~2.53 of 4 rows with the "now" row
highlighted wherever it sits.
### 1.2 The slim loop strip — banner inventory
What `ProgressionBanner` renders today, and its disposition:
| Banner element today | Disposition |
|---|---|
| Key chip (root text-2xl accent + mode + confidence %) | **Survives** — leftmost, unchanged |
| Chord history (last 8, age-faded, tap → ChordDetailModal; current chip enlarged text-3xl + amber rn + pop-in animation) | **Survives, capped to last 5** — the enlarged current chip IS the now-playing display now; the pop-in animation moves with it |
| Loop row (♻ + chips, chord + rn, active chip accent-glow via `findLoopPosition`, "→ loop" tail) | **Survives, promoted onto the same row** as key + history (divider between) |
| `hidden lg:block` divider + right 30% column: "NOW PLAYING" label, **text-6xl amber chord**, rn, "tap for voicings" | **GONE.** The user's words: the loop chips already carry it. The tap-for-voicings affordance is not lost — every chip already opens ChordDetailModal, and the rail shows the loop's voicings permanently |
| Empty states ("Detecting key…", "Start listening…", "Play a chord") | First two survive; "Play a chord" dies with its column |
One row: key chip (~90px) + 5 history chips (~230px) + divider + up to 8 loop
chips (~320px) + tail ≈ ~720px — fits 1,256 with room; 12-chord loops (12-bar
blues) wrap the loop chips to a second line (strip ~104px, still fine).
**Strip chrome trim (part of the slimming):** `p-4 → p-2` and drop the history
wrapper's `pb-1` — the enlarged current chip (text-3xl + rn + chip padding) is
~58px tall on its own, so with p-4 the strip lands at ~9296px; the trim is
what makes the **~76px** figure true. Goes in L-50 commit 1 with the column
removal (§6.1).
Duplication audit: the current chord appears twice (last history chip + active
loop chip) — pre-existing, and the user's directive explicitly endorses the
loop chip as the "now"; the big third copy is what dies.
---
## 2. Compact instrument view — the mechanism
**Chosen: a `compact` prop on Fretboard / Piano / BassFretboard = trimmed card
chrome + a natural-width cap on the SVG. No fret reduction, no transform
scaling.**
- **Natural-width cap:** each SVG keeps `width:100%` but gains
`max-width: <its viewBox width>px` (Fretboard 674px, Piano 562px), i.e. it
never renders *above* scale 1.0. In the 744px left column (≈718px card
interior with the compact `p-3`) the fretboard sits at its designed 1.0 scale → SVG height
**186px** (today at 70% of 1,256 it renders at ~1.23 scale ≈ 229px + fat
chrome ≈ 320px card). Piano: 150px SVG.
- **Trimmed chrome:** `p-6 → p-3`, heading `mb-4 → mb-2`, and the legend row
(chord tone / pentatonic / scale dots) merges onto the heading line
(right-aligned) instead of a separate `mt-3` row. Card totals: fretboard
**240px** (was ~320), piano ≈ **205px**.
- **Legibility, honestly:** at scale 1.0 the fretboard is at its *designed*
size — 20px note dots, 9px note labels, 10px string/fret labels, exactly
what ChordDiagram-era eyes were tuned on; nothing shrinks below today's
rendering (today it renders *larger* than designed, which is part of "too
big"). The compact card is smaller because the chrome and the over-scale go,
not because the notes do. Below ~700px column width the SVG scales down with
the column; at 0.9 scale (≈606px) labels are ~8px — the floor I'd defend.
The narrow plan (§7) gives the view the full window width anyway, so the
sub-1.0 zone only exists between ~1280 and ~1140px windows if the grid
breakpoint were lower — hence `xl:` for the grid, not `lg:`.
- Rejected mechanisms: **fewer frets** (07) kills position playing above the
7th fret — soloists live there; **CSS `transform: scale()`** blurs text and
shrinks hit targets — dishonest compactness; **hard height cap with
letterboxing** wastes the saved space as empty gutters.
---
## 3. What's removed / moved (full inventory)
| Surface | Disposition |
|---|---|
| Big "Now Playing" chord (banner right 30% + divider) | **Removed** (§1.2) |
| `ProgressionSuggestions` | **Unmounted; file kept in place** (EducationPanel/RoadmapTrack precedent — joins the retire-then-delete backlog item). Its job splits in two per the directive: "what to play on these chords" → the voicings rail; "where these changes can go" → RelatedProgressions (§5). Its generic genre/mood table and circle-of-fifths padding retire with it |
| The 70/30 instrument row | **Dissolved** — the instrument view becomes the left column's first block; the 30% slot's replacement is the rail column |
| JamGuide band (rail + licks, full width) | **Recomposed** — JamGuide stops rendering a band and renders the grid's jam surfaces: rail into the right column, LicksStrip + a related-progressions slot into the left (§6, component boundary) |
| LicksStrip | **Stays module-local in JamGuide.jsx** — no file move. It renders from JamGuide's match/context memos (`activeStyle`, `contextStation`); extracting it to its own file buys nothing and forces prop plumbing for the token-boundary context sort. It just mounts in the left column now |
| LoopStation | **Below the grid, first — and hidden in jam view.** Recorded call: the user's enumeration of the live-jam view is "the jam and the voicings and the licks and the chords and the loop", where "the loop" is the *chord* loop (the strip's ♻ chips), not the audio looper. LoopStation is a performance tool, but it is not on the list — it goes below with the learning surfaces, first in line because it feeds the detected loop. If the user misses it mid-jam, admitting it into jam view is a one-line conditional — the reversal path is cheap and noted in §9 |
| Behind the Scenes / Rhythm Analyser / Tuner collapsibles | Below LoopStation, unchanged |
| KnowledgeDock | **Last, unchanged** — browse & study stays below the fold |
| ChordDetailModal, AudioCapture, all `src/lib/**` audio/theory | Zero changes |
In **normal mode** everything below the grid remains exactly what the
refinement asks for — the learning / behind-the-scenes area on the ordinary
page scroll ("everything that is learning and behind the scenes etc you can
keep below/scrollable"). In **jam view** this whole region is hidden (§1.1) —
the dashboard is the entire page.
---
## 4. The rail at column width (~500px shell, ~456px row interior)
Row interior arithmetic: 500 rail section `p-3` + border (~26) row `p-2` +
border (~18) ≈ **456px** for header + cells. The inherited 93/160/284 figures
are already **box values** — integrated-glance's own verified sums prove it
(4×284 + gaps + chrome ≈ 1,178 with no extra per-cell padding), so nothing
gets padding added on top below. Cell strategy: **recommended-first, gallery
wrapped below — all cells always rendered, zero clicks** (D-30's "all at once"
directive stands; only the *geometry* adapts).
- **The recommended cell leads and reads as the answer.** The station's own
voicing (guitar: KB play shape badged "play"; piano: the authored/threaded
voicing with its honest label) keeps its accent-bordered figure and is
always the first cell — at column width it is frequently alone on line one,
which makes prominence free. D-51 may add nothing more than a slightly
stronger figure treatment (accent/60 border → accent) — no size difference,
no new colour.
- **Guitar:** cells ~93px (box) → **4 per line** (4×93 + 3×8 gaps = 396 ≤ 456
— fits with ~60px to spare, not borderline; a 5th cell at 497 does not).
Typical station = play cell + 36 placeable shapes = 47 cells → 12 cell
lines (~140px each). Header content (chord + rn + now/next + solo label +
aim dots + transition chip ≈ 540px of inline content) **wraps to 2 lines
≈ 50px** — fine, it already `flex-wrap`s. Row ≈ **206350px**.
- **Piano:** one-octave cells ~160px (box) → 2 per line (328 ≤ 456);
two-octave cells ~284px (box) → alone or, critically, **paired with a
one-octave cell: 284 + 160 + 8 = 452 ≤ 456 — the mixed pair FITS today, by
~4px**. That 4px is real but fragile (a longer label, a scrollbar gutter, a
browser rounding step could break it), so D-51's cell padding/gap shave is
**margin-hardening for an already-passing fit**, not a rescue — the pairing
is the difference between 5 and 3 cell lines on mixed stations. Worst
station (root above D with a true 7th — all five cells two-octave, per the
D-40 corrected math; 2×284 + 8 = 576 > 456 so they never pair with each
other): **5 cell lines ≈ 650 + header ≈ ~700px per row**. Best (roots CD /
triads): 3 lines ≈ ~490px.
- **Bass:** BassGuideRows text rows (~70px) or BassPatternCard rows — narrow
by construction; the column fits them with no adaptation beyond wrap, which
it inherits.
- **Wrap, never horizontal scroll** — unchanged invariant. The only permitted
horizontal scroller stays VoicingBrowser's per-cell guard around MiniPiano
thumbs on sub-320px pathologies.
### The honest vertical budget
| Scenario | Full rail height | Visible: normal rest (~644px) / jam view fullscreen (~684px) |
|---|---|---|
| 4-chord loop, guitar | ≈ 4×~275 avg + chrome ≈ **~1,150px** | ~2.3 / ~2.5 rows |
| 4-chord loop, piano (jazz flagship, mostly worst-case rows) | ≈ **~2,6003,000px** | ~1 / ~1.1 rows |
| 812 chord loop (12-bar) | guitar ~2,300 / piano ~5,000+ | scroll; the strip's loop chips always carry the position |
**What "one screen" honestly means:** all five surfaces are simultaneously
present at 1280×900 (whole, in jam view — §1.1) — but the rail's *depth* is a
scroll, contained in its column: it is the one panel whose content is
unbounded by construction (every voicing of every loop chord, D-30's "all at
once"), so it is the design's justified last-resort internal scroller; the
cell strategy above compresses first. A 4-chord guitar loop is ~1.4
rail-screenfuls; a 4-chord jazz piano loop is ~3.5. The playhead highlight
travels whether or not the row is in the scroller's window; the strip up top
always shows where you are. **No
auto-scroll in D-51** — same reasoning as D-40 §4, plus: contained auto-follow
is now *technically safe* (the scroller is no longer the document, so it can't
yank the page), so I flag it to Maestro as an optional 1-point follow-up
**after** the user has felt the manual version — auto-motion during a jam is
exactly the "it changes while I play" complaint in a new hat, so it must be
user-pulled, not designer-pushed.
Flag (not in scope): a **root-aligned MiniPiano crop** would turn most
two-octave piano cells into one-octave ones (~160px), roughly halving piano
rail heights. It reopens D-24's C-aligned-crop decision and MiniPiano is
frozen this sprint — Maestro may file it as a D-52 candidate.
---
## 5. Related progressions — the spec for L-51
**What it is:** 35 KB progressions genuinely related to the *detected loop*,
replacing ProgressionSuggestions' generic genre table. KB-sourced only
(`kb[style].progressions` — id, name, rn, degrees, qualities, level, songs),
loop-relative by construction.
### Ranking (computable today, no new theory)
Inputs: `detectedProgression` (chord-name strings), the KB registry, and
`matchLoopToProgression`'s result. Reuse `src/lib/match.js` machinery —
`loopToDegrees` and `canonicalDegrees` are currently module-private and must
become **additive exports** (L-51 lock addition; no behaviour change), next to
the already-exported `matchLoopToProgression`/`buildLoopIndex`.
1. `loopDeg = loopToDegrees(loop)`; bail to empty state if null.
`loopCanon = canonicalDegrees(loopDeg)`. `match = matchLoopToProgression(…)`
(the component computes its own — see §6's parallelism note).
2. Build the loop's **transition set** `T(loop)`: for each i (wrap-around),
the triple `(Δ = (deg[i+1]deg[i]) mod 12, q[i], q[i+1])` with qualities
from the chord-name suffixes (unmappable suffix → wildcard: match on Δ
alone). Same for every KB progression from its `degrees`/`qualities`.
**Collapse first — mandatory.** The live `detectedProgression` is a
*collapsed* form (detection never commits the same chord twice in a row),
while KB `degrees` are *raw*, bar-per-bar — blues-12bar is
`[0,0,0,0,5,5,0,0,7,5,0,7]`. Compared raw, the +100 same-canonical-shape
term would NEVER fire for the ~10 collapse-affected KB progressions —
silently killing the flagship "this 12-bar IS their 12-bar" relation (it
degrades, never misfires, which is why it would go unnoticed). So: before
`canonicalDegrees(p.degrees)` AND before building `T(p)`, **collapse
consecutive equal `(degree, quality)` pairs** in `p` (also with the
wrap-around pair). This additionally removes the harmless-but-deflating
`Δ=0` self-transitions from `T(p)`. Alternative once D-62's fix (a) lands
collapsed-form indexing in match.js: consume that shared collapsed form
instead of collapsing locally — coordinate via the §9 match.js
shared-file note.
3. Score every KB progression `p` with `p.id !== match.id`:
- **+100** if `canonicalDegrees(p.degrees) === loopCanon` — the same
changes in another style/length ("this turnaround IS jazz's IviiiV");
- **+40** if `p.style === match.style` (0 when nothing matched — the
ranking still works loop-relative off the raw degrees);
- **+12 per shared transition** (distinct triples in `T(loop) ∩ T(p)`),
capped at 36 — this is what finds "shares the ii→V" honestly;
- **+ up to 16** for rebased degree-set overlap (Jaccard × 16);
- **1 per chord of length difference** (tie-break toward similar-size loops).
4. Floor **24** (at least a shared transition + some overlap, or same-style +
substance) — never pad with junk; fewer honest entries beat five stretches.
Sort desc (stable by style, id), take **max 5; the dashboard budget
guarantees 3 visible** (§1.1) — the card is the left column's flex
absorber, so entries 45 show on tall viewports and scroll within the card
on tight ones.
### Per-entry render (~56px each)
- Line 1: **name** (gray-100 semibold) · style label (gray-500) · **level
chip** (ExplorePanel's `LevelBadge` language — untagged counts foundation) ·
annotation (gray-500, [10px]): `same changes` when the +100 fired, else
`shares {rn_a}→{rn_b}` naming p's rn at the top shared transition, else
`same style`.
- Line 2: the **chord chain realized in the current key** — rootPc =
`(keyRoot + degree) mod 12` + `CHORD_TYPES[quality].suffix` (the
stationVoicings formula), rendered as tappable chips with rn beneath
(banner-chip visual language, smaller); 12-bar chains truncate to the first
8 + "…". **Tap a chord → `onChordClick` → ChordDetailModal** — the existing
per-chord pattern (ExploreSection does exactly this); no new modal, no dock
deep-link API invented for v1.
### Empty states (honest)
- No loop detected → one-liner (~40px, dashed border):
*"Loop a progression — related changes from the songbook land here."*
- Loop but nothing ≥ floor → *"Nothing in the songbook genuinely relates to
this loop yet."* (never pad).
- Loop unmatched but candidates score (shape/transition terms only) → render
normally; the annotation still explains *why* each entry is there.
---
## 6. Component boundary + migration order (green at every commit)
**Boundary call:** `JamGuide` (default export) is promoted from "band" to
**jam-grid owner**: it renders the two-column `flex` region and takes two JSX
slot props from App — `mainView` (the instrument view — App keeps choosing
Fretboard/BassFretboard/Piano; JamGuide never imports them) and `relatedSlot`
(RelatedProgressions, mounted by App). Left column = `mainView` + LicksStrip +
`relatedSlot`; right column = the height-bounded scroller wrapping GlanceRail /
BassGuideRows / the heard-live fallback. Rationale: the match / stationVoicings
/ canonicalPos / focus machinery stays in ONE component with no context and no
logic lifted into App (the 🚨 App.jsx contract); the slots keep App as pure
mounts. **RelatedProgressions computes its own match** (memoized on the loop
key — `matchLoopToProgression` over a module-level index is trivially cheap);
this small duplicate computation is what makes L-51's files disjoint from
D-51's (they can run in parallel) and keeps the component pure/prop-driven:
`{ loop, keyInfo, onChordClick }`.
Sequenced: **L-50 → (D-51 ‖ L-51) → C-50.** Critic gates each.
### 6.1 L-50 (Luthier) — the dashboard restructure
**Files (re-lock at promotion):** `src/App.jsx` (layout/mounts only, 🚨 audio
contract grep-gated), `src/components/ProgressionBanner.jsx`,
`src/components/JamGuide.jsx`, `src/components/Fretboard.jsx`,
`src/components/Piano.jsx`, `src/components/BassFretboard.jsx` (compact prop —
mechanical chrome trim + max-width cap per §2; D-51 polishes visuals if
needed). **Not touched:** ProgressionSuggestions.jsx (unmounted, not edited),
GlanceRail.jsx, VoicingBrowser.jsx, all `src/lib/**`.
1. **Commit 1 — slim strip.** ProgressionBanner: delete the right 30% column +
divider + its `currentRN`/big-chord code path; merge key + history + loop
onto one row; `HISTORY_SHOWN` 8 → 5; chrome trim `p-4 → p-2` + drop the
history wrapper's `pb-1` (what makes the ~76px strip true, §1.2).
Standalone green.
2. **Commit 2 — the grid (atomic).** These land together or the page has a
hole: App replaces the 70/30 row + band with the `xl:` two-column grid;
**ProgressionSuggestions unmounted** (import + mount deleted); JamGuide
gains `mainView`/`relatedSlot` props and renders left/right columns, rail
wrapped in the height-bounded scroller (`xl:max-h-[calc(100vh-1.5rem)]
xl:overflow-y-auto` — no sticky, §1); instrument views gain
`compact` and App passes it; App passes `relatedSlot={null}` (slot renders
nothing until L-51). Green; contract grep clean.
3. **Commit 3 — jam view (§1.1).** App: `jamView` UI-state + the controls-bar
`⛶ Jam view` toggle button; page root `h-screen overflow-hidden flex
flex-col` + grid `flex-1 min-h-0` + left-column flex layout while active;
below-dashboard region conditionally unmounted; JamGuide's rail wrapper
accepts a `fill` (or `jamView`) prop switching the max-h bound → `h-full
overflow-y-auto`; best-effort `requestFullscreen()`/`exitFullscreen()`
**with `.catch(() => {})`** (they return Promises — a bare try/catch does
not swallow the rejection) + `fullscreenchange` sync + Escape keydown
(active only while `jamView`).
🚨 Pure layout/UI-state — zero contact with audio callbacks, refs, or
AudioCapture props; the toggle never starts/stops listening. Standalone
green on top of commit 2.
### 6.2 D-51 (Muse) — rail at column width
**Files:** `src/components/GlanceRail.jsx`, `src/components/VoicingBrowser.jsx`
(dense-path spacing only). Recommended-cell prominence; cell padding/gap shave
as **margin-hardening for the ~4px-tight 284+160 piano pair fit** (§4 — it
passes today; the shave makes it robust to label length / scrollbar gutters /
rounding); header wrap tuning at ~456px; verify wrap-never-scroll, playhead
highlight, AA contrast + focus rings; eyeball 1280×900, 1440×900, ~640px
stacked; recompute §4's table against the built thing. No auto-scroll
introduced.
### 6.3 L-51 (Luthier) — RelatedProgressions
**Files:** `src/components/RelatedProgressions.jsx` (new), `src/lib/match.js`
(**additive exports only**: `loopToDegrees`, `canonicalDegrees` — flag the
shared-file lock to Maestro at promotion), `src/App.jsx` (one-line: pass
`relatedSlot={<RelatedProgressions …/>}`). Ranking per §5, exported from the
component file for smoke coverage; honest empty states; build + smoke green.
Disjoint from D-51 (App.jsx/match.js vs GlanceRail/VoicingBrowser) → may run
in parallel after L-50.
---
## 7. Narrow plan (< xl, and the ~640px check)
Columns stack in the jam-following order: **loop strip → instrument view →
voicings rail → licks strip → related progressions** — i.e. the right column
tucks between mainView and LicksStrip, matching the user's list order.
Implementation: the rail block is simply the second child inside the stacked
flow below `xl` (JamGuide reorders its own children with responsive classes or
conditional order — no duplicate mounts). The rail **unbounds** below `xl`
(the max-h/overflow classes are `xl:`-prefixed) and lays out at natural height
in page flow — a nested scroller inside a scrolling page is a trap on touch.
Cell wrap at ~576px interior: guitar 5/line, piano cells **pair** (a 284px
two-octave + a 160px one-octave = 452, or two two-octaves at the 576 boundary) —
the same margin-hardened pairing D-51 verified for the bounded column (§4),
with more room here, not the "cells ride alone" of the narrower bounded width. The instrument
selector never moves: it lives in the controls bar, global, above everything
at every width.
**Jam view below `xl`:** the toggle still works — below-dashboard surfaces
hide and fullscreen still fires — but the stacked dashboard is taller than any
narrow viewport, so the page keeps scrolling (`h-screen overflow-hidden`
applies only at `xl:`+ alongside the grid). One-screen is a two-column
promise; jam view narrows honestly to "distraction-free" rather than
pretending the geometry works.
---
## 8. Rejected alternatives
**Rejected A — keep the rail as the full-width band and put licks +
progressions in the right column instead.** The rail is the surface the
directive names for the right side ("i'd like to have the suggested voicings
on the right side of the screen (the jam guide)") — and the math agrees: full
width doesn't make the rail *shorter* in any useful way (rows are height-bound
by cell-line count, and at 1,240px most piano galleries fit one line, but the
band still starts below the instrument view and pushes licks/progressions off
screen — today's exact failure). Licks and progressions are short; they fit
under the instrument view; the tall thing is what needs the dedicated column.
**Rejected B — one-screen by truncation: show only the recommended voicing per
station, gallery behind a tap.** Fits 4 stations in ~640px with zero scroll —
and violates three standing calls at once: scroll > click, D-30's "all at once"
gallery directive, and the learning value the user praised ("potentially learn
new ways to play it while you are playing"). The gallery stays; its depth
becomes a contained scroll, not a click.
**Rejected C — rail in the LEFT column, detection surfaces right.** Reading
order puts the primary, continuously-tracked surfaces (strip, instrument view)
top-left where Western eyes rest; the rail is a reference you glance at. Also
geometric: the instrument view wants the wide column (674px natural fretboard
width > 500px rail), and swapped columns would force the fretboard to ~0.68
scale — sub-legible labels.
**Rejected D — compact the instrument view via CSS `transform: scale()` or a
reduced fret range.** Covered in §2: transform blurs text and shrinks targets;
frets 07 amputates upper-position play. The natural-width cap + chrome trim
achieves the same ~80px saving honestly.
**Rejected E — page-flow rail (no height bound, no contained scroll).** The
"pure" reading of the no-nested-scrollbar taste rule — and it structurally
fails the refinement: an unbounded rail stretches the *document* to the rail's
full height (a jazz piano loop ≈ ~3,000px+), so the below-grid region —
LoopStation and the whole learning area — lands thousands of pixels down
instead of one flick below the dashboard; and in jam view an unbounded rail
can never fit `h-screen`, so the 100vh hard constraint is unmeetable without
the bound anyway. (The left column's five surfaces sit at the top either way —
the cost is the document's length and the jam-view fit, not their
co-presence.) Below `xl` this rejection inverts — §7 — because stacked
layouts have no second column to preserve.
---
## 9. Out of scope / flags for Maestro
- **Contained auto-follow** inside the rail scroller — now technically safe,
deliberately deferred; user-pulled follow-up only (§4).
- **LoopStation in jam view** — excluded per the user's own enumeration (§3
recorded call); if missed mid-jam, admitting it is a one-line conditional.
User-pulled follow-up only.
- **Root-aligned MiniPiano crop** (halves piano rail height) — reopens D-24;
D-52 candidate (§4).
- **`src/lib/match.js` additive exports** in L-51 — shared-file lock note at
promotion (§6.3). Same coordination point covers D-62: if its fix (a) lands
collapsed-form indexing in match.js first, L-51's ranking consumes that
shared collapsed form instead of collapsing locally (§5).
- **Retire-then-delete backlog** grows by ProgressionSuggestions.jsx
(unmounted L-50) alongside RoadmapTrack/CurrentJamPanel/EducationPanel.
- KnowledgeDock deep-link ("open Explore at style X") — not invented for v1;
RelatedProgressions taps go per-chord to ChordDetailModal (§5).
- No new tokens, no new colours, no dependencies, no KB/theory/audio changes
anywhere in this design. Geometry figures verified per integrated-glance.md;
module heights are estimates and D-51/C-50 re-measure the built thing.
+156
View File
@@ -0,0 +1,156 @@
# Related-area space layout — Try-this side-by-side + Related 2×2 (task D-75)
**Sprint:** `sprint-dashboard-polish` · **Owner:** Muse · **Impl tasks:** L-75 (TryThis.jsx + App mount) · L-76 (RelatedProgressions.jsx). Concept doc only — no code here.
**User ask (2026-07-13, verbatim, after running the working dashboard — happy with it):**
> "for the TRY THIS can we also add the little piano/fretboard next to it? now it also has a 1/2 option, but please put them next to each other, we have enough space in that area. also for the suggested progressions underneath there is space to have it cut in half to make it 2x2 in a similar fashion so we use the space and we fit everything in one big screen."
The user is pointing at the **LEFT column** of the jam dashboard (`flex-1`**744px** per `one-screen.md` §1 — far wider than the 500px rail) and asking us to **use its horizontal width**: (A) Try-this stops rotating one-at-a-time and shows **all** the current chord's substitutions **side by side**, each with a **mini instrument diagram** of that chord; (B) RelatedProgressions goes from a vertical list to a **2×2 grid**. Both to compress the vertical footprint so more fits on one screen.
---
## 0. The honest reversal (say it plainly)
L-74 shipped a **rotating one-at-a-time** Try-this card (`pickSub` / `advanceOnWrap` / `cycle`), because the same-day directive was *"more surprising, more jam-like, keeps offering new ideas."* The user has now **seen** that rotation and prefers **all-visible side-by-side** ("put them next to each other, we have enough space"). This doc **reverses** the rotation decision. That is not churn for its own sake — it is the user refining after seeing it live, exactly the loop the ensemble is built for. The **engine (`suggestSubstitutions`, L-73) and its rules do not change**; only the UI shape does.
What survives from L-74's `TryThis.jsx`:
- `parseChordName(name)` — pure, keep.
- `subsForChord(name, pos, loopArr, keyInfo)` — pure, keep.
- `pickSubject(loopArr, keyInfo, currentChord)` — pure, keep. This is what keeps the card **live**: it picks (a) the live `currentChord` if it parses and yields ≥1 sub, else (b) the first loop station that yields subs, else (c) `null` (honest empty). The card still follows the playhead — as you play, the subject chord and its ≤4 subs update.
What is **deleted**:
- `useState(cycle)` + the rotation `useEffect`, `advanceOnWrap`, `pickSub`, the `lastPosRef` / `lastNameRef`, the "N of M" indicator, the dot rail. Smoke coupling: **none**`scripts/smoke.mjs` has zero references to `advanceOnWrap` / `pickSub` / `parseChordName` (grep-confirmed; its "rotation" hits are all progression-match tests). So L-75 can drop the helpers without touching smoke; its lock stays `TryThis.jsx` + `App.jsx`.
Honest empties preserved: no key / no loop / atonal → `pickSubject` returns null → render nothing (unchanged). A chord with fewer than 4 valid subs simply shows fewer cards (the engine already `.slice(0,4)`; often 13 fire).
---
## 1. Try-this — side by side, one card per sub, each with an instrument diagram
### 1.1 The layout
Keep the outer section shell (`rounded-2xl border border-border bg-panel p-3`, the micro-header "Try this instead of {chord} · in {key} {mode}"). Below it, replace the single-card body with a **flex-wrap row of sub-cards**, one per `subject.subs` entry (≤4):
```
<div className="flex flex-wrap gap-2">
{subject.subs.map(sub => <SubCard … />)}
</div>
```
- **Container adapts to the instrument's cell width** (§3 proves the footprints — the across-count is NOT a fixed 4):
- **guitar / bass**`flex flex-wrap gap-2`, each card `basis-[168px] grow min-w-[152px]`: the small cells (guitar 75px, bass none) let **4 fit one row** in the 720px interior; with 13 subs the cards `grow` to fill.
- **piano** — a **`grid grid-cols-2 gap-2`** (2×2): the mini keyboard's real footprint is up to **199px** (§3), so 4 piano cards cannot share one 720px row; a clean 2×2 mirrors the rail's own piano idiom (`VoicingBrowser` dense = `grid grid-cols-2`) and avoids the unbalanced 3+1 that a plain `flex-wrap` would produce.
- On a narrow/stacked viewport both collapse to **1-per-row** (`grid-cols-1` / `flex-wrap`) — the DoD reflow, for free.
Each **SubCard** is a vertical stack (`flex flex-col items-center gap-1.5 rounded-lg border border-border bg-border/30 p-2`):
1. **Chord chip** (top) — the tappable control, reusing L-74's chip idiom exactly:
`button``onChordClick?.(sub.label)`, classes `rounded-lg border border-border bg-border px-2 py-1 text-sm font-bold text-gray-100 hover:border-accent/50 hover:text-accent focus-visible:ring-2 focus-visible:ring-accent`. `aria-label={`${sub.label} — ${sub.why}`}`. Tap → `ChordDetailModal` (App's `setSelectedChord`), where the **full** why + all voicings live.
2. **Mini instrument diagram** (middle) — of `{sub.rootPc, sub.quality}`, following the **global instrument** (§2). This is the "little piano/fretboard next to it" the user asked for.
3. **Category tag** — the L-74 language: `relative` / `borrowed` / `colour` / `V7`, with the `↻` accent glyph **only** for `relative` + `secondary_dominant` (circle categories — unchanged rule, `text-accent`).
4. **Why** (bottom) — `sub.why`, `text-[11px] leading-snug text-gray-400`, **`line-clamp-3`** with the full text on the chip's `aria-label` + tap→modal. At ~152168px card width, clamp-3 keeps whys up to ~75 chars whole; longer ones truncate visibly and the full sentence is one tap away. This is the honest trade of side-by-side: 4 whys visible at a glance costs each one its full width — the user chose see-all over the single full-width why.
### 1.2 Across-count is a function of the diagram footprint, not a fixed "4"
The user said *"put them next to each other … we have enough space"* and — resolving the piano case directly — *"for the piano's u can take more space in case there is indeed a bigger piano needed"* (2026-07-13). So: spend the **horizontal** budget as far as each instrument's diagram allows, and let piano take the **vertical** room it needs rather than cramming it. Guitar/bass cells are small (75px / none) → 4 subs sit **one row across**. Piano cells are large (up to 199px, §3) → 4 subs form a **2×2** — still "next to each other," still using the width, just a taller block (which the user explicitly OK'd). The count follows the footprint; the layout adapts (§1.1) instead of forcing a uniform grid that would clip the piano or waste the guitar row. **No MiniPiano change** — the keyboard renders at its honest size.
---
## 2. The instrument prop — threading + which resolver draws each diagram
`TryThis` needs the global `instrument` (`'guitar' | 'piano' | 'bass'`), which lives in `App.jsx` and is already handed to `JamGuide` (line 849). **Prop path:** add `instrument={instrument}` to the `<TryThis … />` mount in the `relatedSlot` (App.jsx ~line 859) and add `instrument` to the component signature: `TryThis({ loop, keyInfo, currentChord, onChordClick, instrument })`. One-line App change, grep-clean (no audio/callback contract touched) — this is the App half of L-75.
Per-instrument diagram resolver (mirror the established rail idiom in `VoicingBrowser.jsx:288`/`:327`):
| instrument | diagram | resolver → render |
|---|---|---|
| `guitar` | `ChordDiagram size="thumb"` (~75px) | `const shape = getGuitarVoicings(sub.label)[0]``<ChordDiagram shape={shape} rootPc={sub.rootPc} size="thumb" />`. `getGuitarVoicings` (voicings.js) resolves the first (barre/open) shape to **absolute** low-E-first frets; ChordDiagram's open-shape path windows them (draws a `5fr` label when up-neck). **Omit** ChordDiagram's own `label` prop — the chip above already names the chord (saves ~13px). If `getGuitarVoicings(sub.label)` is empty (rare), render **no** diagram — just chip + why (honest, no crash). |
| `piano` | `MiniPiano size="mini"` (107199px, §3) | `<MiniPiano voicing={{ ...pianoVoicing({ rootPc: sub.rootPc, quality: sub.quality }), rootPc: sub.rootPc }} size="mini" />`. **Spread `rootPc` back in**`pianoVoicing()` output carries none, and `VoicingPiano` needs it to badge "R" correctly (the VoicingBrowser:317-319 caveat). `size="mini"` = the dashboard-density scale already used in the rail's 2×2. |
| `bass` | **no diagram — honest** | Bass players read a chord symbol + root, not a chord grip; there is no compact bass-chord renderer, and reusing the guitar/piano diagram under a BASS selector would misrepresent the instrument (same honesty call the licks strip makes for bass). SubCard shows the chip + a small caption `root · {NOTES[sub.rootPc]}` (`text-[10px] text-gray-500`) + the why. Compact, correct, no faked shape. |
All diagrams use the established note-colour tiers already baked into `ChordDiagram`/`MiniPiano` (accent-purple root, light-purple/gray other tones, amber bass ring) — no new colour, no token change.
---
## 3. Space math — the LEFT column (~744px), honest
- Left column `flex-1 min-w-0`**744px** (one-screen.md §1). The `relatedSlot` is `flex flex-col gap-3` **directly** in it, so the Try-this `section` spans the full 744px. Section `p-3` (12px each side) → **interior ≈ 720px**.
- Per-card diagram footprints (recomputed from source geometry):
- **Guitar** `ChordDiagram size="thumb"`: `padL 14 + gridW 55 + padR 6 = 75px` wide; `padT 11 + gridH 55 + padB 6 = 72px` tall (label omitted). Root-independent.
- **Piano** `MiniPiano size="mini"` — the window is **C-octave-boundary anchored, NOT span-anchored** (MiniPiano.jsx:200-207): `octStart = ⌊minNote/12⌋`, `OCTAVES = max(1, ⌈(maxNote octStart·12)/12⌉)`, `SVG_W = (22·(7·OCTAVES + 1) + 2)·0.60`. A voicing whose *interval span* is under an octave STILL renders **2 octaves** whenever its notes straddle a C boundary — so "span ≤ 1 octave" does **not** imply "renders 1 octave." Worked: F♯ major triad `pianoVoicing({rootPc:6})` → notes `[6,10,13]` (span 7) → `octStart 0`, `maxNote 13``OCTAVES = ⌈13/12⌉ = 2``SVG_W = (22·15 + 2)·0.60 = 332·0.60 = **199.2px**`. This fires for **every triad quality at roots pc ≥ 6 (F♯–B)** (maxNote = root + top-interval > 12) and for shells at most roots (the +12 lift pushes the 7th over the next C) — i.e. roughly **half** of all sub roots, and sub roots routinely land upper-half (any G♯/A♯/B relative / borrowed / secondary-dominant candidate). One octave (107px) is the *best* case (triad roots pc 05); **199.2px is the planning footprint.** MiniPiano.jsx:29-31's own header documents this "2-octave mini cell (213.2px)". `SVG_H = (60 + 4)·0.60 = **38.4px** — octave-INDEPENDENT`: the window widens, height never does.
- **Across-count per instrument** (interior 720px, `gap-2` = 8px; an SVG's hard `width` attr floors the flex item's min-content at ≈ its px, so `basis-[168px]` cannot shrink a piano cell below its keyboard):
- **Guitar** — cell 75px, card ~152px min (diagram + `p-2` + chip width) → `4·152 + 3·8 = 632 ≤ 720` → **4-across, one row.**
- **Bass** — no diagram, card ~152px → **4-across, one row.**
- **Piano** — worst-case cell 199.2px, card ~215px (+ `p-2` 16) → `3·215 + 2·8 = 661 ≤ 720` but `4·215 + 3·8 = 884 > 720`. So **at most 3 share a row**, and 4 can't. Laid out as a **2×2 grid** (§1.1, per user's "take more space"): 2 cells/row, `2·215 + 8 = 438 ≤ 720` (roomy, each keyboard gets its full width) → **2 across × up to 2 rows.**
- **Row / block heights** (`SVG_H` is octave-independent, so piano height is driven purely by sub-count, not cell width):
- **Guitar** card: chip ~22 + diagram 72 + why (clamp-3 @11px/1.35 ≈ 45) + tag ~12 + `p-2` 16 + inner gaps ~10 ≈ **~177px** → block (1 row + header 20 + `p-3` 24) ≈ **~221px.**
- **Piano** card: chip ~22 + diagram 38 + why ~45 + tag ~12 + `p-2` 16 + gaps ~12 ≈ **~145px**. 4 subs → 2×2 = `2·145 + 8 ≈ 298` → block (+ 44 chrome) ≈ **~342px**. ≤3 subs → one row → block ≈ **~189px.**
- **Bass** card ≈ chip 22 + root caption 14 + why 45 + tag 12 + `p-2` 16 + gaps 12 ≈ **~121px** → block ≈ **~165px.**
- **Headline:** guitar & bass show all ≤4 subs **4-across in one row** (~165221px block). Piano shows them as a **2×2** taking the full room each 199px keyboard needs — **~189px** block for ≤3 subs, **~342px when all 4 fire** (two rows). Only piano's across-count/row-count vary; height is width-independent (38.4px SVG). This taller piano block is the honest, user-sanctioned cost of "the little piano next to it."
---
## 4. RelatedProgressions → 2×2 grid (L-76, layout only)
### 4.1 The change
Today the populated list is `<ul className="flex flex-col gap-2.5">` of up to `RELATED_MAX_ENTRIES` (5) entries, each = name + meta row (style/level/annotation-or-role) + `ChordChain` chips. **Swap the container** to a 2-column grid:
```
<ul className="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
```
Each `<li>` (its inner markup — name row, `LevelBadge`, role/annotation, `ChordChain`) is **untouched**. `grid-cols-1` on narrow (the stacked reflow), `sm:grid-cols-2` at width. No ranking, scoring, `collapseChanges`, `siblingRole`, or annotation logic changes — L-76 is **presentation only**.
### 4.2 The cap: 5 → display **4** (no ranker change)
A clean 2×2 wants **4** cells; 5 leaves an orphan in a lonely third row that reads as broken. **Decision:** the ranker keeps `RELATED_MAX_ENTRIES = 5` (untouched — no smoke re-pin, no exported-constant edit); the **component renders `primary.slice(0, 4)`** into the grid. Entries are score-sorted, so this drops only the **lowest-scoring** 5th sibling — honest ("top 4"), and a future "show all" affordance could reveal it. This keeps L-76 strictly layout-scoped.
### 4.3 Which sections grid
Per L-72's finding-A, `secondary` (cross-style) is **currently always `[]`**: when a style is locked the panel is same-style-only; when unlocked, everything lands in `primary`. So **only `primary` is ever populated** → only it needs the grid. The optional cross-style section stays dormant; **if** a future change repopulates `secondary`, it gets its own `grid grid-cols-2` block below its own subheading (spec'd, not built). The **idle** dashed card and the two **empty-state sentences** ("You're on the only {style} loop…", "Nothing in the songbook genuinely relates…") stay single-column — they are prose, not a grid.
### 4.4 Space + height
- 2-col cell width ≈ `(720 10 gap) / 2 ≈ 355px`. A `ChordChain` of up to 8 chips (~40px each) wraps to ~2 rows inside 355px — fine, same chips, just narrower flow.
- Cell height ≈ name 18 + meta 16 + chain (2 chip-rows ~30 each) 60 ≈ **~95100px**. Block = header ~20 + subheader ("Try these in {style}") ~18 + (2 rows × 100 + 10 gap) 210 + `p-3` 24 ≈ **~272px**.
- The old vertical **5**-list block ≈ header 20 + subheader 18 + 5 × ~90 + 4 × 10 + 24 ≈ **~552px**. **2×2(4) ≈ 272px → saves ~280px** — the compression the user is after ("cut in half"), almost exactly halved.
---
## 5. The whole left column on one screen (honest)
Usable content box at 1280×900 ≈ **836px** tall (one-screen.md §4). Left stack in jam-view = instrument view + licks strip + `relatedSlot` (`flex-1 min-h-0 overflow-y-auto` absorber = TryThis + RelatedProgressions). Heights are **section-inclusive** (own header + `p-3`); gaps = 3 × `gap-3` = 36px.
| build / instrument | instrument | licks | try-this | related | +gaps | **total** | vs 836 box |
|---|---|---|---|---|---|---|---|
| **current L-74** (guitar) | 240 | 190 | ~154 (rotating, 1 card) | ~552 (5-list) | 36 | **~1172** | overflow **~336px** |
| **D-75 new — guitar** | 240 | 190 | ~221 (4-across, 1 row) | ~272 (2×2) | 36 | **~959** | overflow **~123px** |
| **D-75 new — bass** | 240 | 190 | ~165 (4-across, 1 row) | ~272 | 36 | **~903** | overflow **~67px** |
| **D-75 new — piano, ≤3 subs** | 240 | 190 | ~189 (one row) | ~272 | 36 | **~927** | overflow **~91px** |
| **D-75 new — piano, 4 subs** | 240 | 190 | ~342 (2×2, 2 rows) | ~272 | 36 | **~1080** | overflow **~244px** |
**Honest headline:** the RelatedProgressions 2×2 halves that block in every case (**~552 → ~272, 280px**) — the compression the user asked for. Guitar and bass compress hard: the fold shrinks from the current build's ~336px to **~67123px** (a micro-flick). Piano is the honest exception the user pre-approved: because MiniPiano's C-anchored window makes each keyboard up to 199px, four piano subs form a **2×2 (two rows, ~342px)**, so the piano-with-4-subs fold is **~244px** — still ~90px better than the current build, and only in the corner case where all four sub-rules fire *and* the diagram is piano (many chords yield 23 subs → piano one row → ~91px fold). The residue is absorbed only by the related area's `overflow-y-auto` (instrument + licks never move); a fold-flick is within the standing scroll license, and the user explicitly OK'd more vertical space for the piano. At **1280×960+** guitar/bass/piano-≤3 clear; piano-4-subs still wants a short flick for the related bottom row.
(The `flex-1 min-h-0 overflow-y-auto` absorber already exists — jam-view fit is exact by construction; only the related area, never the instrument/licks, absorbs the residue.)
> **Future option (out of D-75 scope):** the only lever to shrink the piano block further is a **span-anchored** MiniPiano `mini` window (crop to the voicing's actual keys instead of C-boundary octaves) — a MiniPiano code change, option (b), deliberately deferred. Flag for a follow-up task if the piano fold proves annoying in play.
---
## 6. Bounded scopes (disjoint)
- **L-75**`src/components/TryThis.jsx` (rewrite: drop the rotation state/effect + `pickSub`/`advanceOnWrap` + indicator; keep `parseChordName`/`subsForChord`/`pickSubject`; render `subject.subs` as a `flex-wrap` row of SubCards, each with the instrument-following diagram per §2) **+** `src/App.jsx` (add `instrument={instrument}` to the TryThis mount — one line, grep-clean). No smoke coupling (§0). Disjoint from L-76.
- **L-76**`src/components/RelatedProgressions.jsx` **only** (`ul` container `flex flex-col``grid grid-cols-1 sm:grid-cols-2`; `primary.slice(0, 4)` for display; idle/empty states untouched; **no** ranking/scoring/constant change). Disjoint from L-75.
Serialise or worktree — the two locks share no file. No `tailwind.config.js` change (no new colour); no `theory.js` / `piano.js` / `voicings.js` change (resolvers consumed as-is).
---
## 7. Rejected alternatives (≥2)
1. **Keep the rotation AND add a diagram to the single card.** Rejected: the user has seen rotation and explicitly asked for side-by-side ("put them next to each other, we have enough space") — a single card leaves the 744px width the user pointed at mostly empty, and re-litigates a decision the user has already moved past.
2. **One big shared diagram for all subs** (e.g. mark all subs on a single fretboard/piano, or a circle-of-fifths mini). Rejected: the subs differ in root, quality, **and** the right instrument grip; a per-sub diagram is exactly what teaches "play *this* shape instead," and it preserves the tap→modal-per-chord affordance. A merged diagram is unreadable and loses per-chord tapping.
3. **A uniform 2×2 for try-this across all instruments.** Rejected as the *default*: for guitar/bass (75px / no diagram) a 2×2 wastes half the row and is taller than 4-across for no benefit. Piano adopts a 2×2 only because its ~199px keyboards genuinely can't fit 4-across (§3) and the user OK'd more space for it — an instrument-driven adaptation, not a uniform choice.
4. **Cram/shrink the piano keyboards to force 4-across.** Rejected (and the user directly vetoed it, 2026-07-13): the `mini` SVG carries a hard width attr that floors the flex item, so "shrinking" would clip the keyboard; the honest fix is to let piano take a 2×2 and more vertical space. (A genuine width fix = span-anchored MiniPiano window = §5's deferred option b.)
4. **Change `RELATED_MAX_ENTRIES` 5→4 in the ranker for the 2×2.** Rejected: that edits an exported constant + forces a smoke re-pin, pulling L-76 out of "layout only." A component-side `slice(0, 4)` gets the clean grid with zero engine/scoring/test churn.
+196
View File
@@ -0,0 +1,196 @@
# Related-area v2 — always-multi-chord voicings rail + stable 3×3 Try-this (task D-76)
**Sprint:** `sprint-dashboard-polish` · **Owner:** Muse · **Impl tasks:** L-77 (voicings rail: GlanceRail.jsx + JamGuide.jsx) · L-78 (TryThis.jsx). Concept doc only — no code here. Supersedes the relevant parts of `related-area-layout.md` (D-75) that this refines.
**User ask (2026-07-13, verbatim — "one last change then we push everything"):**
> "for the right part 'different voicings' there is currently only one chord visible, we said to show all chords in the loop with the most recent first. at all times we wanna see all different voicings of the different chords. also for the TRY THIS part please always keep the layout the same if it's 2 or 3 chords i want it to stay in place its annoying when the layout changes then u dont know where to look. max it on 3 TRY THIS suggestions, PLUS please add at least 3 ways to play it. i think we have enough space for 3x3 guitar. for piano it can be just one thats okay."
Two independent surfaces:
- **(A) The voicings RAIL** (right column, `JamGuide` `railContent`) must show **multiple chords, most recent first, at all times** — the "only one chord visible" is the no-loop heard-live fallback.
- **(B) TRY THIS** (left column) caps at **3** suggestions, holds a **stable fixed layout** (2-vs-3 subs never shifts position), and gives each suggestion **≥3 ways to play it** — a **3×3** guitar grid, **1** piano keyboard, bass root caption.
---
## 0. Where "only one chord" actually comes from (say it plainly)
`JamGuide` `railContent` (JamGuide.jsx:373-435) has **three** states:
1. `match.matched``<GlanceRail stations={stationVoicings} …/>`**already** shows every loop chord as a vertical row (canonical KB order, playhead highlight, full per-row gallery). This is NOT the bug.
2. `liveChord` (no KB match but a chord is committing, JamGuide.jsx:252) → a **single** `<VoicingBrowser rootPc quality show dense/>` inside a "Heard live · {chord} — every voicing" section (JamGuide.jsx:411-425). **This is the "only one chord."**
3. else → the slim idle line.
So the fix is scoped to state 2 (and the idle-with-history case): replace the single-chord fallback with a **multi-chord, most-recent-first history rail**. State 1 (the loop) already satisfies "all chords of the loop" — the open question is only whether to physically reorder it most-recent-first (§1.3: no, and why).
---
## 1. The voicings rail — always multiple chords, most recent first
### 1.1 Decision: keep GlanceRail-for-loop + a new history fallback — do NOT fully unify
**Recommendation: keep the two paths, replace only the single-chord fallback.**
- **Loop matched**`GlanceRail` as today (canonical order, playhead, per-row gallery, the D-40 voice-leading education). Untouched.
- **No loop** → a **new `HistoryRail`** driven by the recent DISTINCT `chordHistory`, most-recent-first, each rendered as a GlanceRail-style voicing row.
**Why not unify** (always drive the rail from recent-distinct-history, loop adds highlighting): the loop rail's education is *canonical-order-dependent*. `GlanceRail` computes `voiceLeadingPairs` between **canonically adjacent** stations (GlanceRail.jsx:234-241) and renders per-row `TransitionChip`s ("next F→E · ½ step down") plus the wrap chip ("loop") — a voice-leading **wheel**. Reordering those rows most-recent-first would make every "next …" chip point at the wrong neighbour, and the wrap chip lie. Unifying therefore *destroys* the loop education to satisfy a directive the loop already meets another way (§1.3). So: two paths, one shared row idiom, no loss.
This is also the **minimal, lowest-regression** change: `StationRow` (loop) stays byte-identical; the new `HistoryRow`/`HistoryRail` is additive.
### 1.2 The no-loop history rail — data source & most-recent-first
`chordHistory` is already a `JamGuide` prop (JamGuide.jsx:186; App passes it at App.jsx:846) — **no App change needed.** Build the rail entirely from it:
```
recentDistinct(chordHistory, cap = 6):
seen = new Set(); out = []
for name from END of chordHistory backwards: // newest first
parsed = parseChord(name) // voicings.js — same parser JamGuide already imports (line 12)
if (!parsed) continue // unparseable → skip, no crash
if (seen.has(name)) continue // DISTINCT by chord name (subsumes consecutive-dedup)
seen.add(name); out.push({ ...parsed, label: name })
if (out.length === cap) break
return out // out[0] = the chord sounding now
```
**"Most recent first" mapping:** walk `chordHistory` from the tail (the newest commit is `chordHistory[len-1]` = `currentChord`, App.jsx:572). `out[0]` is therefore the current chord, `out[1]` the previous distinct chord, etc. **Distinct-by-name** (not merely consecutive-dedup) so "F Am F Am F" yields `[F, Am]` — the user wants the *different chords*, each once, not a ping-pong; the most-recent occurrence fixes each chord's slot. Cap **6** rows.
Each entry parses to `{ rootPc, type, label }` (voicings.js `parseChord` returns `{ rootPc, type }`). Feed each as a row.
**Honest edges:**
- **1 chord ever played** → 1 row. Unavoidable (there is genuinely one chord) — but it is now a *row in the rail idiom*, not a bespoke single-chord section. Strictly better than today, which also showed one.
- **20 chords** → the 6 most-recent distinct, newest first. Older ones roll off (the rail is a live window, not a log — the KnowledgeDock Voicings section is the browse-everything surface).
- **All same chord** (F F F F) → 1 row.
- **Unparseable name** → skipped; if *nothing* parses → fall through to the existing slim idle line (state 3), unchanged.
### 1.3 What "most recent first" means for the LOOP (honest)
For the loop, `GlanceRail` stays **canonical KB order** and the **playhead** (accent ring + "now" badge + `aria-current`, GlanceRail.jsx:184-188) marks the chord you're on. That IS "most recent, unmistakable" — it is exactly the active-chord-at-a-glance the DoD demands — without reordering. Physically reordering the loop rows most-recent-first is **rejected** (§6.1) because it breaks the voice-leading wheel. If the user, after seeing this, still wants the loop *physically* re-sequenced, that is a follow-up that must first rework/retire the `TransitionChip` education — flag to Maestro, don't silently do it.
### 1.4 The HistoryRail row anatomy (reuse, minus loop chrome)
A new `HistoryRow` (sibling of `StationRow` in GlanceRail.jsx — keep `StationRow` untouched for the loop). Per row, most-recent-first:
- **Header line:** `st.label` (plain bold text — no focus-toggle button; history chords aren't stations, so no fretboard-focus wiring → simpler, and the main Fretboard already follows `currentChord`). `SoloLabel` + `AimDots` **kept** (GlanceRail.jsx exported atoms) — those are *per-chord* guide-tone education, correct for any chord, and give the history rail visual parity with the loop rail. **No** `TransitionChip` (no canonical adjacency), **no** "next" tag.
- **"now" marker on row 0** (the most-recent chord): the same `border-accent bg-accent/10 ring-2 ring-accent` + "now" badge `StationRow` uses for the playhead — so the active chord is unmistakable (DoD). Rows 1-5 recede to the `opacity: 0.85` floor, exactly as inactive loop rows.
- **Gallery — as-is:** `<VoicingBrowser rootPc={st.rootPc} quality={st.type} show={instrument} dense max={4} />`. Guitar ≤4 recommended-first shapes on one line, piano 2×2 mini, **no ▶** — the identical per-row gallery the loop rail uses. `recommended` is **null** (an arbitrary heard chord has no authored KB play), which `VoicingBrowser` already handles (order untouched, no badge).
`HistoryRail` header (the section h4): `Recent chords · newest first — every voicing`, with the one-line microcopy `Following what you play — the newest chord is up top; no repeating loop yet.` (tokens: `bg-panel`, `border-border`, `text-gray-500`).
### 1.5 Bass, no loop
The no-loop bass path today renders `BassGuideRows` with a **single** live station (JamGuide.jsx:404-410). Extend it to the **same recent-distinct stations, most-recent-first**: pass the `recentDistinct` array to `BassGuideRows` with approach suppressed (history is not a loop → no "approach into the next chord" line; reuse the existing `live` gate, which already turns `next` off at BassGuideRows.jsx:557, or add a `history` flag if the "· heard live" header wording should change to "· recent"). Root + fifth per row; row 0 marked "now". This keeps all three instruments honest and multi-chord.
### 1.6 Rail fit (unchanged geometry)
The rail column is 500px with the D-51 margin-hardened interior (~451px worst-case; GlanceRail.jsx:5-13). `HistoryRow` reuses the exact `VoicingBrowser dense max={4}` cell math, so guitar 4-across (374 ≤ 451) and the piano 2×2 pair (442 ≤ 451) fits are **byte-for-byte the loop rail's** — no new fit risk. Up to 6 rows stack vertically inside the column's existing `overflow-y-auto` scroller (JamGuide.jsx:493-497); the user owns the scrollbar (no auto-scroll — GlanceRail.jsx:46-49's law holds).
---
## 2. Try this — max 3, stable 3-slot layout, ≥3 ways to play each
### 2.1 The reshape: from cards-across to rows-of-shapes
Today `TryThis` (TryThis.jsx:171-189) lays subs **side by side** (columns = subs), each `SubCard` carrying **one** diagram. D-76 turns this **90°**: **rows = subs, columns = shapes.** Each sub becomes a **horizontal row**: an identity block (chord chip + tag + why) on the left, and its **≥3 ways to play it** on the right. Three sub-rows stacked = the "3×3" the user pictured (3 subs × 3 guitar shapes).
Cap: `subject.subs.slice(0, 3)` (was up to 4 — TryThis.jsx:160 `subs`). The engine (`suggestSubstitutions`, L-73) and `pickSubject`/`subsForChord`/`parseChordName` are **unchanged** — reactivity preserved: subject still follows `currentChord`, subs recompute per chord (TryThis.jsx:79-90, 152-160). Only the render and the cap change.
### 2.2 The STABLE fixed 3-slot layout (the anti-jump)
**Always render exactly 3 slots**, in order:
```
<div className="flex flex-col gap-2">
{[0,1,2].map(i => subs[i] ? <SubRow sub={subs[i]} …/> : <EmptySlot key={i}/>)}
</div>
```
- A present sub → `SubRow`. An absent one → `EmptySlot`: a **subtle placeholder** that holds the **exact SubRow height** for the current instrument — `rounded-lg border border-dashed border-border/50 bg-transparent` at low opacity, a centred muted `—` (`text-gray-600 text-[11px]`), `aria-hidden`. It reads as "an intentionally empty slot," not as broken, and — critically — the first two rows **never move** whether the chord yields 2 or 3 subs. This is the exact complaint the user raised ("annoying when the layout changes then u dont know where to look"): with fixed slots, sub #1 and sub #2 are always in the same pixel band.
- **Uniform row height per instrument** (not across instruments — the global `instrument` is fixed at any moment, so all 3 slots share one instrument's row height): guitar `min-h-[100px]`, piano `min-h-[72px]`, bass `min-h-[64px]` (§3 math). `EmptySlot` inherits the same `min-h-*`.
Why 3 slots and not "as many as fire": stability is worth a little reserved whitespace. The user explicitly chose predictable position over density here.
### 2.3 SubRow — guitar (the 3×3), piano (1), bass (caption)
Outer row: `flex items-center gap-3 rounded-lg border border-border bg-border/30 p-2 min-h-[…]` (reuses the SubCard token palette — TryThis.jsx:126).
**Left identity block** (`flex flex-col gap-1 shrink-0 w-[180px]`), all instruments:
1. **Chord chip** — the tappable control, reused verbatim from TryThis.jsx:127-134: `button → onChordClick?.(sub.label)`, `rounded-lg border border-border bg-border px-2 py-1 text-sm font-bold text-gray-100 hover:border-accent/50 hover:text-accent focus-visible:ring-2 focus-visible:ring-accent`, `aria-label={`${sub.label} — ${sub.why}`}`. Tap → `ChordDetailModal`. Inline beside it: the **category tag** (`relative`/`borrowed`/`colour`/`V7`) + the `↻` accent glyph for circle categories only (`CIRCLE_CATEGORIES`, TryThis.jsx:48-55 — unchanged rule).
2. **Why**`sub.why`, `text-[11px] leading-snug text-gray-400`, `line-clamp-2` (the identity block is ~180px wide; 2 lines ≈ 50 chars; full text stays on the chip `aria-label` + tap→modal). Wider than the old 152px card, so whys clip less.
**Right "ways to play" block**, by instrument:
| instrument | right block |
|---|---|
| **guitar** | `flex gap-2` of **up to 3** `ChordDiagram size="thumb"` (~75px), from `getGuitarVoicings(sub.label).slice(0, 3)`. Each thumb captioned underneath with its shape name (`text-[9px] text-gray-500` — e.g. "E Barre", "A Barre / 5fr") so the three read as **three genuinely different grips**, not a repeat. **Omit** ChordDiagram's own `label` (the chip names the chord). Fewer than 3 shapes exist (dim/aug, §2.4) → show what exists; the row does not pad with blanks (the shapes left-align, the row height is fixed by `min-h`). |
| **piano** | **one** `MiniPiano size="mini"` (per the user: "for piano it can be just one thats okay"): `<MiniPiano voicing={{ ...pianoVoicing({ rootPc: sub.rootPc, quality: sub.quality }), rootPc: sub.rootPc }} size="mini" />`. Spread `rootPc` back in (the VoicingBrowser.jsx:317-319 caveat) so "R" badges correctly. |
| **bass** | no diagram — `root · {NOTES[sub.rootPc]}` caption (`text-[10px] text-gray-500`), the same honesty call TryThis/BassGuideRows already make (there is no compact bass-chord renderer). |
All diagrams use the established tiers baked into `ChordDiagram`/`MiniPiano` (accent-purple root, gray/light-purple other tones) — **no new colour, no token change.**
### 2.4 Honest empties
- **Fewer than 3 subs** for the chord → the missing slot(s) render `EmptySlot` (§2.2). Position of the present subs is unchanged.
- **A guitar sub with fewer than 3 shapes**: `getGuitarVoicings` returns all placeable shapes — barre forms are always placeable (any root ≤ fret 15). The engine only ever emits **{min, maj, dom7, maj7, add9, maj6, min7, sus4}** (every `mk()` call in theory.js:801-917 — dim/aug are **never** substitution candidates, so they can't appear here). Of those, **maj/min/dom7/maj7/min7/sus4/maj6** carry ≥3 barre shapes → the full 3×3 (voicings.js:10-53, 76-105). The genuine 2-shape case is **add9**: `getGuitarVoicings` returns only 2 barre shapes (E Barre, A Shape) for **9 of 12 roots**, and 3 only for **C/G/D** (which add an open Cadd9/Gadd9/Dadd9, voicings.js:116-121) → that sub-row honestly shows **2** thumbs, `slice(0,3)` simply yielding two. And add9 is **routinely** emitted — Rule C picks add9 for a major-family chord whose maj7 added tone is non-diatonic (e.g. in D major, the V chord A → **Aadd9**), which is common on major-family V-type chords. So a 2-thumb guitar row is a **regular, honest occurrence**, not a rarity; it never crashes and never pads with fakes.
- **No subject** (no key / no loop / atonal) → `pickSubject` returns null → render nothing (TryThis.jsx:157, unchanged).
### 2.5 Reactivity preserved
`pickSubject(loopArr, keyInfo, currentChord)` still chooses the live chord first, then the first loop station that yields subs (TryThis.jsx:79-90). As the progression evolves the subject and its (now ≤3) subs recompute every commit — the user confirmed they want it to evolve with the playing. The only behavioural deltas: **cap 3** and **3 shapes each**.
---
## 3. Space math — honest
**Left column** `flex-1 min-w-0`**744px**, section `p-3` → interior **≈ 720px** (one-screen.md §1; carried from D-75 §3). Footprints from source geometry: `ChordDiagram size="thumb"` = **75×72px** (padL 14 + gridW 55 + padR 6; padT 11 + gridH 55 + padB 6). `MiniPiano size="mini"` = up to **199×38px** (C-anchored window, D-75 §3 — width varies with root, **height is octave-independent 38.4px**).
**Guitar SubRow.** Right block: 3 thumbs = `3·75 + 2·8 = 241px` (+ 9px shape captions → ~84px tall). Left identity 180px + gaps ≈ `180 + 12 + 241 = 433 ≤ 720` — comfortable, ~287px to spare. Row height = max(thumb 72 + caption 12 = 84, chip 22 + why-2-lines 30 = 52) + `p-2` 16 ≈ **~100px** → `min-h-[100px]`. **3 slots** = `3·100 + 2·8 = 316`; block (+ header 20 + `p-3` 24) ≈ **~360px** — fixed, 2 subs or 3.
**Piano SubRow.** Right block: one `mini` keyboard ≤199px wide, 38px tall. `180 + 12 + 199 = 391 ≤ 720`. Row = max(38, 52) + 16 ≈ **~72px** → `min-h-[72px]`. **3 slots** = `3·72 + 16` ≈ 232; block ≈ **~276px**.
**Bass SubRow.** No diagram. Row = 52 + 16 ≈ **~64px** → `min-h-[64px]`. 3 slots ≈ 208; block ≈ **~250px**.
Note the 3×3 guitar block (~360px) is **taller** than D-75's 4-across single row (~221px) — the honest cost of "at least 3 ways to play each," which the user asked for directly.
### One-screen budget @ 1280×900 (usable box ≈ 836px, one-screen.md §4)
Left jam-view stack = instrument view + licks strip + `relatedSlot` (`flex-1 min-h-0 overflow-y-auto` absorber = **new** Try-this + RelatedProgressions 2×2 from L-76); gaps = 3·`gap-3` = 36px.
| instrument | instrument | licks | try-this (new) | related 2×2 | +gaps | **total** | vs 836 |
|---|---|---|---|---|---|---|---|
| **guitar** | 240 | 190 | ~360 (3×3, 3 slots) | ~272 | 36 | **~1098** | overflow **~262px** |
| **piano** | 240 | 190 | ~276 (1 kbd, 3 slots) | ~272 | 36 | **~1014** | overflow **~178px** |
| **bass** | 240 | 190 | ~250 (caption, 3 slots) | ~272 | 36 | **~988** | overflow **~152px** |
**Scroll story (honest):** the instrument view and licks strip stay **pinned** (they are `xl:shrink-0`, JamGuide.jsx:476-481); only the `relatedSlot` — the `flex-1 min-h-0 overflow-y-auto` absorber (JamGuide.jsx:485-489) — scrolls. So the taller 3×3 try-this deepens the fold in the *related area only*: guitar wants a ~262px flick to reach the bottom of the RelatedProgressions grid, piano ~178px, bass ~152px. This is ~139px more than D-75's guitar fold (~123px) — the direct, user-requested trade for 3 grips per sub. Instrument + licks never move; the active chord and the Try-this subjects are always above the fold. At **1280×1080+** guitar clears; piano/bass clear at ~1100. The `overflow-y-auto` absorber makes the fit exact by construction — the residue lands only in the related area, never on the instrument/licks the player watches.
*(The right rail is independent: `HistoryRail`'s ≤6 rows live in the 500px column's own `overflow-y-auto` scroller — they do not affect the left-column budget.)*
---
## 4. Bounded scopes (file-disjoint → parallelisable)
- **L-77 — the voicings rail.** Files: **`src/components/GlanceRail.jsx`** (add `HistoryRow` + exported `HistoryRail`, reusing the `VoicingBrowser dense max={4}` gallery + `SoloLabel`/`AimDots`; `StationRow`/`GlanceRail` for the loop stay byte-identical) **+ `src/components/JamGuide.jsx`** (a `recentDistinct(chordHistory)` memo; the no-loop `railContent` branch → `HistoryRail` for guitar/piano and `BassGuideRows` fed the recent-distinct stations with approach suppressed for bass; the single-`VoicingBrowser` fallback is retired). **No App change** (`chordHistory` already flows in, JamGuide.jsx:186 / App.jsx:846). No `theory.js`/`voicings.js`/`piano.js`/`tailwind.config.js` change (resolvers/tokens consumed as-is).
- **L-78 — Try this.** File: **`src/components/TryThis.jsx` only.** Cap `subs.slice(0,3)`; replace the cards-across body with the 3-slot rows-of-shapes (§2); keep `parseChordName`/`subsForChord`/`pickSubject`. **No App change** (`instrument` already threaded by L-75, App.jsx:864). No engine change (§2.5).
**Disjoint:** L-77 = {GlanceRail.jsx, JamGuide.jsx}; L-78 = {TryThis.jsx}. **Zero file overlap** → they can run in parallel (worktree) or serial, in any order. Neither touches `theory.js`, `voicings.js`, `piano.js`, `App.jsx`, or `tailwind.config.js`. C-70's `VoicingBrowser.jsx` aria fold is disjoint from both.
*(If a future revision wants the history rail and the loop rail to share one component body, that unification is out of D-76 scope — it would re-touch `StationRow` and risk the loop path; keep it a separate task.)*
---
## 5. What does NOT change
- The engine `suggestSubstitutions` and its rules/why-copy (L-73) — untouched; only the display cap (4→3) and per-sub shape count change.
- The loop rail (`GlanceRail`/`StationRow`): canonical order, playhead, voice-leading wheel, focus→fretboard — all byte-identical.
- `VoicingBrowser`, `ChordDiagram`, `MiniPiano`, `pianoVoicing`, `getGuitarVoicings` — consumed as-is.
- Tokens: `bg-panel`, `bg-surface`, `border-border`, `text-accent`/`bg-accent`, the accent ring, the established note-colour tiers. **No new colour, no `tailwind.config.js` edit.**
---
## 6. Rejected alternatives (≥2)
1. **Reorder the LOOP rail most-recent-first (physically re-sequence the rows).** Rejected: `GlanceRail` builds `voiceLeadingPairs` between *canonically adjacent* stations and shows per-row "next F→E · ½ step down" + a "loop" wrap chip (GlanceRail.jsx:118-132, 234-241). Reordering makes every transition chip point at the wrong neighbour and the wrap chip lie — it trades away the loop's whole voice-leading education for a re-sort the playhead highlight already conveys. The current chord is unmistakable *in place* via the "now" ring.
2. **Fully unify: always drive the rail from recent-distinct-history, loop merely overlays highlighting.** Rejected: same casualty — the transition/wrap education is canonical-order-only, and a history-ordered rail can't carry it. Unifying is a larger refactor that *reduces* the loop's teaching value. Two paths sharing one row idiom is smaller and loses nothing.
3. **Keep Try-this side-by-side (columns = subs) and just add 2 more diagrams per card.** Rejected: 3 subs × 3 guitar thumbs across = `3·(3·75) ≈ 675px` of diagrams fighting for a 720px row with no room for chips/whys, and it re-introduces the 2-vs-3 horizontal jump the user hates (cards grow/reflow). Rows = subs, columns = shapes, fixed 3 slots is the stable-position answer.
4. **Let the number of Try-this slots follow the sub count (render 2 rows when 2 subs).** Rejected: that is exactly the "layout changes, you don't know where to look" jump the user called out. Reserving 3 slots with a subtle placeholder costs a little whitespace and buys constant position — the user's explicit priority.
5. **Shrink guitar thumbs to force less height / cram the 3×3.** Rejected: 75px is the established `ChordDiagram thumb` size used everywhere (rail, KC, modal); shrinking it below the shared size fragments the visual language and hurts readability mid-jam. The honest cost of 3 grips per sub is ~140px more fold in the *related area only* (§3) — pinned instrument/licks are unaffected, and the user asked for the 3 grips knowing it takes room.
+219
View File
@@ -0,0 +1,219 @@
# Related progressions — same-style-first (D-72)
Concept doc for **L-72**. Design-only; no code here. Scope is one bounded edit to
`src/components/RelatedProgressions.jsx` (match.js untouched — see §6).
## The user's ask (2026-07-13, verbatim intent)
> "for the related progressions this is good also, but i would also want
> bridge/chorus/modifications in the same style … say i select jam roulette with
> blues, then i want for that progression other options and not necessarily go
> into other styles."
**Chosen scope:** reuse the KB's *existing* same-style progressions. No computed
modifications, no new authored content, no new KB fields. When a style is active
(rolled via Jam Roulette **or** live-detected), the panel leads with the OTHER
progressions of that same style, reframed as variations/sections to try — instead
of jumping to other styles.
The component today already computes a match, ranks every *other* KB progression
by musical proximity, and prints a flat cross-style list. This doc changes only
**how the list is partitioned, floored, ordered, and labelled** once a style is
known. When no style is known, behaviour is unchanged.
---
## 1. How the active style is known — reuse the component's own match
`rankRelatedProgressions(loop)` already calls
`matchLoopToProgression(loop, index)`, whose result is
`{ matched, id, style, rotation, progression }`. **`match.style` IS the active
style** — for both entry points:
- **Jam Roulette:** `rollJam` seeds `detectedProgression = seedableLoop(prog, key)`
(the collapsed canonical form). The L-60 collapsed-form index makes the
component re-match that loop back to the rolled progression → `match.style ==
the rolled style`, `match.id == the rolled progression's id`. That id is already
excluded from `entries` (the `prog.id === match.id` guard), so the surviving
same-style progressions are exactly "other options for the style I rolled."
- **Live detection:** the detected repeating loop is what App passes as
`loop={detectedProgression}`; the same match resolves the live style/id.
**Recommendation — use the internally-computed `match.style`; do NOT add a prop.**
Naming it explicitly: inside `rankRelatedProgressions`, after the existing
`const match = matchLoopToProgression(...)`, take
```
const activeStyle = match.matched ? match.style : null
```
Rejected: threading a `matchedStyle` prop down from App (roulette knows it via
`lastRolledStyleRef`; live detection could expose its own match). It duplicates
state that the component already derives identically from the same `loop`, and
introduces a divergence risk (App's match vs the component's match drifting).
The single source of truth is the loop → its match. Keep it in one place.
**No-match fallback.** When `match.matched === false` (the loop matches no KB
progression — an off-book jam), `activeStyle` is `null`; the panel renders exactly
today's cross-style list (flat, floor `RELATED_SCORE_FLOOR`, existing
annotations). Nothing about the current behaviour changes when no style is locked.
---
## 2. Same-style-first presentation — two sections
When `activeStyle != null`, partition the scored candidates by
`entry.style === activeStyle`:
**Primary — "Try these in {styleLabel}"** (same-style siblings).
All same-style progressions except the one being played, in scorer order (§4),
capped at `RELATED_MAX_ENTRIES` (5). The score floor is **relaxed to 0 for this
section** — a sibling of your own style is never "junk"; it is exactly the "other
options" the user asked for. Styles hold ≤7 progressions, so this shows all of
them (blues → 4 siblings).
**Secondary — "Same changes, other styles"** (cross-style), demoted, small.
Only progressions whose canonical changes are *identical* to the loop
(`sameChanges === true`), capped at **2**, floor kept. This preserves a genuinely
valuable, rare relative — "this exact turnaround also lives in jazz and gospel" —
without "going into other styles" for merely-similar material. If none qualify,
the section is omitted entirely.
**Recommendation: ship both sections (option b).** It honours "not necessarily go
into other styles" (same-style leads and dominates the panel) while not hiding an
exact-match cousin elsewhere. Dropping the secondary later is a one-line change
(don't render it) if the user wants pure same-style — noted as the toggle.
Rejected: a hard same-style-only filter that *never* shows cross-style. It throws
away the exact-match cousin (musically the most useful cross-style pointer we
have) and would also have to special-case the no-match path. Kept only as the
one-line fallback if the user insists on zero cross-style.
---
## 3. The reframe — "bridge/chorus/modifications" with NO new content
Same-style siblings must read as *sections/variations to try*, not a flat list.
We label each with a short **role phrase** derived only from data already in the
KB — comparing the sibling to the active (matched) progression. Fields used:
`mode`, `bars` (summed = the form length), `qualities` (the colour set),
`name`, `level`. No new fields.
`siblingRole(sibling, active)` → a short phrase or `null`, first rule that fires:
1. **mode differs**`"{mode} version"` — minor→`"minor version"`,
major→`"major version"`, else the mode name (`"dorian version"`, …).
2. **same mode, fewer total bars**`"shorter form"`.
3. **same mode, more total bars**`"extended form"`.
4. **same mode & length, a quality the active lacks**`"reharmonized"`.
5. **otherwise**`null` (honest: just the name + level badge, no role line).
The active progression's `mode`/`bars` come from looking the raw KB entry up by
`match.id` in `kbRegistry[activeStyle].progressions` (avoids any collapsed-
projection subtlety; the raw entry is authoritative).
### Concrete — active = blues **Standard 12-bar** (major, 12 bars)
| sibling | mode | bars | role phrase | reads as |
|---|---|---|---|---|
| Quick-change 12-bar | major | 12 | `null` | name + `foundation` (name already says "quick-change") |
| 8-bar blues | major | 8 | **shorter form** | "the compact take" |
| Minor blues | minor | 12 | **minor version** | "the minor cousin" |
| Turnaround cycle | major | 4 | **shorter form** | name already says "Turnaround cycle" |
Every phrase is honest and re-derivable from `mode`/`bars`/`qualities`. Where no
character is derivable (Quick-change: same mode, same length, same all-dom7 colour
set) we print **nothing** beyond the name and level badge — the name carries it.
The two "shorter form"s are fine: their *names* (`8-bar blues`, `Turnaround
cycle`) already distinguish them, and the scorer orders them by proximity (§4).
This is where the "bridge/chorus/modification" feel comes from: the KB already
holds the minor version, the short form, the turnaround, the quick-change — we are
just *reframing existing siblings* with a one-line role, not synthesising sections.
---
## 4. Ranking within same-style — keep the scorer order
The existing scorer still runs over every candidate. Within the same-style group
the `+40 SCORE_SAME_STYLE` term is constant, so it cancels — ordering is driven by
`same changes (+100)``shared transitions``Jaccard`` length`, i.e.
**musical proximity to the loop you're playing.** That is more useful mid-jam than
alphabetical, so:
**Recommendation: keep the scorer sort within same-style. Do NOT re-sort by
level/name.** The closest variation to what your hands are already doing surfaces
first. The only change is relaxing the floor to 0 for this section (§2) so no
sibling is silently dropped for being "only" a distant relative — the user
explicitly wants *all* the style's options.
---
## 5. Edge / empty states
- **Style with only 1 progression** (0 same-style siblings after excluding the
played one). No current style hits this (all have ≥5), but handle it: render an
honest primary line — *"You're on the only {styleLabel} loop in the songbook."*
then fall through to the cross-style secondary (kept at floor). Never pad.
- **Secondary empty** (no exact cross-style cousin) → omit the secondary section
silently; the primary stands alone.
- **No match at all** (`activeStyle == null`) → today's single flat list, unchanged.
- **Instrument-agnostic — confirmed.** `RelatedProgressions` reads only
`progressions` (`degrees`/`qualities`/`rn`/`level`/`name`/`mode`/`bars`), never
the `instruments` cells. It behaves identically under guitar / piano / bass; the
global instrument selector does not touch it.
---
## 6. L-72 change list (RelatedProgressions.jsx only)
`match.js` needs **no change**`matchLoopToProgression` already returns
`{ style, id, progression }`. Reuse it.
In `rankRelatedProgressions`:
1. After computing `match`, derive `const activeStyle = match.matched ? match.style
: null` and look up the raw active progression (`kbRegistry[activeStyle]
?.progressions.find(p => p.id === match.id)`) for its `mode` + summed `bars`.
2. Keep the existing scoring loop. Change the floor test: skip the
`score < RELATED_SCORE_FLOOR → continue` **only when** `style === activeStyle`
(same-style siblings bypass the floor); cross-style keeps the floor.
3. Add a `siblingRole(sibling, active)` helper (§3) and attach `role` to each
same-style entry; leave cross-style entries' existing `annotation` intact.
4. Partition the sorted entries into `primary` (`style === activeStyle`, cap 5)
and `secondary` (`style !== activeStyle && sameChanges`, cap 2). Return
`{ match, activeStyle, activeStyleLabel, primary, secondary }`. Keep
`entries` (= `primary.concat(secondary)`) on the return so any existing
`entries[0]` / `entries.length` reads still resolve during the transition.
When `activeStyle == null`, return today's shape (`primary = entries`,
`secondary = []`) so the render path collapses to the current flat list.
In the render:
5. Two `<section>`-internal blocks: primary headed *"Try these in
{activeStyleLabel}"*, secondary headed *"Same changes, elsewhere"* (rendered
only when non-empty). Same-style rows swap the `annotation` line for the `role`
phrase (omit the line when `role == null`). Reuse the existing `LevelBadge` /
`ChordChain` — no new tokens, no new colours (all within `bg-panel` /
`border-border` / `text-gray-*` / `text-amber`, already in use).
**Smoke pins (C-50, `scripts/smoke.mjs` §8) will shift — re-derive, coordinate
with C-70:**
- Pin (a) collapsed 12-bar in A: top stays **blues/blues-8bar, score 92**
(blues is now the active style; 8-bar is a same-style sibling; the +40 is still
in its score, order unchanged). Its **annotation label changes** from
`'shares I7→V7'` to the role `'shorter form'` — the assertion must be re-pinned.
- Pin (b) iiVI in C: top stays **jazz/jazz-251-minor, score 156** (same-style,
same changes). Its label changes from `'same changes'` to the role
`'minor version'` (mode differs) — re-pin.
- Scores and top ids are stable; only the annotation strings and the return shape
move. Add coverage for the primary/secondary split and the no-match fallback.
### Rejected alternatives (recap)
- **Computed modifications** (synthesise a bridge/chorus by transposing or
reharmonising) — rejected per the user's explicit choice to reuse existing KB
content; also risks inventing non-idiomatic changes we can't vouch for.
- **Hard same-style-only, no cross-style ever** — rejected: loses the exact-match
cousin in another style and complicates the no-match path. Retained only as the
one-line "drop the secondary" toggle if the user later wants zero cross-style.
- **An explicit `matchedStyle` prop from App** — rejected as redundant (§1): the
component derives the same style from the same loop; a prop only adds a
divergence surface.
+170
View File
@@ -0,0 +1,170 @@
# "Try this" — chord-substitution nudge (task D-73)
**Sprint:** `sprint-dashboard-polish` · **Owner:** Muse · **Impl tasks:** L-73 (engine, `theory.js`) + L-74 (UI, new `TryThis.jsx`)
**User ask (2026-07-13, verbatim):** *"imagine we play a simple Am C F then i'd like to have an alternative to that F that would be in the similar style … potentially based on the circle of fifths? i'd like an option that says: 'try this' … i want musicians to learn how they can make the jam more interesting."* Plus the guard-rail: *"we dont have to create something too difficult."*
So this is a **small, curated, learnable nudge** — not a reharmonisation engine. For the chord under the playhead, in the detected key, show 34 alternative chords, each with one plain sentence that *teaches why it works*. Tap a suggestion → the existing `ChordDetailModal` to study it.
> **Not** the existing `getChordSubstitutions` (education.js). That returns **context-free, same-root colour swaps** (`maj → maj7, add9, maj6…`) and never looks at the key. The new engine is **key-aware** and, crucially, **changes the root** (relative sub, secondary dominant) with a *why* framed against the live key. They coexist; the modal keeps its colour-swap grid, the dashboard gets the new nudge.
---
## 1. The reading model — which key/mode the engine trusts
**Recommendation: take the app's `effectiveKey` (`lockedKey ?? keyInfo`) as the single reading. Do not compute both readings at once.**
- `effectiveKey` is `{ root, mode, confidence }`. The **mode disambiguates the i-vs-vi ambiguity** that makes `Am C F` read two ways: if the app committed **A minor**, `F` is `♭VI`; if **C major**, `F` is `IV`. The engine frames the *why* against whichever one is live, and gates the moves that need a specific reading (borrowed `iv` needs a major reading — see Rule B).
- The user can already flip the mode in the key dropdown (the app's intended workflow, per project memory — e.g. A minor → A Dorian). When they do, the *why* copy and the applicable moves change with it. That is the honest way to "see the other framing" — one reading on screen at a time, driven by the user's own mode choice.
- **Edge — no key / atonal / low confidence:** `suggestSubstitutions` returns `[]` when `!keyInfo?.root`. `TryThis` then renders a quiet idle line ("Lock a key to see substitutions") — never a fabricated suggestion. This mirrors `RelatedProgressions`/`CircleOfFifths` idle states.
The worked examples in §4 show **both** readings only so the gate can verify the arithmetic under each; at runtime exactly one is shown.
---
## 2. The curated set — 4 categories, ranked softest → boldest
All rules operate on `{ rootPc, quality }` (a pitch class 011 + a `CHORD_TYPES` key) — the same shape the KB/JamGuide stations already use — and read `keyInfo {root, mode}`. `keyRootPc = noteIndex(keyInfo.root)` (theory.js's own in-module note-name→pc helper, line 133 — **not** match.js's `chordRootPC`, which would make theory.js import from a module that imports it back = circular). Candidates are returned as `{ rootPc, quality, label, why, category }` where `label = NOTES[rootPc] + CHORD_TYPES[quality].suffix`. **Cap the output at 4**, in the order below (softest first, so the glance reads top-down by boldness).
Notation: pc arithmetic is mod 12. `NOTES = [C,C#,D,D#,E,F,F#,G,G#,A,A#,B]` (C=0 … B=11).
### A. Relative / diatonic-third sub — *the softest, most universal*
Swap a chord for the diatonic chord a third away that **shares two of three tones**.
- **major-family chord** (`maj, maj7, maj6, add9`): candidate = `{ (rootPc + 9) % 12, 'min' }` — the **relative minor** (a minor 3rd below). *Shared tones:* the original root and 3rd become the relative's 3rd and 5th.
- **minor-family chord** (`min, min7, min6`): candidate = `{ (rootPc + 3) % 12, 'maj' }` — the **relative major** (a minor 3rd above).
- **Gate:** emit only if the candidate is **diatonic in `keyInfo`** (`getChordsInKey(root,mode)` contains it). This keeps the swap "safe/soft" and never forces an out-of-key relative. (Non-diatonic relatives are out of MVP scope.)
- **Circle tie-in: yes** — the relative minor/major is the circle's *inner ring* (see `CircleOfFifths.jsx`). The *why* may say so.
- **Why template:** `"{cand} is {orig}'s relative {minor|major} — shares {t1} & {t2}. In this key it's the {rn(cand)}: {softer|brighter} pull, same family."`
### B. Borrowed minor colour — *the "blue"/"Creep" move* (conditional)
Major `IV → iv` (same root, major → minor) — lowers the 6th of the key to the ♭6.
- **Gate (strict, honest):** emit **only** when `keyInfo.mode` is **major-ish** AND the chord is the **IV** (`rootPc === (keyRootPc + 5) % 12`) AND quality is major-family. Under a **minor reading it is suppressed** (in A minor, `F` is a diatonic major `♭VI`; `Fm` would be a chromatic `♭vi` with no honest function — we do not fake it).
- Candidate = `{ rootPc, 'min' }`.
- **Circle tie-in: no** — this is a modal borrowing, not a circle step. The *why* must not claim the circle.
- **Why template:** `"Borrow {cand} (the iv) from the parallel minor — {n6}→{nb6} adds that wistful pull home. The 'Creep' move."` where `nb6 = noteName((keyRootPc + 8) % 12, /*preferFlat*/true)` (the ♭6). **Spell it flat** — this is a flatward modal borrow (A→A♭), never the sharp `NOTES[8]='G#'`. (The *ascending* leading tone in Rule D stays sharp — see §3.)
### C. Extension / colour — *same function, more colour*
Keep the root and function; add one diatonically-honest colour tone.
- Pick the extension whose **added tone is diatonic** in `keyInfo` (prefer, in order): major-family → `maj7` if `(rootPc+11)` diatonic, else `add9` if `(rootPc+2)` diatonic, else `maj6`; minor-family → `min7` if `(rootPc+10)` diatonic, else `add9`; `dom7``sus4` (the 9sus-ish suspension). Same root, so `label` = `NOTES[rootPc] + suffix`.
- **Gate:** the chosen added tone must be in `getScale(root,mode)`; if none qualifies, omit category C rather than add a clashing tone.
- **Circle tie-in: no** — vertical colour, not a circle step.
- **Why template:** `"Add the {intervalName} ({addedNote}) — same {rn}, lusher. {addedNote} is the key's own {degreeWord}, so it stays in the family."`
### D. Secondary dominant of the next chord — *the circle move*, boldest (conditional)
Approach the **next loop chord** by its own `V7` — the circle-of-fifths, dominant-direction pull.
- **Gate:** requires `opts.nextRootPc` (the next station's root pc). Candidate = `{ (nextRootPc + 7) % 12, 'dom7' }`. Emit only when a loop/next chord is known and the candidate root ≠ current root.
- **Circle tie-in: yes** — the candidate root is **one wedge clockwise from the next chord** on the circle (its dominant). Its 3rd is the **leading tone** into the next root.
- **Why template:** `"Swap for {cand}, the V7 of {next} — its 3rd ({leadingTone}) leans a half-step into {next}, pulling the loop around. One step clockwise on the circle."`
> **Honest circle summary:** A and D **are** circle relationships (inner ring; dominant step) — name the circle in their copy. B and C are **not** — never claim the circle for them. We do **not** require the D-61 circle widget on the dashboard; the *why* copy carries the lesson.
---
## 3. Worked examples — `Am C F`, both readings (gate: recompute me)
Loop wraps `Am → C → F → Am`. Target = **F** = `{ rootPc: 5, quality: 'maj' }`, tones `{F=5, A=9, C=0}`. Next chord after F = **Am** (`nextRootPc = 9`).
### Reading (i) — **A minor** (`i · III · ♭VI`) → 3 subs (borrowed iv suppressed)
`A-minor scale = {9,11,0,2,4,5,7}` = A B C D E F G. `getChordsInKey(A,minor) = [Am, B°, C, Dm, Em, F, G]`.
| # | Cat | Candidate (pc) | label | Diatonic check | WHY copy |
|---|-----|----------------|-------|----------------|----------|
| A | relative | (5+9)=**2**, min | **Dm** | Dm ∈ A-min = `iv` ✓ | "Dm is F's relative minor — shares **F & A**. In A minor it's the **iv**: a darker, more grounded step than the bright ♭VI. (Circle: F's inner-ring relative.)" |
| B | borrowed | — | — | mode = minor → **suppressed** | *(not shown — F is ♭VI here, not IV; Fm would be chromatic. Honest omission.)* |
| C | extension | 5, add 11→**E(4)** | **Fmaj7** | E ∈ A-min (the 5th) ✓ | "Add the major 7th (**E**) — ♭VI becomes Fmaj7, dreamy and floating. E is A minor's own 5th, so it stays in the family." |
| D | 2nd-dom | (9+7)=**4**, dom7 | **E7** | leads to Am | "Swap for **E7**, the V7 of Am — its 3rd (**G♯**) leans a half-step into A, pulling the loop back around. One step clockwise on the circle." |
*Arithmetic:* Dm={2,5,9}∩F{5,9,0}={5,9}=F,A ✓. Fmaj7={5,9,0,4}, all ∈ A-min ✓. E7={4,8,11,2}; G♯=8→A=9 ✓; E is a fifth above A (9+7=4) ✓.
### Reading (ii) — **C major** (`vi · I · IV`) → 4 subs (cap)
`C-major scale = {0,2,4,5,7,9,11}` = C D E F G A B. `getChordsInKey(C,major) = [C, Dm, Em, F, G, Am, B°]`.
| # | Cat | Candidate (pc) | label | Diatonic check | WHY copy |
|---|-----|----------------|-------|----------------|----------|
| A | relative | (5+9)=**2**, min | **Dm** | Dm ∈ C-maj = `ii` ✓ | "Dm is F's relative minor — shares **F & A**. In C it's the **ii**: trades IV's brightness for a softer, more forward pull. (Circle: F's inner-ring relative.)" |
| B | borrowed | 5, **min** | **Fm** | mode major **and** F = IV (0+5=5) ✓ | "Borrow **Fm** (the iv) from C minor — lowering A to **A♭** adds that wistful 'Creep' pull home. The classic blue move." |
| C | extension | 5, add 11→**E(4)** | **Fmaj7** | E ∈ C-maj (the 3rd) ✓ | "Add the major 7th (**E**) — same IV, lusher and static. E is C's own 3rd (the mediant), so it glues the chord to the key." |
| D | 2nd-dom | (9+7)=**4**, dom7 | **E7** | leads to Am | "Swap for **E7**, the V7 of Am — its 3rd (**G♯**) leans into A, pulling the loop around. One step clockwise on the circle." |
*Arithmetic:* Fm={5,8,0}; A(9)→A♭(8) ✓; A♭=8=(0+8)=♭6 of C ✓. Everything else as above.
**Payoff:** the *same* candidate chord (Dm, Fmaj7, E7) is right under both readings — only its role-name and *why* change with the mode. Borrowed `Fm` appears **only** under the major reading. That is the honesty the feature promises.
**Bonus — the same rules over the whole loop** (feeds the smoke truth-table): current **Am**→next C ⇒ D = **G7** (V7/C, B→C); current **C**→next F ⇒ D = **C7** (V7/F, E→F — the classic bluesy `I7→IV`). Both musically gold, both from the one rule.
---
## 4. Which chord gets suggestions — the playhead chord
**Decision: one `TryThis` card that follows the playhead — subs for the *currently sounding* chord, updated as the loop turns.**
- Rejected: one static sub for the whole loop (misses the point — the user asked specifically about *F*), and a per-station sub grid across the rail (too dense, collides with the rail — see §6).
- Target selection: `currentChord` when present → fall back to the committed loop's active/first station when silent → else idle. `opts.nextRootPc` = the following loop station's root (so Rule D can fire); when there is no loop, D is simply omitted.
- Keep it tiny: **≤4 chips, one row.** It is a nudge, not a panel.
- *(Optional nicety, not required):* the UI may drop a candidate that is already a loop chord (e.g. relative of Am = C, which is already in `Am C F`) to avoid a redundant suggestion. Engine stays pure; dedup lives in `TryThis`.
---
## 5. The UI surface — new `TryThis.jsx`, left column
A compact card, visually a sibling of `RelatedProgressions`/`CircleOfFifths` (same micro-header + chip language):
```
Try this instead of F · in A minor ← text-[10px] uppercase tracking-widest text-gray-500
[ Dm ] relative minor — softer, same family ← chip + one-line why, per row
[ Fmaj7 ] add the maj7 (E) — dreamy, in-key
[ E7 ] V7 of Am — pulls the loop around ↻
```
- **Chip = tappable**`onChordClick(label)` = App's `setSelectedChord``ChordDetailModal` (the established tap target; reuse verbatim). Each chip is a `<button>`, keyboard-reachable, `focus-visible:ring-2 focus-visible:ring-accent`.
- **Layout:** chip on the left (bold, `text-gray-100`), *why* to the right (`text-[11px] text-gray-400`), category label optional as a faint tag. `Category D` gets a small `↻` glyph hinting the circle (no widget dependency).
- **Tokens only** (`tailwind.config.js`): `bg-panel`, `border-border`, `text-accent`, `text-gray-100/400/500`, `hover:border-accent/50 hover:text-accent`. **No new colour** — nothing to flag to Maestro. Accent-on-panel meets AA (same usage cleared in D-61).
- **Mount — App.jsx only (file-disjoint from the rail/licks/related chains):** compose `TryThis` **above** `RelatedProgressions` inside App's existing `relatedSlot` prop:
```jsx
relatedSlot={
<div className="flex flex-col gap-3">
<TryThis
chord={currentChord} {/* App parses to {rootPc,quality} */}
nextRootPc={/* next station root of the committed loop, or undefined */}
keyInfo={effectiveKey}
onChordClick={setSelectedChord}
/>
<RelatedProgressions loop={detectedProgression} keyInfo={effectiveKey} onChordClick={setSelectedChord} />
</div>
}
```
This edits **App.jsx only** (mount) + the new file — it does **not** touch `JamGuide.jsx` (locked by L-71), `GlanceRail/VoicingBrowser/index.css` (L-70), or `RelatedProgressions.jsx` (L-72). The left column already reflows to one-per-row narrow (JamGuide `order-4` wrapper); `TryThis` inherits that. Glanceable in the ≤4-chip footprint at 1280×900 and stacks cleanly narrow.
---
## 6. Circle-of-fifths tie-in — honest
- **Rule A (relative)** and **Rule D (secondary dominant)** ARE circle relationships — the inner ring and the clockwise/dominant step respectively (both visible in `CircleOfFifths.jsx`). Their *why* copy names the circle.
- **Rule B (borrowed iv)** and **Rule C (extension)** are **not** circle-adjacent — modal/vertical colour. Their copy must **never** invoke the circle.
- We **do not** require the D-61 circle widget on the dashboard (it lives in the Knowledge Center). The lesson travels entirely in the one-line *why*. Optional future polish: a tiny `↻` affordance on circle-derived chips.
---
## 7. Impl scopes (bounded)
### L-73 — engine (`src/lib/theory.js`, additive; `scripts/smoke.mjs`)
- Add `export function suggestSubstitutions({ rootPc, quality }, keyInfo, opts = {})``[{ rootPc, quality, label, why, category }]`, categories in order `relative, borrowed, extension, secondary_dominant`, capped at 4, `[]` when `!keyInfo?.root`. Reuse `NOTES`, `NOTES_FLAT`, `noteName`, `noteIndex`, `CHORD_TYPES`, `getChordsInKey`, `getScale`, `getChordTones`, `intervalName`, `toRomanNumeral` — all **in-module** to theory.js (do **not** import `chordRootPC` from match.js — circular). **Never re-derive** intervals or diatonic sets. `opts.nextRootPc` gates Rule D.
- **Smoke truth-table** in `smoke.mjs` (sabotage-proven, like the `resolveDegree` guard): pin the §3 tables — `F/maj` in **A minor**`[Dm, Fmaj7, E7]` (no Fm); in **C major**`[Dm, Fm, Fmaj7, E7]`; plus `Am/min`→next C ⇒ D=`G7`, `C/maj`→next F ⇒ D=`C7`; and a no-key case → `[]`. Flip one rule constant → smoke must go red.
- **⚠ Sequencing flag for Maestro:** L-73 and **L-72 both lock `scripts/smoke.mjs`** — they cannot be claimed concurrently. Serialize them (L-73 appends a new smoke section to minimise merge friction). `theory.js` is the shared Professor+Luthier file → single-task lock + Critic + non-owning-domain review, per PROTOCOL §3.
### L-74 — UI (`src/components/TryThis.jsx` new; `src/App.jsx` mount)
- Pure/presentational component consuming `suggestSubstitutions`; props `{ chord, nextRootPc?, keyInfo, onChordClick }`; renders header + ≤4 chip/why rows; tap → `onChordClick`. Idle line when the engine returns `[]`.
- Mount per §5 (App composes it into `relatedSlot` above `RelatedProgressions`). **Files disjoint** from L-70/L-71/L-72; App.jsx is unlocked by all three. Audio contract untouched (mount/UI-state only — the App.jsx grep gate applies).
---
## 8. Rejected alternatives (≥2)
1. **Full reharmonisation engine** (chord-scale subs, iiV insertion, Coltrane changes, tritone-on-everything). **Rejected** per the user's explicit *"we dont have to create something too difficult"* + "not a reharm engine." Un-glanceable mid-jam and un-learnable. The curated 4-move set is the whole point.
2. **Blanket tritone sub** (`root+6` dom7 on every chord). **Rejected as a general rule:** the tritone sub is only functionally honest on a *dominant resolving down a fifth*; on a static major IV like `F` it yields `B7` — jarring, no diatonic footing, no *why* that teaches. The **secondary-dominant** move (Rule D) captures the same circle-of-fifths energy but is functionally grounded in the *actual next chord*. (Tritone could return later as a dom7-only opt-in.)
3. **Per-station subs plastered across the voicings rail.** **Rejected:** clutters the glance-critical rail (owned by L-70), 34 chips × N stations is too dense, and it competes with the voicings the user is reading to *play*. One playhead-following card is the nudge.
4. **Show both key readings at once.** **Rejected:** doubles the surface, contradicts "keep it small," and the app already commits to one `effectiveKey` (the mode disambiguates). The user flips the mode dropdown to see the other framing — one reading on screen at a time.
</content>
</invoke>
+71
View File
@@ -0,0 +1,71 @@
# KB Expansion Backlog
The queue for the `/kb-expand` loop. One cell per session, top-to-bottom. Protocol and schema: [`docs/kb-plan.md`](kb-plan.md). Statuses: `todo``in-progress``done (YYYY-MM-DD, coverage)`.
> Ground truth (verified 2026-07-10): `node scripts/validate-kb.mjs` → ✓ KB valid — **10 style(s), 56 progressions, 164 plays, 23 licks**. Registered cells in `src/data/kb/index.js`: all 10 guitar; piano for jazz, blues, gospel, rnb.
>
> **Next cells:** piano column continues (pop, rock, funk, country, reggae, bossa remain) · **bass column is now active** — blues bass is next (ledger task P-41, pending the C-41 bass play schema), order blues → jazz → funk per plan.
## Phase 0 — Foundation (must be first)
| # | Cell | Status |
|---|---|---|
| 0 | Bootstrap: `src/data/kb/` + `SCHEMA.md` + `scripts/validate-kb.mjs` + `kb/index.js` + **jazz/guitar gold standard** | done (2026-06-12, iteration 1) |
## Guitar
| # | Style | Status |
|---|---|---|
| 1 | Jazz (part of bootstrap) | done (2026-06-12, 5 progressions × 2 plays; +2 intermediate progressions 2026-07-08 → 7 × 2, validator ✓) |
| 2 | Blues | done (2026-06-12, 5 progressions × 2 plays, validator ✓) |
| 3 | Rock | done (2026-06-12, 5 progressions × 2 plays, validator ✓) |
| 4 | Bossa Nova | done (2026-06-12, 5 progressions × 2 plays, validator ✓) |
| 5 | Funk | done (2026-06-12, 5 progressions × 2 plays, validator ✓) |
| 6 | Reggae | done (2026-06-12, 5 progressions × 2 plays, validator ✓) |
| 7 | Country / Folk | done (2026-06-12, 5 progressions × 2 plays, validator ✓) |
| 8 | R&B / Neo-soul | done (2026-06-12, 5 progressions × 2 plays; +2 intermediate progressions 2026-07-08 → 7 × 2, validator ✓) |
| 9 | Gospel | done (2026-06-15, 5 progressions × 2 plays; +2 intermediate progressions 2026-07-08 → 7 × 2, validator ✓) |
| 10 | Pop | done (2026-06-15, 5 progressions × 2 plays, validator ✓) |
> Guitar licks (not tracked as cells above; C-20 lick schema, 2026-07-08): 23 licks live in 6 guitar cells — blues 4, jazz 4, funk 4 (pack #1, 2026-07-08) + rock 4, country 4, reggae 3 (pack #2, 2026-07-08/09).
## Piano
| # | Style | Status |
|---|---|---|
| 11 | Jazz | done (2026-07-08, 7 progressions × 2 plays, validator ✓) |
| 12 | Blues | done (2026-07-10, 5 progressions × 2 plays, validator ✓) |
| 13 | Bossa Nova | todo |
| 14 | Gospel | done (2026-07-09, 7 progressions × 2 plays, validator ✓) |
| 15 | R&B / Neo-soul | done (2026-07-10, 7 progressions × 2 plays, validator ✓) |
| 16 | Pop | todo — **next piano cell** |
| 17 | Rock | todo |
| 18 | Funk | todo |
| 19 | Country / Folk | todo |
| 20 | Reggae | todo |
## Bass
| # | Style | Status |
|---|---|---|
| 21 | Blues | todo — **next bass cell** (ledger task P-41; blocked on the C-41 bass play schema) |
| 22 | Jazz | todo |
| 23 | Funk | todo |
| 24 | Reggae | todo |
| 25 | Rock | todo |
| 26 | Bossa Nova | todo |
| 27 | R&B / Neo-soul | todo |
| 28 | Country / Folk | todo |
| 29 | Gospel | todo |
| 30 | Pop | todo |
## UI milestones (interleave when their data exists)
| Milestone | Depends on | Status |
|---|---|---|
| Jam Guide MVP (panel, matching, `ChordDiagram.jsx`, live sync) | cell 0 | done (2026-06-15, sprint-jam-guide, PR #2) |
| `MiniPiano.jsx` + recipe resolver | cell 11 | done (2026-06-16 resolver + MiniPiano voicing prop; authored packs render at stations 2026-07-09) |
| Bass pattern renderer | cell 21 | todo — activated in sprint-integrated-glance (ledger task L-42, after C-41 + P-41) |
| Improv layer (licks/tabs display) | a few guitar cells | done (2026-07-08, `LickCard.jsx` + licks section; 23 licks across 6 styles) |
> Notes for sessions: piano style order front-loaded the styles where piano voicings differ most (jazz/gospel/neo-soul — all shipped, plus blues); bass order front-loads line-driven styles (blues/jazz/funk). Adjust freely — order is a default, not a rule. Bass cells need the C-41 play schema in `SCHEMA.md` before authoring.
+223
View File
@@ -0,0 +1,223 @@
# Knowledgebase Plan — Styles × Instruments × Progressions × Voicings
The plan for building JamBuddy's **jam knowledgebase**: an intermediate guide to the standard progressions of each style (Jazz, Blues, Rock, Bossa Nova, …) and the different ways to *play* them per instrument (guitar first, then piano, then bass) — expandable one session at a time via a repeatable loop, and rendered live in a large **Jam Guide** panel at the bottom of the app.
Three principles drive everything:
1. **Key-agnostic data.** Everything is stored as scale degrees and movable shapes, never absolute chords. The app detects the key; one KB entry renders in all 12 keys. This is the same convention `PROGRESSIONS.degrees` and the movable shapes in `voicings.js` already use.
2. **Machine-verifiable quality.** A validator proves every voicing actually contains the chord's tones before content lands. That's what makes agent-generated content trustworthy over many loop iterations.
3. **One bounded cell per session.** Each expansion session completes exactly one style × instrument cell (researched, authored, validated, committed). Small enough to review, big enough to matter.
---
## 1. Architecture
```
src/data/kb/
index.js — registry aggregating all styles (UI reads only this)
SCHEMA.md — the authoring contract (formats below, with one full example)
jazz/
meta.js — { id, label, feel, tempoRange, character }
progressions.js — the style's standard progressions (instrument-independent)
guitar.js — guitar pack: plays + comping + improv
piano.js — piano pack
bass.js — bass pack
blues/ … — same shape per style
scripts/
validate-kb.mjs — quality gate, run with `node scripts/validate-kb.mjs`
docs/
kb-backlog.md — the cell matrix with statuses (the loop's queue)
```
`index.js` imports whatever style folders exist — the Jam Guide's style tabs grow automatically as the loop fills cells. A style is usable for one instrument before the others exist (guitar-first rollout).
### Progression entry (per style)
```js
// kb/jazz/progressions.js
export default [
{
id: 'jazz-251-major',
name: 'iiVI',
rn: ['ii7', 'V7', 'Imaj7'],
degrees: [2, 7, 0], // semitone offsets from key root
qualities: ['min7', 'dom7', 'maj7'], // keys of CHORD_TYPES in theory.js
bars: [1, 1, 2],
mode: 'major',
songs: ['Autumn Leaves', 'All The Things You Are'],
tip: 'The 7th of each chord resolves down a half-step to the 3rd of the next.',
},
// … 4-8 progressions per style (see docs/progression-repertoire.md §1 for the lists)
]
```
### Instrument pack — guitar
```js
// kb/jazz/guitar.js
export default {
styleIntro: '2-3 sentences on the guitarist's role in this style.',
comping: [{ label: 'Four-to-the-bar (Freddie Green)', rhythm: '♩ ♩ ♩ ♩', description: '…' }],
plays: {
'jazz-251-major': [ // ≥2 "ways to play" per progression
{
label: 'Shell voicings',
level: 'intermediate',
chords: [ // one entry per progression step
{ shape: { rootStr: 5, offsets: ['x', 0, 'x', 0, 1, 'x'], fingers: [0,1,0,2,3,0] },
note: 'root–♭7–♭3' },
// …
],
tips: 'Stay light; the 3rds and 7ths do all the work.',
},
{ label: 'Drop-2 on top four strings', /* … */ },
],
},
improv: {
scales: [{ over: 'ii7', scale: 'dorian', why: '…' }],
targetNotes: 'Land the 3rd of each chord on beat 1.',
licks: [{ tab: 'e|---…', description: '…', over: 'jazz-251-major' }],
},
}
```
**Shape format** follows the existing `voicings.js` convention so the renderer is shared: movable shapes use `rootStr` + `offsets` relative to the root fret (renders in any key); open shapes use absolute `frets` + `onlyRoot` (pitch class) and only render when the key matches. Strings are arrays of 6, low-E first, `'x'` = muted.
### Instrument pack — piano
Voicings are **interval recipes** resolved per chord quality (no fingering data needed):
```js
plays: {
'jazz-251-major': [
{
label: 'Rootless A/B alternation',
level: 'intermediate',
chords: [
{ recipe: { LH: ['3', '5', '7', '9'] }, note: 'Type A' }, // ii7
{ recipe: { LH: ['7', '9', '3', '13'] }, note: 'Type B' }, // V7
{ recipe: { LH: ['3', '5', '7', '9'] }, note: 'Type A' }, // Imaj7
],
register: 'top note between C4 and C5',
tips: 'Alternate types so inner voices barely move.',
},
],
}
```
Degrees are chord-degree strings (`'1' '3' 'b7' '9' '13'`); the resolver maps them through the chord quality's intervals (which `theory.js` chord templates already encode).
### Instrument pack — bass
Line patterns per progression step, in degrees plus approach annotations:
```js
plays: {
'blues-12bar': [
{
label: 'Walking, chromatic approach',
level: 'intermediate',
bars: [{ beats: ['R', '3', '5', 'chrom→next'] } /* … per bar */],
tips: 'Beat 1 is always the new root; beat 4 walks into it.',
},
],
}
```
---
## 2. Quality gates
### Mechanical — `scripts/validate-kb.mjs` (must pass before any commit)
- ids unique; every `plays` key references an existing progression id; `chords`/`bars` length matches the progression length
- `degrees` ∈ 011; `qualities` are keys of `CHORD_TYPES`; `mode` is a known mode
- guitar shapes: 6 entries per array, frets 015, **fret span ≤ 4** (intermediate hands), and — the strong check — the shape's computed pitch classes (standard tuning EADGBE) must contain the chord's root and defining tones (3rd/7th or quality equivalent) and contain **no out-of-chord tones**
- piano recipes: every degree resolvable for that chord quality
- coverage per cell: ≥ 4 progressions, ≥ 2 plays per progression, improv section present (guitar/piano), styleIntro present
### Musician checklist (human/agent self-review, in SCHEMA.md)
- Are the plays *idiomatically different* (register, density, difficulty), not just transpositions of each other?
- Is each play genuinely intermediate — no 5-fret stretches, no 2-octave rootless clusters?
- Does the style actually sound like the style (bossa ≠ jazz with different labels: distinct rhythm descriptions)?
- Do tips teach a *transferable* idea (voice leading, register, space), not just "play this"?
---
## 3. The expansion loop
### The queue
`docs/kb-backlog.md` holds the matrix of cells with statuses (`todo` / `in-progress` / `done` + date + coverage). Order: **all guitar cells first** (most voicing complexity — it sets the quality bar), then piano, then bass. Style priority within each instrument: jazz → blues → rock → bossa → funk → reggae → country/folk → R&B/neo-soul → gospel → pop.
### The session protocol (encoded as the `/kb-expand` project skill)
Each session:
1. **Orient** — read this plan, `SCHEMA.md`, the backlog, and the gold-standard cell (`kb/jazz/guitar.js`, the first one built).
2. **Claim** — take the first `todo` cell, mark it `in-progress`.
3. **Research** — dispatch web-research agent(s) for that style × instrument: the style's standard progressions (cross-check against `docs/progression-repertoire.md`), the 2-3 idiomatic intermediate ways to play each, comping rhythms, improv approach. Named sources required.
4. **Author** — write `progressions.js` (if the style is new) and the instrument pack, conforming to SCHEMA.md.
5. **Validate** — run `node scripts/validate-kb.mjs`; fix until green; run the musician checklist.
6. **Integrate** — register the style in `kb/index.js`; `npm run build` must pass.
7. **Record** — mark the cell `done` with date + coverage stats in the backlog; commit (`kb: add <style> <instrument> pack`).
8. **Report** — summarize what was added and name the next cell.
**Session 0 (bootstrap):** if `src/data/kb/`, `SCHEMA.md`, or the validator don't exist yet, the first session builds them *plus* the jazz/guitar gold-standard cell. Every later session imitates that exemplar.
### How to run it
- One session: type **`/kb-expand`** — does exactly one cell.
- Several in a row: `/loop /kb-expand` and let it self-pace, or run `/kb-expand` whenever there's time.
- Review cadence: cells are individual commits on a branch — review/merge per instrument tranche if preferred.
30 cells ≈ 30 short sessions; guitar's 10 cells deliver user-visible value immediately because the Jam Guide reads whatever exists.
---
## 4. The Jam Guide panel (UI)
A large panel at the **bottom of the main scroll** — while jamming you scroll down and the current progression's playbook is laid out to fit the screen.
```
┌─ JAM GUIDE ─────────────────────────────── [Guitar|Piano|Bass] [Jazz][Blues][Rock][Bossa]… ─┐
│ Matched: iiVI in G major your loop: Am7 → D7 → Gmaj7 │
│ │
│ Am7 (ii7) D7 (V7) Gmaj7 (Imaj7) │
│ ▼ playing now │
│ Shells [diagram] [diagram] [diagram] root37, four-to-the-bar │
│ Drop-2 [diagram] [diagram] [diagram] top-4 strings, stays high │
│ Triads 1-3 [diagram] [diagram] [diagram] fills between vocal lines │
│ ───────────────────────────────────────────────────────────────────────────── │
│ IMPROV D dorian → G mixo → G major · target the 3rds: C → F# → B · lick ▸ tab… │
└──────────────────────────────────────────────────────────────────────────────────────────────┘
```
- **Component:** `JamGuide.jsx`, mounted last in `App.jsx`; collapsed header always visible, expands to ~70vh.
- **Inputs:** `keyInfo`, `detectedProgression`, `currentChord` — plus instrument + style selection (persisted in settings; style tabs are generated from `kb/index.js`, so the panel grows as the loop runs).
- **Matching:** convert the detected loop to degrees relative to the key root, match against the selected style's progressions **rotation-invariantly** (same canonicalization idea as `detectRepeatingProgression`). No match → fallback: per-chord voicing alternatives from `voicings.js`, so the panel is never empty.
- **Live sync:** the active chord column highlights using the loop-position logic in `ProgressionBanner.jsx` (`findLoopPosition` — extract it to a shared util). The player reads the *next* voicing in time, in rhythm with the band.
- **Diagrams:** new small renderers — `ChordDiagram.jsx` (6-string × 5-fret SVG grid, consumes the shape format), `MiniPiano.jsx` (~2-octave SVG, highlights resolved recipe notes), bass patterns as degree badges (R · 3 · 5 · ♭7) over a mini string diagram. Reuse design tokens (`bg-panel`, `border-border`, accent purple for chord tones).
- **Smart fit:** CSS grid — columns = progression chords (46), rows = plays; rows beyond what fits collapse behind "more ways ▾"; diagrams scale to column width; on narrow windows the grid flips to one play per row, chords scrolling horizontally.
- **Key-aware rendering:** movable shapes get their fret position computed from the detected key; open shapes appear only when the chord's root matches; piano recipes resolve through the chord quality. All 12 keys for free, per principle 1.
---
## 5. Phases
| Phase | What | Outcome |
|---|---|---|
| 0 | Foundation: `kb/` dirs, `SCHEMA.md`, validator, backlog, `/kb-expand` skill, jazz/guitar gold standard | The loop exists and has an exemplar |
| 1 | Jam Guide MVP: panel + matching + guitar `ChordDiagram` + live sync | jazz/guitar visible in the app while jamming |
| 2 | Loop guitar cells: blues, rock, bossa, funk, reggae, country, R&B, gospel, pop | Full guitar guide across styles |
| 3 | Piano: `MiniPiano` renderer + recipe resolver, loop piano cells | Second instrument live |
| 4 | Bass: pattern renderer, loop bass cells | Third instrument live |
| 5 | Polish: improv layer with tabs/licks, Progression Builder integration (GOAL G3), ToneGym-style tap-to-hear | Guide ↔ Builder round-trip |
### Success criteria
- During a jam, scrolling to the Jam Guide shows ≥ 3 ways to play the detected progression on the selected instrument, in the detected key, with the active chord highlighted in time.
- `/kb-expand` completes a cell in one session with the validator green, no hand-holding.
- A new style added by the loop appears in the UI with **zero code changes** (data + registry only).
- An intermediate player can switch Jazz → Bossa over the same iiVI and see *genuinely different* voicings and rhythm guidance.
+129
View File
@@ -0,0 +1,129 @@
# Learn Curriculum — Intermediate, Jam-Ready Players
Research-backed training repertoire for the Learn section. Companion to [`GOAL.md`](../GOAL.md) Part 2. Audience: players who know the basics and can survive a jam — the goal is making them better *in* the jam. Not beginner material.
Across guitar, piano, and bass pedagogy the intermediate→advanced jump converges on four pillars: **instrument liberation** (play anything anywhere), **playing the changes** (chord-tone awareness), **ensemble skills** (space, register, pocket), and **functional ears** (hearing 1-5-6-4). The per-instrument curricula below feed both the Learn UI and the knowledgebase (see `docs/kb-plan.md`).
---
## Guitar
### Skill taxonomy (rough order)
**Tier A — Fretboard liberation**
1. CAGED system fluency — locate any chord in 5 places instantly (Fretboard Logic, Pickup Music)
2. Triads on string sets — major/minor triads + inversions on strings 1-3, 2-4, 3-5 (Justin Guitar Grade 5, Leavitt Vol. 2)
3. Connecting pentatonic boxes — the box 2↔3 seam is the documented weak point
4. Scale-over-chord mapping — seeing the chord *inside* the scale shape
**Tier B — Playing the changes**
5. Chord-tone / target-note soloing — land on a chord tone on beat 1 of each change
6. Guide tones (3rds & 7ths) — the 7th of one chord resolves to the 3rd of the next
7. Phrasing across positions
**Tier C — Ensemble skills**
8. Comping with small triad voicings — stay out of the vocalist's/keys' register
9. Internal time — metronome on beats 2 & 4, then no click (Tomo Fujita's core emphasis)
10. Ear-led playing — "let your ears lead you instead of your eyes" (Fujita)
**Tier D — Functional ears**
11. Progression recognition by ear — track the bass line first
12. Modal awareness — how Dorian/Mixolydian overlap shapes you already know
13. Transcribing & daily riff-writing — the recurring plateau fix
### Top drills
1. **Triad voice-leading over 12-bar blues** — only close triads on one string set; on every change move each finger to the *nearest* note of the next triad. Forces inversions + minimal-motion voice leading at once.
2. **One-CAGED-position soloing** — improvise using only one grip's chord tones + surrounding scale notes; shift position each chorus. Welds chord, arpeggio, and scale into one visual unit.
3. **Target-note drill** — first note after each chord change must be the 3rd (then 7ths, then 7th→3rd resolutions); pentatonic filler in between. Pure pentatonic playing suddenly "follows the changes".
4. **Pentatonic seam drill** — ascend box 1, exit through a named seam note into box 2, etc. Shifts become melodic destinations.
5. **Metronome on 2 & 4** — click as the snare backbeat; progress to click once per bar, then none.
6. **Comping ladder** — comp behind a recorded soloist using only 3-string triads above fret 5, varying rhythm/dynamics, never register-clashing.
7. **Daily progression dictation** — 10-15 min naming I-IV-V vs vi-IV-I-V vs ii-V-I from songs, bass line first.
### Sources
Fretboard Logic (Bill Edwards) · Justin Guitar Grades 46 · Tomo Fujita *Accelerate Your Guitar Playing* (Berklee) · Leavitt *A Modern Method for Guitar* Vol. 2 · Absolutely Understand Guitar · Pickup Music CAGED pathway · fundamental-changes.com (guide tones) · TrueFire (box connection, plateaus) · Premier Guitar "Rhythm Rules" · zotzinguitarlessons.com (triads in 12 keys) · ToneGym / tonedear.com · stringshock.com & jazzguitartoday.com (jam etiquette)
---
## Piano / Keys
### Skill taxonomy (rough order)
**Tier 1 — Harmonic vocabulary**
1. Triad inversions in all 12 keys — grab any chord near the current hand position
2. Voice leading — minimum-distance inversion choice; the biggest "amateur → pro" jump
3. Shell voicings (root37) — light, clear, gateway to comping (Open Studio, PianoGroove)
4. Sus2/sus4/add9 colors and slash chords — pop/worship vocabulary
5. Rootless voicings — Type A (3-5-7-9), Type B (7-9-3-5); top note between C4C5
**Tier 2 — Rhythm & ensemble role**
6. Comping rhythms — Charleston, reverse Charleston, Red Garland pattern, anticipations
7. Register discipline — LH stays above ~G3 when a bassist is present
8. Density discipline ("rule of 1") — in a 5-piece band, play 1/5 of the music
9. Hand-role splitting — LH harmony/groove anchor, RH color and answers
**Tier 3 — Functional/ear skills**
10. Thinking in numbers (Nashville Number System / Roman numerals)
11. Progression recognition by ear — bass line + emotional flow of each degree
12. Transposition fluency — known songs in all 12 keys via the number method
13. Sight-comping — realize an unfamiliar lead sheet at tempo (Berklee keyboard method)
**Tier 4 — Bandstand**
14. Form-keeping under pressure — never lose bar 1
15. Improvising over changes — chord tones → pentatonics → scale tones
16. Repertoire in 2-3 keys from memory
### Top drills
1. **Voice-led progression loop in 12 keys** — IVviIV with minimum hand movement (C → G/B → Am → F/A), through the circle of fifths. Self-grading: you can see and hear when you jump.
2. **Shell iiVI cycle** — root+3+7 through all keys, alternating types so 3rds/7ths swap and resolve by half-step. The core voice-leading mechanic made physical.
3. **Charleston metronome ladder** — one syncopation pattern to automaticity at 80→160 BPM; comping failure in jams is usually rhythmic, not harmonic.
4. **Backing-track subtraction** — chorus 1 whole notes only; chorus 2 LH only above G3, no roots; chorus 3 RH colors only; chorus 4 two hits per bar. Simulates bandmates occupying frequency space.
5. **Bass-line ear training** — hum the bass note of each chord in a pop song, convert to numbers, play it.
6. **One song, twelve keys** — number-chart a known song, new key daily.
7. **Cold lead-sheet sight-comping** — slow metronome, once through the form, never stopping. Rehearses the actual jam failure mode.
### Sources
Berklee Online Keyboard Method · Mark Levine *The Jazz Piano Book* · Open Studio Piano Pathway · PianoGroove (rootless voicings, comping) · The Jazz Piano Site (jam prep) · Piano With Jonny (voicings, transposing) · Jens Larsen (comping rhythms) · Pianote (band guide, NNS) · Worship Online / Musicademy / Sweetwater (band role) · ToneDear / ToneGym / Musical U / trainear.com (ear training)
---
## Bass
### Skill taxonomy (rough order)
1. Fretboard zone mastery — every note to fret 12, lines through each zone (Friedland)
2. Root-fifth-octave vocabulary — the "safe but musical" jam fallback
3. Chord-tone fluency — R-3-5-7 of maj/min/dom/m7♭5 anywhere (TalkingBass: chord tones *before* scales)
4. Scale-tone vs chord-tone discrimination — outline on strong beats, connect on weak
5. Approach-note technique — chromatic from above/below, W|H|H walkup, dominant approach
6. Walking bass construction — root on 1, chord tones on 1 & 3, approach into the next root on 4
7. Subdivision command — straight 8ths / swing / shuffle / 16th funk, switching mid-groove
8. Pocket / drummer lock — kick matching, ghost notes, dynamic mirroring
9. Functional ear training — root movement, I/IV/V/vi by function
10. Real-time harmonic prediction — the V "pushes home", reacting within one pass of the form
11. Dynamics, touch, space — most cited intermediate→pro separator
12. Fills and form awareness — fills at bars 4/8 phrase boundaries
### Top drills
1. **Root-only song stripping** — play only the root of each change by ear; add 5ths and octaves on later passes. Strips songs to harmonic skeleton.
2. **Arpeggiate the progression** — R-3-5(-7) over I-V-vi-IV in several keys, then inversions, then other neck zones.
3. **W|H|H chromatic walkup** — between chords a 4th apart: root, whole, half, half (C-D-E♭-E→F). Formulaic forward motion that telegraphs the next chord.
4. **Walking 12-bar / 1-6-2-5 loop** — a decision every beat about chord vs passing tone (Friedland, SBL 5-step formula).
5. **2-bar loop challenge** — one groove for 5+ minutes changing only tone/dynamics/note length. Pocket training; exposes drift.
6. **Subdivision switching** — 2 bars 8ths / 2 bars 16ths at 60-80 BPM; click on 2&4 only; mute the click 4 bars and check.
7. **Sing-then-play root movement** — sing the roots before touching the bass, then 3rds/5ths/7ths.
### Sources
Scott's Bass Lessons (Players Path, Groove Trainer) · TalkingBass Chord Tone Essentials · Ed Friedland *Building Walking Bass Lines* · Hal Leonard Bass Method · Berklee Practice Method: Bass · Bass Musician Magazine (drummer lock) · Premier Guitar (jam survival) · StudyBass · Learn Jazz Standards · Jazz Night School (chromatic 4) · onlinebasscourses.com · Functional Ear Trainer
---
## How the app supports this (detection-powered training)
These map to GOAL.md L1L4; the app's unfair advantage is that it *hears* the player.
1. **Target-note highlighting** — on each detected chord change, flash the new chord's 3rd/7th on the fretboard/piano (guitar drill 3, piano drill 2). Later: score whether the first detected note after the change was a chord tone.
2. **Voice-leading coach (piano view)** — highlight the *nearest inversion* to the previous chord, common tones marked "hold"; score total semitone travel per progression.
3. **Next-chord preview tier (bass)** — when a loop is detected, highlight the upcoming chord's root plus its chromatic approach notes a half-step above/below — the walking-line scaffold, one beat ahead.
4. **Progression ear-trainer on your own jam** — hide the chord banner, ask for the numbers (vi-IV-I-V), reveal. Uses chord history + `toRomanNumeral`; contextual beats abstract drills.
5. **Pocket report** — extend the onset/BPM histogram to show beat-phase drift (rushing/dragging), plus a 2-&-4-only click synced to the detected tempo.
6. **Mode-difference teaching** — when the user manually switches mode (the K-S limitation), briefly highlight the difference notes (minor → Dorian = raised 6th).
+149
View File
@@ -0,0 +1,149 @@
# Chord Progression Repertoire
Research-backed reference for expanding the progression features. Companion to [`GOAL.md`](../GOAL.md) Part 1. Notation: uppercase = major, lowercase = minor, ° = diminished, 7 = dominant unless marked maj7/m7.
How this maps to code today:
- `PROGRESSIONS` in `src/lib/theory.js``{ name, rn, degrees }` per progression; `degrees` are semitone offsets from the key root. This is the format new entries should use.
- `getSuggestedProgressions(root, mode)` maps degrees → chord names in key; `toRomanNumeral()` converts any chord back to a numeral.
- `FAMOUS_PROGRESSIONS` in `src/lib/education.js` — richer entries (songs, tips, style variations) for the Learn side.
## 1. Genre-by-genre progression tables
### Pop
| Progression | Name / notes |
|---|---|
| IVviIV | "Axis of Awesome" — #1 in Hooktheory's corpus of 75k+ analyzed songs |
| viIVIV | Same loop rotated to start on vi ("pessimistic axis") |
| IviIVV | "Doo-wop" / "'50s progression" |
| IIVviV | Common variant (Africa chorus) |
| IVViiivi | "Royal Road" — J-pop/anime staple, spreading into Western pop |
### Rock
| Progression | Name / notes |
|---|---|
| IIVV | Foundation of rock/blues/country |
| I–♭VIIIV(I) | Mixolydian rock cliché (Sweet Home Alabama as VIVI rotation) |
| i–♭VII–♭VI(V) | Andalusian-derived minor loop; with V = full Andalusian cadence |
| I–♭IIIIV | Blues-rock riff progression (borrowed ♭III) |
### Blues (12-bar family)
| Progression | Name / notes |
|---|---|
| I7×4 / IV7×2, I7×2 / V7, IV7, I7, V7 | Standard 12-bar |
| Bar 2 → IV7 | "Quick change" / "quick four" |
| ii7V7 in bars 910, turnaround IVI7iiV7 | Jazz blues |
| i7iv7i7 … ♭VI7V7i7 | Minor blues (The Thrill Is Gone) |
| IVIVIVIVIV | 8-bar blues (Key to the Highway) |
### Jazz
| Progression | Name / notes |
|---|---|
| ii7V7Imaj7 | The fundamental cadence |
| IviiiV (also iiiviiiV) | Rhythm changes A / turnaround |
| III7VI7II7V7 | Rhythm changes bridge (circle of dominants) |
| iim7♭5V7♭9i | Minor iiVi |
| ii7–♭II7Imaj7 | Tritone-sub cadence |
| ivm7–♭VII7Imaj7 | "Backdoor" progression |
### Folk / Country
| Progression | Name / notes |
|---|---|
| IIVV(I) | Core of both genres |
| IVIIV | Two/three-chord verse pattern |
| i–♭VII–♭VI | Minor folk descent (AmGF) |
| IVviiiiIVIIVV | Pachelbel progression |
| III7VI | Classic country secondary-dominant (V/V) move |
### Funk
| Progression | Name / notes |
|---|---|
| I7 vamp | James Brown static dominant, voiced as 9th |
| i7IV7 | Dorian two-chord vamp — the most common funk pair |
| i7 / m11 vamp | Minor one-chord groove |
| ii7V7 loop | Funk/disco vamp |
Design insight: funk needs few *progressions* but rich *chord qualities* (9, 7♯9, m11, 13sus) — colour lives in the voicing, not the changes.
### Reggae
| Progression | Name / notes |
|---|---|
| IV or IIV | Two-chord skank vamps |
| IVviIV | No Woman No Cry |
| i–♭VII(–♭VI) | Minor roots-reggae vamp |
| IIVV | Ska/rocksteady standard |
### R&B / Neo-soul
| Progression | Name / notes |
|---|---|
| ii7V7Imaj7 (with 9/11/13 extensions) | Core cadence |
| iii7vi7ii7V7 | Circle movement from the mediant — neo-soul staple |
| viiiVI | "6-2-5-1" cyclical soul loop |
| Imaj7IVmaj7 / Imaj7iii7 | Two-chord vamps |
| i7iv7 | Dorian D'Angelo-style minor vamp |
### Gospel
| Progression | Name / notes |
|---|---|
| ii7V7I | The gospel "2-5-1", often chained: 6-2-5-1, 3-6-2-5-1 |
| II7IV | Tonicizing IV (V7/IV "amen" setup) |
| IVivI | Plagal with borrowed iv |
| I–♯i°–ii | Chromatic passing-diminished walk-up |
## 2. Substitution / variation taxonomy
Progression "families" relate through a small set of transforms — these are the generation rules for variation buttons and the Builder:
1. **Rotation** — any loop can start on any chord (IVviIV ≡ viIVIV). Treat loops as cyclic equivalence classes; display the rotation matching the user's tonic emphasis. (`detectRepeatingProgression` already canonicalizes rotations.)
2. **Diatonic (function) substitution** — chords sharing two notes swap: I↔vi↔iii (tonic), IV↔ii (subdominant), V↔vii° (dominant).
3. **Modal interchange / borrowing** — take a chord from the parallel mode: iv, ♭VI, ♭VII, ♭III, iim7♭5 in major; major IV (Dorian) in minor.
4. **Secondary dominants** — precede any diatonic target with its V7: V/V = II7, V/vi = III7, V/IV = I7, V/ii = VI7.
5. **Tritone substitution** — replace any dominant with the dominant a tritone away (V7 → ♭II7). Jazz flavour flag.
6. **Backdoor dominant** — ♭VII7 resolving to I, usually as ivm7–♭VII7I.
7. **Quality embellishment** — same root, richer colour: triad → 7th → 9/11/13, sus2/4, add9. The main axis distinguishing genres (pop = triads/sus, jazz/neo-soul/gospel = extensions, funk = dominant 9/♯9). Already partially covered by `CHORD_SUBSTITUTIONS` in `education.js`.
8. **Passing/approach chords** — chromatic passing diminished (I–♯i°–ii), bass-line inversions (slash chords).
## 3. UX patterns worth copying
- **Hookpad (Hooktheory)***key-relative chord palette*: only the diatonic chords of the current key, colour-coded consistently per scale degree (key-agnostic colours). Borrowed chords live in expandable secondary palettes. *Magic Chord* suggests the statistically likeliest next chord. Drag-and-drop onto a timeline. → Direct model for the Progression Builder (GOAL G3).
- **Hooktheory TheoryTab** — progressions ranked by real-song frequency; each links to songs using it. "You're playing the Creep progression" is a strong engagement hook (partially exists via `FAMOUS_PROGRESSIONS` song lists).
- **Scaler 2/3** — three-zone vertical flow: detection area (top) → suggested chords/scales (middle) → user-built progression (bottom). Maps directly onto this app: live detection → suggestions → builder.
- **iReal Pro** — one-tap transposition; per-genre rendering of the same progression.
- **ToneGym** — instant audio preview when tapping any chord/progression.
## 4. Voicing data
### Guitar
Best option found: [`tombatossals/chords-db`](https://github.com/tombatossals/chords-db) (MIT, npm `@tombatossals/chords-db`, prebuilt `lib/guitar.json`):
- All 12 keys × large suffix list, **multiple positions per chord** (open + barre + higher CAGED positions).
- Per position: `frets` (per string, `x` = mute, low-E first), `fingers`, optional `barres`, `baseFret`. Example: `{ frets: '55775x', fingers: '114310', barres: 5 }`.
- Companion renderer: [`tombatossals/react-chords`](https://github.com/tombatossals/react-chords) (React SVG diagrams consuming this format).
Triads on string-sets (top-3 / middle-3) are *not* in chords-db but are cheap to generate: for each inversion of the triad, map the 3 chord tones onto a chosen string set within a 4-fret window. This complements the existing `GUITAR_SHAPES` in `src/lib/voicings.js`.
### Piano
No canonical open dataset exists. The sane model is **interval recipes resolved per chord quality** (the chord templates in `theory.js` already encode quality → semitone mapping):
```js
// voicing = named recipe of chord degrees, resolved per chord quality
{
shell: { LH: ['1', '7'], RH: ['3'] },
rootPosition: { LH: ['1'], RH: ['1', '3', '5', '7'] },
rootlessA: { LH: ['3', '5', '7', '9'] }, // Type A: 3rd on bottom
rootlessB: { LH: ['7', '9', '3', '5'] }, // Type B: 7th on bottom
guideTones: { LH: ['3', '7'] },
}
```
Conventions to encode: rootless voicings keep the top note between C4C5; alternate Type A/B through a progression so inner voices barely move — i.e. pick the voicing minimizing semitone travel from the previous chord (simple voice-leading distance minimization).
## 5. Sources
- Hooktheory corpus & blog: hooktheory.com/blog/i-analyzed-the-chords-of-1300-popular-songs-for-patterns-this-is-what-i-found/ ; hooktheory.com/blog/jazz-chord-progressions/
- 12-bar variants: en.wikipedia.org/wiki/Twelve-bar_blues ; happybluesman.com/common-variations-12-bar-blues/
- Named progressions: en.wikipedia.org/wiki/%2750s_progression ; piano.org/chord-progressions/ ; supersimplepiano.com/learn/chord-progressions/royal-road
- Substitutions: learnjazzstandards.com (chord substitution) ; hub.yamaha.com (beyond diatonic) ; hubguitar.com (tritone subs)
- Gospel: gospelmaps.com/top-gospel-chord-progressions/ ; gospel.hearandplay.com (2-5-1)
- Genre vamps: orphiq.com (reggae) ; guitar-chord.org/articles/funk.html ; orangecandymusic.com & pickupmusic.com (R&B/neo-soul)
- Tools: producelikeapro.com (Scaler review) ; hooktheory.com/hookpad
- Voicing data: github.com/tombatossals/chords-db ; github.com/tombatossals/react-chords ; voicinglab.com & pianowithjonny.com & thejazzpianosite.com (rootless voicings)
+307
View File
@@ -0,0 +1,307 @@
# Plan: PWA + Firebase Hosting for JamBuddy
Status: **proposed**. Each phase is independently shippable; stop after any one.
---
## 0. Why this is low-risk
The Electron shell (`electron/main.cjs`, `preload.cjs`) does **nothing but host a window** — no IPC, no native APIs, `sandbox:false` only to give the renderer full Web Audio. All logic lives in the React renderer, which already runs browser-only via `npm run dev`. So the web build is the same `vite build` output the desktop installer already ships; we just add a manifest + service worker and serve `dist/` over HTTPS. Firebase gives us HTTPS for free, which `getUserMedia` (the mic) requires — that's the only hard web constraint.
Nothing in the app makes network calls today, so there's no API surface to re-host and no secrets to manage.
---
## Phase 1 — PWA scaffolding (no Firebase yet)
Goal: `vite build` produces an installable, offline-capable web app served from any static host.
### 1.1 Add `vite-plugin-pwa`
Only new dependency. Wraps Workbox under a Vite plugin — generates the service worker and injects the manifest. Cheaper than hand-rolling a SW and gets update flow for free.
```js
// vite.config.js
import { VitePWA } from 'vite-plugin-pwa'
export default defineConfig({
plugins: [
react(),
tailwindcss(),
VitePWA({
registerType: 'autoUpdate',
includeAssets: ['favicon.ico', 'apple-touch-icon.png'],
manifest: {
name: 'JamBuddy — WhatTheFlat',
short_name: 'JamBuddy',
description: 'Real-time key and chord detection for live jams.',
theme_color: '#0f0f0f', // matches bg-surface token
background_color: '#0f0f0f',
display: 'standalone',
orientation: 'any',
start_url: '/',
scope: '/',
icons: [ /* see 1.3 */ ],
},
workbox: {
globPatterns: ['**/*.{js,css,html,svg,png,ico,woff2}'],
// Audio is captured live — nothing to cache from a remote. Precache the app shell only.
navigateFallback: '/index.html',
},
}),
],
})
```
### 1.2 Create `public/` directory
Vite serves `public/` at root and copies it verbatim into `dist/`. We need it for:
- `favicon.ico`, `apple-touch-icon.png` (180×180)
- Any static PWA icons referenced by the manifest
- (Optional) `robots.txt` — not needed for an app, skip.
The existing `src/assets/whattheflat-logo.png` is imported in `App.jsx` and bundled by Vite — leave that as-is; **don't** move it. The manifest icons must live in `public/` because they're referenced by URL, not imported.
### 1.3 Generate icon set from the existing logo
Derive all required sizes from `assets/whattheflat-logo.png` (one source image → PNG output). Required manifest entries:
```js
icons: [
{ src: '/icon-192.png', sizes: '192x192', type: 'image/png', purpose: 'any' },
{ src: '/icon-512.png', sizes: '512x512', type: 'image/png', purpose: 'any' },
{ src: '/icon-512-maskable.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' },
]
```
Plus `apple-touch-icon.png` (180×180) in `public/` — iOS ignores the manifest and uses this `<link>`. The maskable variant needs safe-zone padding (~10%) so the logo isn't cropped by Android's circular mask.
One-liner with ImageMagick if available, else export manually from the source PNG:
```bash
magick assets/whattheflat-logo.png -resize 192x192 public/icon-192.png
magick assets/whattheflat-logo.png -resize 512x512 public/icon-512.png
magick assets/whattheflat-logo.png -resize 180x180 public/apple-touch-icon.png
```
### 1.4 Update `index.html`
Two problems with the current `<head>`:
1. **No PWA tags** — add theme-color, manifest link, apple-touch-icon, apple-mobile-web-app-capable, description.
2. **CSP is hardcoded for dev**`connect-src 'self' http://localhost:5173 ws://localhost:5173` and `script-src 'self' 'unsafe-eval'`. The `unsafe-eval` and the localhost entries are Vite dev artifacts; production Vite doesn't need `unsafe-eval`. Keep a CSP (it's good hygiene and the app is genuinely offline) but drop the dev bits:
```html
<meta name="theme-color" content="#0f0f0f" />
<meta name="description" content="Real-time key and chord detection for live jams." />
<link rel="manifest" href="/manifest.webmanifest" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
```
CSP (production):
```
default-src 'self';
script-src 'self';
style-src 'self' 'unsafe-inline';
img-src 'self' data:;
connect-src 'self';
media-src 'self' blob:; <!-- the mic stream lives in a blob -->
```
`blob:` in `media-src` is required because `getUserMedia` streams are blob-backed and the analyser reads them. Verify nothing else regresses — `vite-plugin-pwa` registers the SW from a same-origin script, so `'self'` covers it.
Move the dev-only CSP into a Vite conditional so dev still allows HMR/websocket:
```js
// vite.config.js — inject dev CSP via plugin, or keep a separate dev index template.
```
Simplest: keep one CSP in `index.html` with the production values, and in dev let Vite's own injected tags coexist (HMR works over the same origin websocket; CSP `connect-src 'self'` already allows it). If dev breaks, add `ws://localhost:5173` only in a dev-specific block.
### 1.5 Verify
- `npm run build``dist/` contains `manifest.webmanifest`, `registerSW.js`, `sw.js`, and all `public/` icons.
- Serve `dist/` locally with `npm run preview` and use Chrome DevTools → Application → Manifest (should show icons, installability ✓) and Service Workers (registered).
- Install to desktop / "Add to Home Screen" on mobile.
- Confirm the app still works **fully offline** after first load (airplane mode). Since there are no network calls, the only risk is the SW failing to precache — Workbox handles this.
---
## Phase 2 — Firebase Hosting setup
Goal: serve `dist/` over HTTPS on a `*.web.app` domain (or custom domain).
### 2.1 Install the CLI
```bash
npm install -D firebase-tools
```
### 2.2 Init
```bash
npx firebase init hosting
```
Answer:
- **Public directory:** `dist`
- **Single-page app (rewrite all urls to /index.html):** Yes — though the app has no client-side routing today, this protects future routes and is harmless.
- **Set up automatic builds with GitHub:** **No.** (You're not using GitHub.)
- **File `dist/index.html` already exists — overwrite?** **No.** This is critical — saying yes would clobber the Vite-built index.
This creates:
- `firebase.json`
- `.firebaserc`
### 2.3 `firebase.json` (target shape)
```json
{
"hosting": {
"public": "dist",
"ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
"rewrites": [{ "source": "**", "destination": "/index.html" }],
"headers": [
{
"source": "**/*.@(js|css|svg|png|ico|woff2|webmanifest)",
"headers": [
{ "key": "Cache-Control", "value": "public, max-age=31536000, immutable" }
]
},
{
"source": "/sw.js",
"headers": [
{ "key": "Cache-Control", "value": "no-cache" }
]
},
{
"source": "/index.html",
"headers": [
{ "key": "Cache-Control", "value": "no-cache" }
]
}
]
}
}
```
Why the headers: Vite hashes asset filenames, so JS/CSS/icons are content-addressed → cache them **immortal**. `index.html` and `sw.js` must stay fresh so updates propagate — `no-cache` revalidates them every time. (Note: with `vite-plugin-pwa`'s `autoUpdate`, the SW self-updates; the `no-cache` on `sw.js` is belt-and-braces.)
### 2.4 First deploy
```bash
npm run build
npx firebase deploy --only hosting
```
Output: `https://<project>.web.app`. The mic will now work because the origin is HTTPS.
### 2.5 `.gitignore`
Add `.firebase/` and `firebase-debug.log` (already in a sane gitignore, but confirm).
---
## Phase 3 — (optional) custom domain
In Firebase console → Hosting → Add custom domain. Add the DNS TXT/CNAME records it gives you. Lets Encrypt cert is auto-provisioned. No app change needed.
---
---
## Phase 4 — Web optimization checklist
Things that matter specifically for shipping this app on the web. Most are cheap; do them before the first public deploy.
### 4.1 Drop the dead dependency
`audiomotion-analyzer` is listed in `package.json` but **imported nowhere** in `src/`. Vite tree-shakes unused ESM, so it likely doesn't bloat the production bundle — but it still inflates `npm install` and is misleading. Either:
- **Remove it** from `dependencies` (one-line `npm uninstall audiomotion-analyzer`), or
- If something depends on it being present (it doesn't — grep confirms zero imports), wire it up.
Recommend: remove.
### 4.2 Audit bundle size
```bash
npm run build
npx vite-bundle-visualizer # one-off, no config needed
```
Expected heavy bits: `pitchy` (small, pure JS) and React 19. `electron` / `electron-builder` are devDeps and excluded from the web build. If the visualizer shows anything surprising (e.g. a transitive dep pulling in moment/lodash), trim it.
### 4.3 Code-split the heavy, rarely-used views
`DebugView`, `DrumView`, and `Tuner` are collapsible panels most users never open. They import theory helpers and own audio contexts. Lazy-load them so the initial bundle stays lean:
```jsx
const Tuner = lazy(() => import('./components/Tuner'))
const DebugView = lazy(() => import('./components/DebugView'))
const DrumView = lazy(() => import('./components/DrumView'))
```
Wrap in `<Suspense fallback={null}>`. These are already behind toggle buttons, so there's no UX cost. This is the single biggest web win — the core pitch/chord flow loads first.
### 4.4 Audio permissions & UX on the web
- **HTTPS** — covered by Firebase. `getUserMedia` is blocked on plain HTTP (except `localhost`).
- **User gesture** — the existing "Start Listening" button already provides the gesture the browser requires to call `getUserMedia`. Don't change this; never auto-start listening on load.
- **Mobile Safari quirks** — iOS Safari:
- Requires `audio: { echoCancellation: false }` style may differ; test the existing `AudioCapture` constraints on an iPhone.
- AudioContext must be resumed after a gesture — already handled since capture starts on click.
- `sharedArrayBuffer` is not needed by this app (no worklets), so no COOP/COEP headers required. Good — don't add them; they'd complicate the Firebase static host.
- **Permissions API** — optionally surface "microphone blocked" before the user clicks, using `navigator.permissions.query({ name: 'microphone' })`. The existing `micError` state already covers the denied case; this is a polish step, not required.
### 4.5 Mobile layout
The app uses Tailwind with responsive `lg:` breakpoints already (e.g. the progressions sidebar is `hidden lg:block`). For a real mobile deploy:
- Test the fretboard / piano SVGs at phone widths — they're SVG so they scale, but text labels may crowd.
- The `controls bar` wraps with `flex-wrap` — good. Verify the key-lock select dropdowns are tappable.
- Consider a `display: standalone` install prompt; the manifest already sets `standalone`.
- This is a "play and look at the screen" app — portrait guitar fretboard orientation may want `orientation: 'portrait'` in the manifest instead of `'any'`. Decide based on the primary instrument view.
### 4.6 Performance for the audio hot loop
Already mostly tuned (the dual-analyser design is deliberate). Web-specific notes:
- `requestAnimationFrame` driving the analyser is fine on web — no change.
- `Float32Array` chroma math is cheap. No change needed.
- Don't add a Workbox runtime cache for audio — there's no audio to cache; everything is live.
- If you ever add an AudioWorklet, its file must be served with the correct MIME and same-origin — Workbox precaches it as part of `globPatterns` only if it's emitted to `dist/`. Not needed today.
### 4.7 SEO / social (minimal — this is an app, not content)
- `<title>` and meta description (added in 1.4) are enough for the web.app URL to have a sane share card.
- Add `og:title` / `og:description` / `og:image` to `index.html` if you want a nice link preview (point `og:image` to `/icon-512.png`). Optional.
- No sitemap needed for a single-page offline app.
### 4.8 Keep Electron working
The desktop build must not regress:
- `electron-builder` config in `package.json` is untouched by any of the above.
- The CSP change in `index.html` affects both targets — verify the desktop window still loads (it serves the built `dist/index.html`, so the new production CSP applies there too; that's fine and arguably better).
- `vite-plugin-pwa` is a dev dependency; it only runs at build time and doesn't touch the renderer runtime in a way that breaks Electron.
- Run `npm run electron:dev` after Phase 1 to confirm the Electron path still works.
---
## What stays Electron-only
Nothing in this plan removes or forks code. The Electron and web builds share the exact same `dist/` output. The only per-target differences are:
- Electron adds the `electron/main.cjs` shell and `electron-builder` packaging.
- Web adds the PWA manifest + SW (ignored by Electron) and is served over HTTPS.
If a future feature needs a native API (filesystem dialogs, auto-launch, tray), it would go through Electron's preload/IPC — which currently exposes nothing. At that point you'd add an `isElectron` guard and a `preload` IPC bridge. Not needed for any current feature.
---
## Suggested order of operations
1. **Phase 1.2** — create `public/`, drop in icons (Phase 1.3).
2. **Phase 1.1 + 1.4** — add `vite-plugin-pwa`, update `index.html`, relax CSP.
3. Verify with `npm run preview` + DevTools (Phase 1.5).
4. **Phase 2**`firebase init hosting`, hand-tune `firebase.json`, first deploy.
5. **Phase 4.1** — remove dead `audiomotion-analyzer` dep.
6. **Phase 4.3** — lazy-load the three collapsible views.
7. Polish: mobile pass (4.5), bundle audit (4.2), optional OG tags (4.7).
Each step is independently revertible. Stop after step 4 and you have a working, installable, offline PWA on the web; the rest is optimization.
+14
View File
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.device.audio-input</key>
<true/>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
</dict>
</plist>
+55
View File
@@ -0,0 +1,55 @@
const { app, BrowserWindow, systemPreferences } = require('electron')
const path = require('path')
const isDev = !app.isPackaged
async function handlePermissions() {
// macOS requires an explicit native request for microphone access in packaged apps
if (process.platform === 'darwin') {
try {
const status = systemPreferences.getMediaAccessStatus('microphone')
if (status !== 'granted') {
await systemPreferences.askForMediaAccess('microphone')
}
} catch (err) {
console.error('[Main] Microphone permission error:', err)
}
}
}
function createWindow() {
const win = new BrowserWindow({
width: 1280,
height: 900,
minWidth: 620,
minHeight: 600,
title: 'WhatTheFlat ♭? - JamBuddy',
icon: path.join(__dirname, '../assets/whattheflat-logo.png'),
webPreferences: {
preload: path.join(__dirname, 'preload.cjs'),
contextIsolation: true,
nodeIntegration: false,
sandbox: false, // allows renderer getUserMedia to work on all platforms
},
})
if (isDev) {
win.loadURL('http://127.0.0.1:5173')
win.webContents.openDevTools()
} else {
win.loadFile(path.join(__dirname, '../dist/index.html'))
}
}
app.whenReady().then(async () => {
await handlePermissions()
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit()
})
+8
View File
@@ -0,0 +1,8 @@
// Preload runs in a privileged context before the renderer.
// Expose only what the app actually needs from Node/Electron here.
// Currently the app is pure browser JS so nothing needs exposing.
const { contextBridge } = require('electron')
contextBridge.exposeInMainWorld('electronAPI', {
platform: process.platform,
})
+28
View File
@@ -0,0 +1,28 @@
{
"hosting": {
"site": "jambuddy",
"public": "dist",
"ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
"rewrites": [{ "source": "**", "destination": "/index.html" }],
"headers": [
{
"source": "**/*.@(js|css|svg|png|ico|woff2|webmanifest)",
"headers": [
{ "key": "Cache-Control", "value": "public, max-age=31536000, immutable" }
]
},
{
"source": "/sw.js",
"headers": [
{ "key": "Cache-Control", "value": "no-cache" }
]
},
{
"source": "/index.html",
"headers": [
{ "key": "Cache-Control", "value": "no-cache" }
]
}
]
}
}
-12
View File
@@ -1,12 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WhatTheFlat</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
-2486
View File
File diff suppressed because it is too large Load Diff
-25
View File
@@ -1,25 +0,0 @@
{
"name": "whattheflat-frontend",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"pitchy": "^4.1.0",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.1",
"autoprefixer": "^10.4.20",
"postcss": "^8.4.47",
"tailwindcss": "^3.4.14",
"vite": "^5.4.10"
}
}
-6
View File
@@ -1,6 +0,0 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
-263
View File
@@ -1,263 +0,0 @@
import { useState, useCallback, useRef, useEffect } from 'react'
import AudioCapture from './components/AudioCapture'
import ProgressionBanner from './components/ProgressionBanner'
import KeyDisplay from './components/KeyDisplay'
import ChordDisplay from './components/ChordDisplay'
import SafeNotes from './components/SafeNotes'
import Fretboard from './components/Fretboard'
import ProgressionSuggestions from './components/ProgressionSuggestions'
import ChatAssistant from './components/ChatAssistant'
import { NOTES, detectKey, matchChordFromChroma, detectRepeatingProgression } from './lib/theory'
// Key detection tuning
const NOTE_HISTORY_SIZE = 80
const KEY_VOTE_WINDOW = 12
const KEY_VOTE_THRESHOLD = 9 // out of 12 very stable
// Chord detection tuning
const CHROMA_SMOOTH = 12 // frames to average (~200ms at 60fps)
const CHORD_VOTE_THRESHOLD = 3 // consecutive identical detections required
export default function App() {
// Listening state
const [isListening, setIsListening] = useState(false)
// App mode
const [appMode, setAppMode] = useState('beginner') // 'beginner' | 'advanced'
// Key: auto-detected + optional lock
const [keyInfo, setKeyInfo] = useState(null) // auto-detected
const [lockedKey, setLockedKey] = useState(null) // { root, mode } or null
const [lockRoot, setLockRoot] = useState('A')
const [lockMode, setLockMode] = useState('minor')
// Effective key used by all components
const effectiveKey = lockedKey ?? keyInfo
// Locked key = only match diatonic chords regardless of mode far fewer candidates
const isStrictMode = lockedKey !== null
// Chord state
const [chordHistory, setChordHistory] = useState([])
const [detectedProgression, setDetectedProgression] = useState(null)
// Internal refs
const noteHistoryRef = useRef([])
const keyVotesRef = useRef([])
const effectiveKeyRef = useRef(null) // mirror for use inside callbacks
const chromaRingRef = useRef(
Array.from({ length: CHROMA_SMOOTH }, () => new Float32Array(12))
)
const chromaIdxRef = useRef(0)
const chordVotesRef = useRef([])
// Keep ref in sync
useEffect(() => { effectiveKeyRef.current = effectiveKey }, [effectiveKey])
// Detect progression whenever chord history changes
useEffect(() => {
setDetectedProgression(detectRepeatingProgression(chordHistory))
}, [chordHistory])
// Key lock handlers
function applyLock() {
const info = { root: lockRoot, mode: lockMode, confidence: 1 }
setLockedKey(info)
effectiveKeyRef.current = info
chordVotesRef.current = []
setChordHistory([])
setDetectedProgression(null)
}
function removeLock() {
setLockedKey(null)
effectiveKeyRef.current = keyInfo
}
// Note handler: drives key detection (pitch-based)
const handleNote = useCallback(({ pitchClass }) => {
const history = noteHistoryRef.current
history.push(pitchClass)
if (history.length > NOTE_HISTORY_SIZE) history.shift()
if (history.length < 10) return
if (history.length % 5 !== 0) return
const result = detectKey(history)
if (result.confidence < 0.5) return
const votes = keyVotesRef.current
votes.push(`${result.root}_${result.mode}`)
if (votes.length > KEY_VOTE_WINDOW) votes.shift()
const counts = {}
for (const v of votes) counts[v] = (counts[v] || 0) + 1
const [winner, count] = Object.entries(counts).sort((a, b) => b[1] - a[1])[0]
if (count >= KEY_VOTE_THRESHOLD) {
const [root, mode] = winner.split('_')
setKeyInfo(prev => {
if (prev?.root === root && prev?.mode === mode) {
return { root, mode, confidence: result.confidence }
}
// Key changed reset chord votes but keep history visible
if (!lockedKey) {
chordVotesRef.current = []
}
return { root, mode, confidence: result.confidence }
})
}
}, [lockedKey])
// Chroma handler: drives chord detection
const handleChroma = useCallback((chroma, bassPC) => {
const ring = chromaRingRef.current
ring[chromaIdxRef.current % CHROMA_SMOOTH] = chroma
chromaIdxRef.current++
if (chromaIdxRef.current % CHROMA_SMOOTH !== 0) return
const key = effectiveKeyRef.current
if (!key) return
// Average ring buffer
const avg = new Float32Array(12)
for (const frame of ring) for (let i = 0; i < 12; i++) avg[i] += frame[i]
for (let i = 0; i < 12; i++) avg[i] /= CHROMA_SMOOTH
const chord = matchChordFromChroma(avg, key, bassPC, isStrictMode)
if (!chord) {
// Ambiguous moment (transition, silence) reset streak, history is untouched
chordVotesRef.current = []
return
}
const votes = chordVotesRef.current
votes.push(chord)
if (votes.length > CHORD_VOTE_THRESHOLD) votes.shift()
// All last N detections must agree one wrong reading resets the streak
if (votes.length >= CHORD_VOTE_THRESHOLD && votes.every(v => v === votes[0])) {
const winner = votes[0]
setChordHistory(prev => {
if (prev[prev.length - 1] === winner) return prev
return [...prev.slice(-30), winner]
})
}
}, [isStrictMode])
const currentChord = chordHistory[chordHistory.length - 1]
return (
<div className="min-h-screen bg-surface text-white p-4 md:p-6">
{/* ── Header ── */}
<header className="mb-4 flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-accent">
WhatTheFlat <span className="text-gray-600">&#9837;?</span>
</h1>
<p className="text-xs text-gray-600 mt-0.5">Real-time key detection for real humans</p>
</div>
<button
onClick={() => setIsListening(l => !l)}
className={`px-5 py-2.5 rounded-full font-semibold text-sm transition-all ${
isListening
? 'bg-red-600 hover:bg-red-700 text-white'
: 'bg-accent hover:bg-purple-600 text-white'
}`}
>
{isListening ? 'Stop' : 'Start Listening'}
</button>
</header>
{/* ── Controls bar ── */}
<div className="mb-4 flex flex-wrap gap-3 items-center p-3 bg-panel border border-border rounded-xl">
{/* Mode toggle */}
<div className="flex bg-surface border border-border rounded-full p-0.5 text-sm">
{['beginner', 'advanced'].map(m => (
<button
key={m}
onClick={() => setAppMode(m)}
className={`px-4 py-1 rounded-full capitalize transition-all ${
appMode === m ? 'bg-accent text-white' : 'text-gray-400 hover:text-gray-200'
}`}
>
{m}
</button>
))}
</div>
{/* Key lock */}
{lockedKey ? (
<div className="flex items-center gap-2">
<span className="px-3 py-1 bg-accent/20 border border-accent text-accent rounded-full text-sm font-semibold">
🔒 {lockedKey.root} {lockedKey.mode}
</span>
<button
onClick={removeLock}
className="text-xs text-gray-500 hover:text-gray-300 underline"
>
unlock
</button>
</div>
) : (
<div className="flex gap-2 items-center">
<select
value={lockRoot}
onChange={e => setLockRoot(e.target.value)}
className="bg-surface border border-border rounded-lg px-2 py-1 text-sm text-gray-300"
>
{NOTES.map(n => <option key={n}>{n}</option>)}
</select>
<select
value={lockMode}
onChange={e => setLockMode(e.target.value)}
className="bg-surface border border-border rounded-lg px-2 py-1 text-sm text-gray-300"
>
<option value="major">Major</option>
<option value="minor">Minor</option>
</select>
<button
onClick={applyLock}
className="px-3 py-1 bg-border hover:bg-accent/20 border border-border hover:border-accent text-sm rounded-lg transition-all"
>
Lock Key
</button>
</div>
)}
{/* Auto-detected key badge (advanced mode) */}
{appMode === 'advanced' && keyInfo && !lockedKey && (
<span className="text-xs text-gray-500">
auto: {keyInfo.root} {keyInfo.mode} ({Math.round(keyInfo.confidence * 100)}%)
</span>
)}
</div>
<AudioCapture onNote={handleNote} onChroma={handleChroma} isListening={isListening} />
{/* ── Progression banner — full width ── */}
<ProgressionBanner
chordHistory={chordHistory}
keyInfo={effectiveKey}
detectedProgression={detectedProgression}
/>
{/* ── Main grid ── */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<KeyDisplay keyInfo={effectiveKey} locked={!!lockedKey} />
<ChordDisplay history={chordHistory} />
<SafeNotes keyInfo={effectiveKey} currentChord={currentChord} />
<ProgressionSuggestions keyInfo={effectiveKey} />
<div className="md:col-span-2">
<Fretboard
keyInfo={effectiveKey}
currentChord={currentChord}
pentatonicOnly={appMode === 'beginner'}
/>
</div>
<div className="md:col-span-2">
<ChatAssistant keyInfo={effectiveKey} currentChord={currentChord} />
</div>
</div>
</div>
)
}
-166
View File
@@ -1,166 +0,0 @@
import { useEffect, useRef, useCallback } from 'react'
import { PitchDetector } from 'pitchy'
import { NOTES } from '../lib/theory'
// Why two analysers?
//
// The Web Audio FFT has linearly-spaced bins: bin width = sampleRate / fftSize.
//
// fftSize 4096 ~10.8 Hz/bin (default we were using)
// fftSize 16384 ~2.7 Hz/bin (multi-rate chord analyser)
//
// On the low guitar strings the gap between adjacent semitones is only ~5-6 Hz.
// At 10.8 Hz/bin we literally cannot separate A2 (110 Hz) from A#2 (116 Hz).
// That is the single biggest source of wrong chord notes on the low strings.
//
// Solution: run a second, larger analyser just for chord/chroma detection.
// The pitch analyser stays small (4096) so pitchy has a 90ms window fast
// enough for responsive pitch detection. The chord analyser uses 16384 (~370ms
// window) slower to respond but with 2.7 Hz bins that can cleanly separate
// every semitone across the guitar's entire range.
//
// This is an approximation of the Constant-Q Transform (CQT) your friend
// mentioned: CQT achieves log-spaced bins mathematically; we approximate it
// by simply using a much larger FFT window.
//
const PITCH_FFT = 4096 // ~90ms window good temporal resolution for pitch
const CHORD_FFT = 16384 // ~370ms window 2.7 Hz/bin, separates low semitones
const MIN_CLARITY = 0.80
const MIN_VOLUME = 0.01
const NOISE_FLOOR = -65 // dB
// Harmonic summation chroma
// Each FFT bin votes back toward lower fundamentals that could have generated
// it as an overtone. This undoes the harmonic contamination that makes minor
// chords look like major ones (the 5th harmonic of the root lands on the major
// 3rd, which is NOT in the minor chord).
const HARMONIC_WEIGHTS = [1.0, 0.5, 0.33, 0.25, 0.2] // h = 15
function computeChroma(freqData, sampleRate, fftSize) {
const chroma = new Float32Array(12)
const binHz = sampleRate / fftSize
const N = freqData.length
for (let bin = 2; bin < N; bin++) {
const freq = bin * binHz
if (freq < 80 || freq > 4000) continue
const db = freqData[bin]
if (db < NOISE_FLOOR) continue
const amp = Math.sqrt(Math.pow(10, db / 10)) // amplitude, not power
for (let h = 1; h <= HARMONIC_WEIGHTS.length; h++) {
const fundamental = freq / h
if (fundamental < 40 || fundamental > 2000) continue
const midi = 12 * Math.log2(fundamental / 440) + 69
const pc = ((Math.round(midi) % 12) + 12) % 12
chroma[pc] += amp * HARMONIC_WEIGHTS[h - 1]
}
}
for (let i = 0; i < 12; i++) chroma[i] = Math.log1p(chroma[i])
const max = Math.max(...chroma)
if (max > 0) for (let i = 0; i < 12; i++) chroma[i] /= max
return chroma
}
function detectBassPC(freqData, sampleRate, fftSize) {
const binHz = sampleRate / fftSize
let maxPower = 0, bestMidi = -1
for (let bin = 2; bin < freqData.length; bin++) {
const freq = bin * binHz
if (freq < 40 || freq > 350) continue
const db = freqData[bin]
if (db < NOISE_FLOOR) continue
const power = Math.pow(10, db / 10)
if (power > maxPower) {
maxPower = power
bestMidi = Math.round(12 * Math.log2(freq / 440) + 69)
}
}
if (bestMidi < 0) return null
return ((bestMidi % 12) + 12) % 12
}
export default function AudioCapture({ onNote, onChroma, isListening }) {
const audioCtxRef = useRef(null)
const pitchAnalyser = useRef(null)
const chordAnalyser = useRef(null)
const timeBufRef = useRef(null)
const freqBufRef = useRef(null)
const detectorRef = useRef(null)
const rafRef = useRef(null)
const streamRef = useRef(null)
const stop = useCallback(() => {
if (rafRef.current) cancelAnimationFrame(rafRef.current)
if (streamRef.current) streamRef.current.getTracks().forEach(t => t.stop())
if (audioCtxRef.current) audioCtxRef.current.close()
audioCtxRef.current = null
}, [])
const start = useCallback(async () => {
stop()
const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
streamRef.current = stream
const ctx = new AudioContext()
audioCtxRef.current = ctx
const source = ctx.createMediaStreamSource(stream)
// Small analyser pitch detection needs fast time-domain data
const pa = ctx.createAnalyser()
pa.fftSize = PITCH_FFT
pa.smoothingTimeConstant = 0.0 // no smoothing: pitchy needs clean waveform
pitchAnalyser.current = pa
source.connect(pa)
timeBufRef.current = new Float32Array(pa.fftSize)
detectorRef.current = PitchDetector.forFloat32Array(pa.fftSize)
// Large analyser chord detection needs fine frequency resolution
const ca = ctx.createAnalyser()
ca.fftSize = CHORD_FFT
ca.smoothingTimeConstant = 0.65 // smooth over time for stable chord reading
chordAnalyser.current = ca
source.connect(ca)
freqBufRef.current = new Float32Array(ca.frequencyBinCount)
function tick() {
const timeBuf = timeBufRef.current
pa.getFloatTimeDomainData(timeBuf)
const rms = Math.sqrt(timeBuf.reduce((s, v) => s + v * v, 0) / timeBuf.length)
if (rms >= MIN_VOLUME) {
// Pitch via McLeod (autocorrelation) unaffected by FFT bin size
const [freq, clarity] = detectorRef.current.findPitch(timeBuf, ctx.sampleRate)
if (clarity >= MIN_CLARITY && freq > 60 && freq < 4200) {
const midi = Math.round(12 * Math.log2(freq / 440) + 69)
const pitchClass = ((midi % 12) + 12) % 12
onNote({ noteName: NOTES[pitchClass], pitchClass, freq, midi, clarity })
}
// Chord chroma from the high-resolution FFT
if (onChroma) {
const freqBuf = freqBufRef.current
ca.getFloatFrequencyData(freqBuf)
onChroma(
computeChroma(freqBuf, ctx.sampleRate, ca.fftSize),
detectBassPC(freqBuf, ctx.sampleRate, ca.fftSize)
)
}
}
rafRef.current = requestAnimationFrame(tick)
}
tick()
}, [onNote, onChroma, stop])
useEffect(() => {
if (isListening) start().catch(console.error)
else stop()
return stop
}, [isListening, start, stop])
return null
}
-89
View File
@@ -1,89 +0,0 @@
import { useState, useRef, useEffect } from 'react'
export default function ChatAssistant({ keyInfo, currentChord }) {
const [messages, setMessages] = useState([])
const [input, setInput] = useState('')
const [loading, setLoading] = useState(false)
const bottomRef = useRef(null)
useEffect(() => {
bottomRef.current?.scrollIntoView({ behavior: 'smooth' })
}, [messages])
async function send(e) {
e.preventDefault()
if (!input.trim() || loading) return
const userMsg = { role: 'user', content: input.trim() }
const next = [...messages, userMsg]
setMessages(next)
setInput('')
setLoading(true)
try {
const context = {}
if (keyInfo?.root) context.key = `${keyInfo.root} ${keyInfo.mode}`
if (currentChord) context.chord = currentChord
const res = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ messages: next, context }),
})
const data = await res.json()
setMessages(prev => [...prev, { role: 'assistant', content: data.reply }])
} catch (err) {
setMessages(prev => [...prev, {
role: 'assistant',
content: 'Could not reach the AI assistant. Is the backend running?',
}])
} finally {
setLoading(false)
}
}
return (
<div className="bg-panel border border-border rounded-2xl p-6 flex flex-col h-80">
<p className="text-sm text-gray-500 uppercase tracking-widest mb-3">Theory Assistant</p>
<div className="flex-1 overflow-y-auto space-y-3 pr-1">
{messages.length === 0 && (
<p className="text-gray-600 text-sm">Ask anything: "What lick works over this chord?" or "Why does the IV sound so resolved?"</p>
)}
{messages.map((m, i) => (
<div key={i} className={`text-sm ${m.role === 'user' ? 'text-right' : 'text-left'}`}>
<span className={`inline-block px-3 py-2 rounded-xl max-w-[85%] ${
m.role === 'user'
? 'bg-accent text-white'
: 'bg-border text-gray-200'
}`}>
{m.content}
</span>
</div>
))}
{loading && (
<div className="text-left">
<span className="inline-block px-3 py-2 rounded-xl bg-border text-gray-400 text-sm animate-pulse">
Thinking
</span>
</div>
)}
<div ref={bottomRef} />
</div>
<form onSubmit={send} className="mt-3 flex gap-2">
<input
className="flex-1 bg-surface border border-border rounded-lg px-3 py-2 text-sm outline-none focus:border-accent"
placeholder="Ask about music theory…"
value={input}
onChange={e => setInput(e.target.value)}
/>
<button
type="submit"
disabled={loading || !input.trim()}
className="px-4 py-2 bg-accent text-white rounded-lg text-sm font-medium disabled:opacity-40"
>
Send
</button>
</form>
</div>
)
}
-25
View File
@@ -1,25 +0,0 @@
export default function ChordDisplay({ history }) {
const current = history[history.length - 1]
const past = history.slice(-8, -1)
return (
<div className="bg-panel border border-border rounded-2xl p-6">
<p className="text-sm text-gray-500 uppercase tracking-widest mb-3">Chord</p>
<p className="text-5xl font-bold text-amber-400">
{current ?? '—'}
</p>
{past.length > 0 && (
<div className="mt-4 flex gap-2 flex-wrap">
{past.map((chord, i) => (
<span
key={i}
className="text-sm px-2 py-1 bg-border rounded text-gray-400"
>
{chord}
</span>
))}
</div>
)}
</div>
)
}
-154
View File
@@ -1,154 +0,0 @@
import { getPentatonicScale, getFullScale, getChordTones, NOTES } from '../lib/theory'
// Standard tuning: pitch classes of open strings, high-E first (top of diagram)
const STRINGS = [
{ label: 'e', root: 4 }, // high E
{ label: 'B', root: 11 },
{ label: 'G', root: 7 },
{ label: 'D', root: 2 },
{ label: 'A', root: 9 },
{ label: 'E', root: 4 }, // low E
]
const NUM_FRETS = 13 // frets 0 (open) through 12
const FRET_MARKERS = [3, 5, 7, 9]
const DOUBLE_MARKER = 12
// Layout constants
const NUT_X = 40 // x of the nut line
const OPEN_X = 18 // x of open-string dot centres
const FRET_W = 52 // pixels per fret
const STRING_H = 28 // pixels between strings
const PAD_T = 28 // top padding (fret numbers)
const PAD_B = 18 // bottom padding (fret marker dots)
const BOARD_W = NUT_X + (NUM_FRETS - 1) * FRET_W + 10
const BOARD_H = PAD_T + 5 * STRING_H + PAD_B
const DOT_R = 10
// x centre of a fretted note (fret >= 1)
const fretX = f => NUT_X + (f - 0.5) * FRET_W
// y centre of string si (0 = high e, 5 = low E)
const stringY = si => PAD_T + si * STRING_H
function noteColor(isChordTone, isPenta, isScale) {
if (isChordTone) return { fill: '#f59e0b', text: '#000' } // amber
if (isPenta) return { fill: '#a855f7', text: '#fff' } // purple
if (isScale) return { fill: '#374151', text: '#d1d5db' } // grey
return null
}
export default function Fretboard({ keyInfo, currentChord, pentatonicOnly = false }) {
const { root, mode } = keyInfo ?? {}
if (!root) return null
const pentaSet = new Set(getPentatonicScale(root, mode).map(n => NOTES.indexOf(n)))
const scaleSet = pentatonicOnly
? pentaSet
: new Set(getFullScale(root, mode).map(n => NOTES.indexOf(n)))
const chordSet = currentChord
? new Set(getChordTones(currentChord).map(n => NOTES.indexOf(n)))
: new Set()
return (
<div className="bg-panel border border-border rounded-2xl p-6">
<p className="text-sm text-gray-500 uppercase tracking-widest mb-4">
Fretboard {root} {mode}
{currentChord && <span className="text-amber-400 ml-2">/ {currentChord}</span>}
</p>
<div className="overflow-x-auto">
<svg
width={BOARD_W}
height={BOARD_H}
style={{ display: 'block', minWidth: BOARD_W }}
>
{/* Fretboard background */}
<rect x={NUT_X} y={PAD_T - 6} width={BOARD_W - NUT_X - 4} height={5 * STRING_H + 12}
fill="#1a120b" rx={2} />
{/* Fret position marker dots (between strings 23 and 34) */}
{FRET_MARKERS.map(f => (
<circle key={f}
cx={fretX(f)} cy={PAD_T + 2.5 * STRING_H}
r={5} fill="#3a2a1a" />
))}
{/* Double dot at 12 */}
<circle cx={fretX(DOUBLE_MARKER)} cy={PAD_T + 1.5 * STRING_H} r={5} fill="#3a2a1a" />
<circle cx={fretX(DOUBLE_MARKER)} cy={PAD_T + 3.5 * STRING_H} r={5} fill="#3a2a1a" />
{/* Fret lines (112) */}
{Array.from({ length: NUM_FRETS - 1 }, (_, i) => i + 1).map(f => (
<line key={f}
x1={NUT_X + f * FRET_W} y1={PAD_T - 6}
x2={NUT_X + f * FRET_W} y2={PAD_T + 5 * STRING_H + 6}
stroke={f === DOUBLE_MARKER ? '#888' : '#4a3a2a'}
strokeWidth={f === DOUBLE_MARKER ? 2 : 1} />
))}
{/* Nut */}
<line x1={NUT_X} y1={PAD_T - 6} x2={NUT_X} y2={PAD_T + 5 * STRING_H + 6}
stroke="#c0b090" strokeWidth={4} />
{/* Strings */}
{STRINGS.map((_, si) => (
<line key={si}
x1={OPEN_X - DOT_R - 2} y1={stringY(si)}
x2={BOARD_W - 8} y2={stringY(si)}
stroke="#9ca3af"
strokeWidth={si < 2 ? 1 : si < 4 ? 1.5 : 2} />
))}
{/* Fret numbers */}
{[3, 5, 7, 9, 12].map(f => (
<text key={f}
x={fretX(f)} y={PAD_T - 10}
textAnchor="middle" fontSize={10} fill="#6b7280"
>{f}</text>
))}
{/* String labels */}
{STRINGS.map((s, si) => (
<text key={si}
x={6} y={stringY(si) + 4}
textAnchor="middle" fontSize={10} fill="#6b7280"
>{s.label}</text>
))}
{/* Note dots */}
{STRINGS.flatMap((str, si) =>
Array.from({ length: NUM_FRETS }, (_, fi) => {
const pc = (str.root + fi) % 12
const color = noteColor(chordSet.has(pc), pentaSet.has(pc), scaleSet.has(pc))
if (!color) return null
const cx = fi === 0 ? OPEN_X : fretX(fi)
const cy = stringY(si)
return (
<g key={`${si}-${fi}`}>
<circle cx={cx} cy={cy} r={DOT_R} fill={color.fill} />
<text
x={cx} y={cy + 4}
textAnchor="middle"
fontSize={9}
fontWeight="600"
fill={color.text}
>
{NOTES[pc]}
</text>
</g>
)
})
)}
</svg>
</div>
<div className="mt-3 flex gap-5 text-xs text-gray-500">
<span><span className="text-amber-400"></span> Chord tone</span>
<span><span className="text-accent"></span> Pentatonic</span>
<span><span className="text-gray-500"></span> Scale</span>
</div>
</div>
)
}
-33
View File
@@ -1,33 +0,0 @@
export default function KeyDisplay({ keyInfo, locked = false }) {
const { root, mode, confidence } = keyInfo ?? {}
const pct = confidence ? Math.round(confidence * 100) : 0
return (
<div className="bg-panel border border-border rounded-2xl p-6 text-center">
<p className="text-sm text-gray-500 uppercase tracking-widest mb-1">
{locked ? '🔒 Key (locked)' : 'Detected Key'}
</p>
{root ? (
<>
<p className="text-6xl font-bold text-accent leading-none">
{root}
<span className="text-3xl text-gray-400 ml-2">{mode}</span>
</p>
{!locked && (
<div className="mt-3 flex items-center justify-center gap-2">
<div className="h-1.5 w-32 bg-border rounded-full overflow-hidden">
<div
className="h-full bg-accent rounded-full transition-all duration-500"
style={{ width: `${pct}%` }}
/>
</div>
<span className="text-xs text-gray-500">{pct}% confident</span>
</div>
)}
</>
) : (
<p className="text-2xl text-gray-600 mt-2">Listening</p>
)}
</div>
)
}
@@ -1,122 +0,0 @@
import { useRef, useEffect } from 'react'
import { toRomanNumeral } from '../lib/theory'
const HISTORY_SHOWN = 8 // ~2 bars at 4 chords/bar
function findLoopPosition(chordHistory, progression) {
if (!progression?.length || !chordHistory.length) return -1
const last = chordHistory[chordHistory.length - 1]
for (let p = progression.length - 1; p >= 0; p--) {
if (progression[p] !== last) continue
let match = true
for (let i = 1; i < Math.min(p + 1, chordHistory.length); i++) {
if (progression[p - i] !== chordHistory[chordHistory.length - 1 - i]) { match = false; break }
}
if (match) return p
}
return progression.indexOf(last)
}
export default function ProgressionBanner({ chordHistory, keyInfo, detectedProgression }) {
const { root, mode } = keyInfo ?? {}
// Newest chord is the last entry; we show the most recent HISTORY_SHOWN
const visible = chordHistory.slice(-HISTORY_SHOWN)
const current = visible[visible.length - 1]
// Animate the current chord slot when it changes
const currentRef = useRef(null)
const prevChord = useRef(null)
useEffect(() => {
if (current && current !== prevChord.current && currentRef.current) {
currentRef.current.animate(
[{ opacity: 0, transform: 'scale(0.85)' },
{ opacity: 1, transform: 'scale(1)' }],
{ duration: 200, easing: 'ease-out', fill: 'forwards' }
)
prevChord.current = current
}
}, [current])
const loopPos = findLoopPosition(chordHistory, detectedProgression)
if (!chordHistory.length) {
return (
<div className="bg-panel border border-border rounded-2xl p-5 mb-4 flex items-center justify-center h-28">
<p className="text-gray-600">Start listening to detect chords</p>
</div>
)
}
return (
<div className="bg-panel border border-border rounded-2xl p-5 mb-4">
{/* ── Chord history strip: all HISTORY_SHOWN chords at consistent size ── */}
<div className="flex items-stretch gap-1 overflow-x-auto pb-1">
{visible.map((chord, i) => {
const isCurrent = i === visible.length - 1
const age = visible.length - 1 - i // 0 = current, higher = older
const opacity = Math.max(0.2, 1 - age * 0.1) // fade but stay readable
const rn = root ? toRomanNumeral(chord, root, mode) : ''
return (
<div
key={i}
ref={isCurrent ? currentRef : null}
style={{ opacity }}
className={`
flex flex-col items-center justify-end shrink-0 px-3 py-2 rounded-xl
transition-colors duration-200
${isCurrent
? 'bg-accent/10 border border-accent/40 ring-1 ring-accent/20'
: 'border border-transparent'}
`}
>
<span className={`font-black leading-none tracking-tight ${
isCurrent ? 'text-5xl text-accent' : 'text-3xl text-gray-200'
}`}>
{chord}
</span>
<span className={`text-xs font-semibold mt-1 ${
isCurrent ? 'text-amber-400' : 'text-gray-500'
}`}>
{rn || '\u00A0'}
</span>
</div>
)
})}
</div>
{/* ── Detected loop ── */}
{detectedProgression && (
<div className="mt-4 pt-3 border-t border-border">
<p className="text-xs text-gray-500 uppercase tracking-widest mb-2"> Detected loop</p>
<div className="flex gap-2 flex-wrap">
{detectedProgression.map((chord, i) => {
const isActive = i === loopPos
const rn = root ? toRomanNumeral(chord, root, mode) : chord
return (
<div
key={i}
className={`flex flex-col items-center px-4 py-2 rounded-xl border transition-all duration-200 ${
isActive
? 'bg-accent/20 border-accent shadow-[0_0_14px_rgba(168,85,247,0.35)]'
: 'bg-border border-border'
}`}
>
<span className={`text-2xl font-bold leading-none ${isActive ? 'text-accent' : 'text-gray-200'}`}>
{chord}
</span>
<span className={`text-xs mt-1 font-semibold ${isActive ? 'text-amber-400' : 'text-gray-500'}`}>
{rn}
</span>
</div>
)
})}
<span className="self-center text-gray-600 text-sm pl-1"> loop</span>
</div>
</div>
)}
</div>
)
}
@@ -1,32 +0,0 @@
import { getSuggestedProgressions } from '../lib/theory'
export default function ProgressionSuggestions({ keyInfo }) {
const { root, mode } = keyInfo ?? {}
if (!root) return null
const progressions = getSuggestedProgressions(root, mode)
return (
<div className="bg-panel border border-border rounded-2xl p-6">
<p className="text-sm text-gray-500 uppercase tracking-widest mb-4">
Progressions in {root} {mode}
</p>
<div className="space-y-3">
{progressions.map(prog => (
<div key={prog.genre} className="flex items-center gap-3">
<span className="text-xs text-gray-500 w-10 shrink-0">{prog.genre}</span>
<div className="flex gap-2 flex-wrap">
{prog.chords.map((chord, i) => (
<span key={i} className="px-3 py-1 bg-border rounded text-sm font-medium">
{chord}
<span className="ml-1 text-gray-600 text-xs">({prog.rn[i]})</span>
</span>
))}
</div>
</div>
))}
</div>
</div>
)
}
-46
View File
@@ -1,46 +0,0 @@
import { getPentatonicScale, getFullScale, getChordTones } from '../lib/theory'
const ALL_NOTES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
export default function SafeNotes({ keyInfo, currentChord }) {
const { root, mode } = keyInfo ?? {}
if (!root) return null
const penta = getPentatonicScale(root, mode)
const full = getFullScale(root, mode)
const chordTones = currentChord ? getChordTones(currentChord) : []
return (
<div className="bg-panel border border-border rounded-2xl p-6">
<p className="text-sm text-gray-500 uppercase tracking-widest mb-4">Safe Notes</p>
<div className="flex gap-2 flex-wrap">
{ALL_NOTES.map(note => {
const isChordTone = chordTones.includes(note)
const isPenta = penta.includes(note)
const isScale = full.includes(note)
let cls = 'px-3 py-2 rounded-lg text-sm font-semibold border transition-all '
if (isChordTone) {
cls += 'bg-accent text-white border-accent scale-105'
} else if (isPenta) {
cls += 'bg-accent/20 text-accent border-accent/40'
} else if (isScale) {
cls += 'bg-border text-gray-300 border-border'
} else {
cls += 'bg-transparent text-gray-700 border-transparent'
}
return (
<span key={note} className={cls}>{note}</span>
)
})}
</div>
<div className="mt-3 flex gap-4 text-xs text-gray-500">
<span><span className="text-accent"></span> Chord tone</span>
<span><span className="text-accent/60"></span> Pentatonic</span>
<span><span className="text-gray-500"></span> Scale</span>
</div>
</div>
)
}
-9
View File
@@ -1,9 +0,0 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
body {
background-color: #0f0f0f;
color: #f5f5f5;
font-family: system-ui, -apple-system, sans-serif;
}
-366
View File
@@ -1,366 +0,0 @@
// ─── Constants ───────────────────────────────────────────────────────────────
export const NOTES = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B']
export const NOTES_FLAT = ['C','Db','D','Eb','E','F','Gb','G','Ab','A','Bb','B']
// Semitone intervals for each scale mode
export const SCALES = {
major: [0, 2, 4, 5, 7, 9, 11],
minor: [0, 2, 3, 5, 7, 8, 10],
dorian: [0, 2, 3, 5, 7, 9, 10],
phrygian: [0, 1, 3, 5, 7, 8, 10],
lydian: [0, 2, 4, 6, 7, 9, 11],
mixolydian: [0, 2, 4, 5, 7, 9, 10],
pentatonic_major: [0, 2, 4, 7, 9],
pentatonic_minor: [0, 3, 5, 7, 10],
blues: [0, 3, 5, 6, 7, 10],
diminished: [0, 2, 3, 5, 6, 8, 9, 11],
whole_tone: [0, 2, 4, 6, 8, 10],
}
// Human-readable scale labels
export const SCALE_LABELS = {
major: 'Major',
minor: 'Natural Minor',
dorian: 'Dorian',
phrygian: 'Phrygian',
lydian: 'Lydian',
mixolydian: 'Mixolydian',
pentatonic_major: 'Major Pentatonic',
pentatonic_minor: 'Minor Pentatonic',
blues: 'Blues',
diminished: 'Diminished',
whole_tone: 'Whole Tone',
}
// Krumhansl-Schmuckler key profiles (major/minor only — used for key detection)
const KS_MAJOR = [6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88]
const KS_MINOR = [6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17]
// Chord type definitions: intervals (semitones from root) and display suffix
export const CHORD_TYPES = {
maj: { intervals: [0, 4, 7], suffix: '' },
min: { intervals: [0, 3, 7], suffix: 'm' },
dom7: { intervals: [0, 4, 7, 10], suffix: '7' },
maj7: { intervals: [0, 4, 7, 11], suffix: 'maj7' },
min7: { intervals: [0, 3, 7, 10], suffix: 'm7' },
dim: { intervals: [0, 3, 6], suffix: 'dim' },
dim7: { intervals: [0, 3, 6, 9], suffix: 'dim7' },
half_dim: { intervals: [0, 3, 6, 10], suffix: 'm7b5' },
aug: { intervals: [0, 4, 8], suffix: 'aug' },
sus4: { intervals: [0, 5, 7], suffix: 'sus4' },
sus2: { intervals: [0, 2, 7], suffix: 'sus2' },
maj6: { intervals: [0, 4, 7, 9], suffix: '6' },
min6: { intervals: [0, 3, 7, 9], suffix: 'm6' },
add9: { intervals: [0, 2, 4, 7], suffix: 'add9' },
}
// Chord types considered during real-time chroma matching
const MATCH_CHORD_TYPES = [
'maj', 'min', 'dom7', 'min7', 'dim', 'half_dim', 'aug', 'sus4', 'add9',
]
// Minimum score for a chord match to be reported
const CHORD_MATCH_MIN_SCORE = 0.42
// Minimum margin over second-best for a match to be considered unambiguous
const CHORD_MATCH_MIN_MARGIN = 0.04
// Chord quality for each scale degree in major and minor
const DEGREE_QUALITIES = {
major: ['', 'm', 'm', '', '', 'm', 'dim'],
minor: ['m', 'dim', '', 'm', 'm', '', '' ],
}
const ROMAN_NUMERALS = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII']
// Common chord progressions by genre, expressed as semitone offsets from the root
const PROGRESSIONS = {
pop: { name: 'Pop', rn: ['I', 'V', 'vi', 'IV'], degrees: [0, 7, 9, 5] },
blues: { name: 'Blues', rn: ['I', 'IV', 'V'], degrees: [0, 5, 7] },
folk: { name: 'Folk', rn: ['I', 'IV', 'I', 'V'], degrees: [0, 5, 0, 7] },
jazz: { name: 'Jazz', rn: ['ii', 'V', 'I'], degrees: [2, 7, 0] },
rock: { name: 'Rock', rn: ['I', 'bVII', 'IV', 'I'], degrees: [0, 10, 5, 0] },
'50s': { name: "'50s", rn: ['I', 'vi', 'IV', 'V'], degrees: [0, 9, 5, 7] },
flamen: { name: 'Flamenco', rn: ['i', 'bVII', 'bVI', 'V'], degrees: [0, 10, 8, 7] },
}
// ─── Internal helpers ────────────────────────────────────────────────────────
function noteName(semitone, preferFlat = false) {
const pc = ((semitone % 12) + 12) % 12
return preferFlat ? NOTES_FLAT[pc] : NOTES[pc]
}
function pearsonCorrelation(a, b) {
const n = a.length
const meanA = a.reduce((s, v) => s + v, 0) / n
const meanB = b.reduce((s, v) => s + v, 0) / n
let num = 0, denA = 0, denB = 0
for (let i = 0; i < n; i++) {
const da = a[i] - meanA
const db = b[i] - meanB
num += da * db
denA += da * da
denB += db * db
}
return num / Math.sqrt(denA * denB + 1e-10)
}
// Accepts both sharp (C#) and flat (Db) spellings
function noteIndex(note) {
const idx = NOTES.indexOf(note)
if (idx !== -1) return idx
return NOTES_FLAT.indexOf(note)
}
// ─── Key Detection ───────────────────────────────────────────────────────────
/**
* detectKey(noteHistory) { root, mode, confidence }
* Uses Krumhansl-Schmuckler: correlates pitch-class histogram with key profiles.
* noteHistory: array of MIDI note numbers or pitch-class integers (011)
*/
export function detectKey(noteHistory) {
if (!noteHistory || noteHistory.length < 4) {
return { root: 'C', mode: 'major', confidence: 0 }
}
const freq = new Array(12).fill(0)
for (const note of noteHistory) {
freq[((note % 12) + 12) % 12]++
}
let best = { root: 0, mode: 'major', score: -Infinity }
for (let root = 0; root < 12; root++) {
const rotated = Array.from({ length: 12 }, (_, i) => freq[(i + root) % 12])
const scoreMaj = pearsonCorrelation(rotated, KS_MAJOR)
const scoreMin = pearsonCorrelation(rotated, KS_MINOR)
if (scoreMaj > best.score) best = { root, mode: 'major', score: scoreMaj }
if (scoreMin > best.score) best = { root, mode: 'minor', score: scoreMin }
}
const confidence = Math.max(0, Math.min(1, (best.score + 1) / 2))
return { root: noteName(best.root), mode: best.mode, confidence }
}
// ─── Scale helpers ───────────────────────────────────────────────────────────
export function getScale(root, mode) {
const rootIdx = noteIndex(root)
if (rootIdx === -1) return []
return (SCALES[mode] ?? SCALES.major).map(i => noteName(rootIdx + i))
}
// Legacy aliases
export const getFullScale = (root, mode) => getScale(root, mode)
export const getPentatonicScale = (root, mode) =>
getScale(root, mode === 'minor' ? 'pentatonic_minor' : 'pentatonic_major')
/**
* Returns all scale modes that contain every note in playedNotes.
* Useful for suggesting compatible scales from a detected chord or melody.
*/
export function getCompatibleScales(playedNotes, root) {
const played = new Set(playedNotes)
return Object.entries(SCALES)
.map(([mode]) => ({ mode, label: SCALE_LABELS[mode] ?? mode, notes: getScale(root, mode) }))
.filter(({ notes }) => [...played].every(n => notes.includes(n)))
}
// ─── Chord helpers ───────────────────────────────────────────────────────────
export function getChordTones(chordName) {
const match = chordName.match(/^([A-G][b#]?)(.*)$/)
if (!match) return []
const root = noteIndex(match[1])
const suffix = match[2] ?? ''
const type = Object.values(CHORD_TYPES).find(t => t.suffix === suffix) ?? CHORD_TYPES.maj
return type.intervals.map(i => noteName(root + i))
}
export function getChordsInKey(root, mode) {
const rootIdx = noteIndex(root)
if (rootIdx === -1) return []
const scale = SCALES[mode] ?? SCALES.major
const qualities = DEGREE_QUALITIES[mode] ?? DEGREE_QUALITIES.major
return scale.map((degree, i) => noteName(rootIdx + degree) + qualities[i])
}
// ─── Progression suggestions ─────────────────────────────────────────────────
export function getSuggestedProgressions(root, mode) {
const rootIdx = noteIndex(root)
if (rootIdx === -1) return []
const scale = SCALES[mode] ?? SCALES.major
const qualities = DEGREE_QUALITIES[mode] ?? DEGREE_QUALITIES.major
return Object.values(PROGRESSIONS).map(prog => {
const chords = prog.degrees.map(semitones => {
const noteIdx = (rootIdx + semitones) % 12
const degreeIdx = scale.indexOf(semitones)
// Chromatic degrees (e.g. bVII in rock) default to major triad
const quality = degreeIdx >= 0 ? qualities[degreeIdx] : ''
return noteName(noteIdx) + quality
})
return { genre: prog.name, rn: prog.rn, chords }
})
}
// ─── Chroma-based chord matching ─────────────────────────────────────────────
/**
* matchChordFromChroma(chroma, keyInfo, bassPC?, strictDiatonic?, minScore?, minMargin?)
* chroma: Float32Array[12], normalised 01 energy per pitch class.
* Returns null when no unambiguous winner is found (transition/silence).
*/
export function matchChordFromChroma(
chroma,
keyInfo,
bassPC = null,
strictDiatonic = false,
minScore = CHORD_MATCH_MIN_SCORE,
minMargin = CHORD_MATCH_MIN_MARGIN,
) {
if (!keyInfo?.root) return null
const diatonicSet = new Set(getChordsInKey(keyInfo.root, keyInfo.mode))
let best = { name: null, score: -Infinity }
let secondScore = -Infinity
for (let r = 0; r < 12; r++) {
for (const typeKey of MATCH_CHORD_TYPES) {
const type = CHORD_TYPES[typeKey]
const chordName = noteName(r) + type.suffix
if (strictDiatonic && !diatonicSet.has(chordName)) continue
const tones = new Set(type.intervals.map(i => (r + i) % 12))
let inEnergy = 0, outEnergy = 0
for (let pc = 0; pc < 12; pc++) {
if (pc === r) {
inEnergy += chroma[pc] * 2 // root carries strongest identity signal
} else if (tones.has(pc)) {
inEnergy += chroma[pc]
} else {
outEnergy += chroma[pc]
}
}
if (inEnergy + outEnergy < 0.05) continue
const coverageScore = inEnergy / (inEnergy + outEnergy * 0.5)
const bassBonus = bassPC !== null && r === bassPC ? 0.15 : 0
const diatonicBonus = diatonicSet.has(chordName) ? 0.15 : 0
const finalScore = coverageScore + bassBonus + diatonicBonus
if (finalScore > best.score) {
secondScore = best.score
best = { name: chordName, score: finalScore }
} else if (finalScore > secondScore) {
secondScore = finalScore
}
}
}
return (best.score >= minScore && best.score - secondScore >= minMargin)
? best.name
: null
}
// ─── Roman numeral notation ───────────────────────────────────────────────────
/**
* Converts a chord name to its Roman numeral relative to a key.
* Chromatic (borrowed) chords get a flat prefix, e.g. Bb in C major VII.
*/
export function toRomanNumeral(chordName, keyRoot, keyMode) {
if (!chordName || !keyRoot) return '?'
const match = chordName.match(/^([A-G][b#]?)(.*)$/)
if (!match) return '?'
const [, root, quality] = match
const chordRootIdx = noteIndex(root)
const keyRootIdx = noteIndex(keyRoot)
if (chordRootIdx < 0 || keyRootIdx < 0) return '?'
const semitones = ((chordRootIdx - keyRootIdx) + 12) % 12
const scale = SCALES[keyMode] ?? SCALES.major
const degreeIdx = scale.indexOf(semitones)
let rn
if (degreeIdx >= 0) {
rn = ROMAN_NUMERALS[degreeIdx]
} else {
// Chromatic chord: flat the nearest diatonic degree above it
const nearestAbove = scale.findIndex(d => d > semitones)
const refDegree = nearestAbove >= 0 ? nearestAbove : 0
rn = '♭' + ROMAN_NUMERALS[refDegree]
}
const isMinorQuality = /^m(?!aj)/.test(quality) || quality === 'dim' || quality === 'm7b5'
return isMinorQuality ? rn.toLowerCase() : rn
}
// ─── Repeating progression detection ─────────────────────────────────────────
/**
* detectRepeatingProgression(history) chord[] or null
* Returns the most-recently-completed repeating pattern (length 26).
* Uses non-overlapping match counting to avoid over-counting.
*/
export function detectRepeatingProgression(history) {
if (!history || history.length < 4) return null
const window = history.slice(-20)
let best = null, bestScore = 0
for (let len = 2; len <= 6; len++) {
if (len * 2 > window.length) break
const candidate = window.slice(-len)
let reps = 0, i = 0
while (i <= window.length - len) {
if (candidate.every((c, j) => c === window[i + j])) {
reps++
i += len // skip past match — non-overlapping
} else {
i++
}
}
const score = reps * len
if (reps >= 2 && score > bestScore) {
bestScore = score
best = candidate
}
}
return best
}
// ─── Utilities ───────────────────────────────────────────────────────────────
export function intervalName(semitones) {
const names = [
'Unison', 'Minor 2nd', 'Major 2nd', 'Minor 3rd', 'Major 3rd',
'Perfect 4th', 'Tritone', 'Perfect 5th', 'Minor 6th',
'Major 6th', 'Minor 7th', 'Major 7th',
]
return names[((semitones % 12) + 12) % 12] ?? 'Unknown'
}
export function transposeChord(chordName, semitones) {
const match = chordName.match(/^([A-G][b#]?)(.*)$/)
if (!match) return chordName
return noteName(noteIndex(match[1]) + semitones) + match[2]
}
export function transposeProgression(chords, semitones) {
return chords.map(c => transposeChord(c, semitones))
}
-476
View File
@@ -1,476 +0,0 @@
// ─── Constants ───────────────────────────────────────────────────────────────
export const NOTES = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B']
export const NOTES_FLAT = ['C','Db','D','Eb','E','F','Gb','G','Ab','A','Bb','B']
// Semitone intervals for each scale mode
export const SCALES = {
major: [0, 2, 4, 5, 7, 9, 11],
minor: [0, 2, 3, 5, 7, 8, 10],
dorian: [0, 2, 3, 5, 7, 9, 10],
phrygian: [0, 1, 3, 5, 7, 8, 10],
lydian: [0, 2, 4, 6, 7, 9, 11],
mixolydian: [0, 2, 4, 5, 7, 9, 10],
pentatonic_major: [0, 2, 4, 7, 9],
pentatonic_minor: [0, 3, 5, 7, 10],
blues: [0, 3, 5, 6, 7, 10],
diminished: [0, 2, 3, 5, 6, 8, 9, 11],
whole_tone: [0, 2, 4, 6, 8, 10],
}
// Human-readable scale labels
export const SCALE_LABELS = {
major: 'Major',
minor: 'Natural Minor',
dorian: 'Dorian',
phrygian: 'Phrygian',
lydian: 'Lydian',
mixolydian: 'Mixolydian',
pentatonic_major: 'Major Pentatonic',
pentatonic_minor: 'Minor Pentatonic',
blues: 'Blues',
diminished: 'Diminished',
whole_tone: 'Whole Tone',
}
// Krumhansl-Schmuckler key profiles (only major/minor used for key detection)
const KS_MAJOR = [6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88]
const KS_MINOR = [6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17]
// Chord type definitions: intervals (semitones from root) and display suffix
export const CHORD_TYPES = {
maj: { intervals: [0, 4, 7], suffix: '' },
min: { intervals: [0, 3, 7], suffix: 'm' },
dom7: { intervals: [0, 4, 7, 10], suffix: '7' },
maj7: { intervals: [0, 4, 7, 11], suffix: 'maj7' },
min7: { intervals: [0, 3, 7, 10], suffix: 'm7' },
dim: { intervals: [0, 3, 6], suffix: 'dim' },
dim7: { intervals: [0, 3, 6, 9], suffix: 'dim7' },
half_dim:{ intervals: [0, 3, 6, 10], suffix: 'm7b5' },
aug: { intervals: [0, 4, 8], suffix: 'aug' },
sus4: { intervals: [0, 5, 7], suffix: 'sus4' },
sus2: { intervals: [0, 2, 7], suffix: 'sus2' },
maj6: { intervals: [0, 4, 7, 9], suffix: '6' },
min6: { intervals: [0, 3, 7, 9], suffix: 'm6' },
add9: { intervals: [0, 2, 4, 7], suffix: 'add9' },
}
// Chord types considered during real-time chroma matching
const MATCH_CHORD_TYPES = [
'maj', 'min', 'dom7', 'min7', 'dim', 'half_dim', 'aug', 'sus4', 'add9',
]
// Minimum score for a chord match to be reported
const CHORD_MATCH_MIN_SCORE = 0.42
// Minimum margin over second-best for a match to be considered unambiguous
const CHORD_MATCH_MIN_MARGIN = 0.08
// Chord quality arrays for each scale degree in major and minor
const DEGREE_QUALITIES = {
major: ['', 'm', 'm', '', '', 'm', 'dim'],
minor: ['m', 'dim','', 'm', 'm', '', '' ],
}
const ROMAN_NUMERALS = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII']
// Common chord progressions by genre, expressed as semitone offsets from the root
const PROGRESSIONS = {
pop: { name: 'Pop', rn: ['I', 'V', 'vi', 'IV'], degrees: [0, 7, 9, 5] },
blues: { name: 'Blues', rn: ['I', 'IV', 'V'], degrees: [0, 5, 7] },
folk: { name: 'Folk', rn: ['I', 'IV', 'I', 'V'], degrees: [0, 5, 0, 7] },
jazz: { name: 'Jazz', rn: ['ii', 'V', 'I'], degrees: [2, 7, 0] },
rock: { name: 'Rock', rn: ['I', 'bVII', 'IV', 'I'], degrees: [0, 10, 5, 0] },
'50s': { name: "'50s", rn: ['I', 'vi', 'IV', 'V'], degrees: [0, 9, 5, 7] },
flamen: { name: 'Flamenco',rn: ['i', 'bVII', 'bVI', 'V'],degrees:[0, 10, 8, 7] },
}
// ─── Internal helpers ────────────────────────────────────────────────────────
/**
* Returns the note name for a given semitone value (011, wraps automatically).
* @param {number} semitone
* @param {boolean} [preferFlat=false]
* @returns {string}
*/
function noteName(semitone, preferFlat = false) {
const pc = ((semitone % 12) + 12) % 12
return preferFlat ? NOTES_FLAT[pc] : NOTES[pc]
}
/**
* Pearson correlation between two equal-length numeric arrays.
* Returns a value in [-1, 1]. A small epsilon avoids division by zero.
* @param {number[]} a
* @param {number[]} b
* @returns {number}
*/
function pearsonCorrelation(a, b) {
const n = a.length
const meanA = a.reduce((s, v) => s + v, 0) / n
const meanB = b.reduce((s, v) => s + v, 0) / n
let num = 0, denA = 0, denB = 0
for (let i = 0; i < n; i++) {
const da = a[i] - meanA
const db = b[i] - meanB
num += da * db
denA += da * da
denB += db * db
}
return num / Math.sqrt(denA * denB + 1e-10)
}
/**
* Returns the semitone offset (011) of a note name, or -1 if not found.
* Accepts both sharp and flat spellings.
* @param {string} note
* @returns {number}
*/
function noteIndex(note) {
const idx = NOTES.indexOf(note)
if (idx !== -1) return idx
return NOTES_FLAT.indexOf(note) // handles Db, Eb, etc.
}
// ─── Key Detection ───────────────────────────────────────────────────────────
/**
* Detects the most likely musical key from a recent history of played notes.
*
* Uses the Krumhansl-Schmuckler algorithm: builds a pitch-class frequency
* vector and correlates it against major and minor profiles for all 12 roots.
*
* @param {number[]} noteHistory MIDI note numbers or pitch-class integers (011)
* @returns {{ root: string, mode: 'major'|'minor', confidence: number }}
* confidence is normalised to [0, 1]; values below ~0.5 are unreliable.
*/
export function detectKey(noteHistory) {
if (!noteHistory || noteHistory.length < 4) {
return { root: 'C', mode: 'major', confidence: 0 }
}
// Build pitch-class frequency vector
const freq = new Array(12).fill(0)
for (const note of noteHistory) {
freq[((note % 12) + 12) % 12]++
}
let best = { root: 0, mode: 'major', score: -Infinity }
for (let root = 0; root < 12; root++) {
// Rotate the observed frequencies to align with the profile's C-root
const rotated = Array.from({ length: 12 }, (_, i) => freq[(i + root) % 12])
const scoreMaj = pearsonCorrelation(rotated, KS_MAJOR)
const scoreMin = pearsonCorrelation(rotated, KS_MINOR)
if (scoreMaj > best.score) best = { root, mode: 'major', score: scoreMaj }
if (scoreMin > best.score) best = { root, mode: 'minor', score: scoreMin }
}
// Map correlation [-1, 1] to a rough confidence in [0, 1]
const confidence = Math.max(0, Math.min(1, (best.score + 1) / 2))
return { root: noteName(best.root), mode: best.mode, confidence }
}
// ─── Scale helpers ───────────────────────────────────────────────────────────
/**
* Returns all note names in a given scale.
* @param {string} root e.g. 'G', 'F#'
* @param {keyof SCALES} mode
* @returns {string[]}
*/
export function getScale(root, mode) {
const rootIdx = noteIndex(root)
if (rootIdx === -1) return []
const intervals = SCALES[mode] ?? SCALES.major
return intervals.map(i => noteName(rootIdx + i))
}
// Legacy aliases kept for backwards compatibility
export const getFullScale = (root, mode) => getScale(root, mode)
export const getPentatonicScale = (root, mode) =>
getScale(root, mode === 'minor' ? 'pentatonic_minor' : 'pentatonic_major')
/**
* Returns all scale modes that contain every note in `playedNotes`.
* Useful for suggesting compatible scales from a detected chord or melody.
* @param {string[]} playedNotes e.g. ['C', 'E', 'G']
* @param {string} root
* @returns {{ mode: string, label: string, notes: string[] }[]}
*/
export function getCompatibleScales(playedNotes, root) {
const played = new Set(playedNotes)
return Object.entries(SCALES)
.map(([mode]) => ({ mode, label: SCALE_LABELS[mode] ?? mode, notes: getScale(root, mode) }))
.filter(({ notes }) => [...played].every(n => notes.includes(n)))
}
// ─── Chord helpers ───────────────────────────────────────────────────────────
/**
* Parses a chord name and returns its component note names.
* @param {string} chordName e.g. 'Am', 'Gmaj7', 'Fdim', 'Baug'
* @returns {string[]}
*/
export function getChordTones(chordName) {
const match = chordName.match(/^([A-G][b#]?)(.*)$/)
if (!match) return []
const root = noteIndex(match[1])
const suffix = match[2] ?? ''
const type = Object.values(CHORD_TYPES).find(t => t.suffix === suffix)
?? CHORD_TYPES.maj // default to major triad
return type.intervals.map(i => noteName(root + i))
}
/**
* Returns the diatonic chords (triads) for every scale degree.
* @param {string} root
* @param {'major'|'minor'} mode
* @returns {string[]} e.g. ['C', 'Dm', 'Em', 'F', 'G', 'Am', 'Bdim']
*/
export function getChordsInKey(root, mode) {
const rootIdx = noteIndex(root)
if (rootIdx === -1) return []
const scale = SCALES[mode] ?? SCALES.major
const qualities = DEGREE_QUALITIES[mode] ?? DEGREE_QUALITIES.major
return scale.map((degree, i) => noteName(rootIdx + degree) + qualities[i])
}
// ─── Progression suggestions ─────────────────────────────────────────────────
/**
* Returns common chord progressions transposed to the given key.
*
* For non-diatonic degrees (e.g. bVII in rock), the quality falls back to a
* major triad rather than silently producing a wrong chord name.
*
* @param {string} root
* @param {'major'|'minor'} mode
* @returns {{ genre: string, rn: string[], chords: string[] }[]}
*/
export function getSuggestedProgressions(root, mode) {
const rootIdx = noteIndex(root)
if (rootIdx === -1) return []
const scale = SCALES[mode] ?? SCALES.major
const qualities = DEGREE_QUALITIES[mode] ?? DEGREE_QUALITIES.major
return Object.values(PROGRESSIONS).map(prog => {
const chords = prog.degrees.map(semitones => {
const noteIdx = (rootIdx + semitones) % 12
const name = noteName(noteIdx)
const degreeIdx = scale.indexOf(semitones)
// Diatonic degree → use proper quality; chromatic (e.g. bVII) → major triad
const quality = degreeIdx >= 0 ? qualities[degreeIdx] : ''
return name + quality
})
return { genre: prog.name, rn: prog.rn, chords }
})
}
// ─── Chroma-based chord matching ─────────────────────────────────────────────
/**
* Matches the most likely chord from a chroma energy vector.
*
* The algorithm scores each candidate chord by comparing in-chord vs
* out-of-chord energy, with bonuses for bass-note and diatonic alignment.
* Returns null when no unambiguous winner is found (e.g. during a transition).
*
* @param {Float32Array|number[]} chroma 12-element pitch-class energy (01)
* @param {{ root: string, mode: string }} keyInfo
* @param {number|null} [bassPC=null] Pitch class of the detected bass note
* @param {boolean} [strictDiatonic=false] Only consider diatonic chords
* @param {number} [minScore] Override default minimum match score
* @param {number} [minMargin] Override default ambiguity margin
* @returns {string|null} Chord name, e.g. 'Am7', or null if ambiguous
*/
export function matchChordFromChroma(
chroma,
keyInfo,
bassPC = null,
strictDiatonic = false,
minScore = CHORD_MATCH_MIN_SCORE,
minMargin = CHORD_MATCH_MIN_MARGIN,
) {
if (!keyInfo?.root) return null
const diatonicSet = new Set(getChordsInKey(keyInfo.root, keyInfo.mode))
let best = { name: null, score: -Infinity }
let secondScore = -Infinity
for (let r = 0; r < 12; r++) {
for (const typeKey of MATCH_CHORD_TYPES) {
const type = CHORD_TYPES[typeKey]
const chordName = noteName(r) + type.suffix
if (strictDiatonic && !diatonicSet.has(chordName)) continue
const tones = new Set(type.intervals.map(i => (r + i) % 12))
let inEnergy = 0, outEnergy = 0
for (let pc = 0; pc < 12; pc++) {
if (pc === r) {
// Root carries the strongest identity signal — double weight
inEnergy += chroma[pc] * 2
} else if (tones.has(pc)) {
inEnergy += chroma[pc]
} else {
outEnergy += chroma[pc]
}
}
// Skip near-silence
if (inEnergy + outEnergy < 0.05) continue
const coverageScore = inEnergy / (inEnergy + outEnergy * 0.5)
const bassBonus = bassPC !== null && r === bassPC ? 0.15 : 0
const diatonicBonus = diatonicSet.has(chordName) ? 0.10 : 0
const finalScore = coverageScore + bassBonus + diatonicBonus
if (finalScore > best.score) {
secondScore = best.score
best = { name: chordName, score: finalScore }
} else if (finalScore > secondScore) {
secondScore = finalScore
}
}
}
const clearWinner = best.score >= minScore && (best.score - secondScore) >= minMargin
return clearWinner ? best.name : null
}
// ─── Roman numeral notation ───────────────────────────────────────────────────
/**
* Converts a chord name to its Roman numeral relative to a key.
*
* Non-diatonic (borrowed/chromatic) chords are returned with a flat prefix,
* e.g. 'Bb' in C major '♭VII'. Previously this always returned '♭I'.
*
* @param {string} chordName e.g. 'Am', 'G7'
* @param {string} keyRoot e.g. 'C'
* @param {string} keyMode e.g. 'major'
* @returns {string}
*/
export function toRomanNumeral(chordName, keyRoot, keyMode) {
if (!chordName || !keyRoot) return '?'
const match = chordName.match(/^([A-G][b#]?)(.*)$/)
if (!match) return '?'
const [, root, quality] = match
const chordRootIdx = noteIndex(root)
const keyRootIdx = noteIndex(keyRoot)
if (chordRootIdx < 0 || keyRootIdx < 0) return '?'
const semitones = ((chordRootIdx - keyRootIdx) + 12) % 12
const scale = SCALES[keyMode] ?? SCALES.major
const degreeIdx = scale.indexOf(semitones)
let rn
if (degreeIdx >= 0) {
rn = ROMAN_NUMERALS[degreeIdx]
} else {
// Chromatic chord: find the nearest diatonic degree above and flat it
const nearestAbove = scale.findIndex(d => d > semitones)
const refDegree = nearestAbove >= 0 ? nearestAbove : 0
rn = '♭' + ROMAN_NUMERALS[refDegree]
}
const isMinorQuality = /^m(?!aj)/.test(quality) || quality === 'dim' || quality === 'm7b5'
return isMinorQuality ? rn.toLowerCase() : rn
}
// ─── Repeating progression detection ─────────────────────────────────────────
/**
* Scans recent chord history for a repeating pattern of length 26.
*
* Returns the most recently completed pattern that appears at least twice
* within the last 20 chords. Longer patterns that repeat are preferred over
* shorter ones via a `repetitions × length` score.
*
* @param {string[]} history Ordered list of chord names
* @returns {string[]|null} Detected repeating pattern, or null
*/
export function detectRepeatingProgression(history) {
if (!history || history.length < 4) return null
const window = history.slice(-20)
let best = null, bestScore = 0
for (let len = 2; len <= 6; len++) {
if (len * 2 > window.length) break
const candidate = window.slice(-len)
let reps = 0
// Count non-overlapping matches from left to right
let i = 0
while (i <= window.length - len) {
const matches = candidate.every((c, j) => c === window[i + j])
if (matches) {
reps++
i += len // skip past this match to avoid overlaps
} else {
i++
}
}
const score = reps * len
if (reps >= 2 && score > bestScore) {
bestScore = score
best = candidate
}
}
return best
}
// ─── Utility ─────────────────────────────────────────────────────────────────
/**
* Returns the interval name for a semitone distance (011).
* @param {number} semitones
* @returns {string}
*/
export function intervalName(semitones) {
const names = [
'Unison', 'Minor 2nd', 'Major 2nd', 'Minor 3rd', 'Major 3rd',
'Perfect 4th', 'Tritone', 'Perfect 5th', 'Minor 6th',
'Major 6th', 'Minor 7th', 'Major 7th',
]
return names[((semitones % 12) + 12) % 12] ?? 'Unknown'
}
/**
* Transposes a chord name by a given number of semitones.
* @param {string} chordName e.g. 'Am7'
* @param {number} semitones Positive = up, negative = down
* @returns {string}
*/
export function transposeChord(chordName, semitones) {
const match = chordName.match(/^([A-G][b#]?)(.*)$/)
if (!match) return chordName
const newRoot = noteName(noteIndex(match[1]) + semitones)
return newRoot + match[2]
}
/**
* Transposes an entire progression by a given number of semitones.
* @param {string[]} chords
* @param {number} semitones
* @returns {string[]}
*/
export function transposeProgression(chords, semitones) {
return chords.map(c => transposeChord(c, semitones))
}
-12
View File
@@ -1,12 +0,0 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
server: {
port: 5173,
proxy: {
'/api': 'http://localhost:8000',
},
},
})
+20
View File
@@ -0,0 +1,20 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="description" content="Real-time key and chord detection for live jams. Play any instrument into your mic and JamBuddy identifies the key, chords, and tempo — fully offline." />
<meta name="theme-color" content="#0f0f0f" />
<link rel="apple-touch-icon" href="apple-touch-icon.png" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="apple-mobile-web-app-title" content="JamBuddy" />
<!-- Production CSP. dev HMR runs same-origin so 'self' covers the ws upgrade. -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' http://127.0.0.1:5173 ws://127.0.0.1:5173; style-src 'self' 'unsafe-inline'; img-src 'self' data:; media-src 'self' blob:; connect-src 'self';" />
<title>WhatTheFlat ♭? - JamBuddy</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
-31
View File
@@ -1,31 +0,0 @@
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from api.config import settings
from api.routers import chat
app = FastAPI(title="WhatTheFlat API", version="0.1.0")
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(chat.router, prefix="/api")
@app.get("/api/health")
async def health():
return {"status": "ok", "ai_mode": settings.ai_mode}
def serve():
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
if __name__ == "__main__":
serve()
+11258
View File
File diff suppressed because it is too large Load Diff
+71
View File
@@ -0,0 +1,71 @@
{
"name": "jambuddy",
"description": "A jam session companion app that provides a chromatic tuner, chord progressions, and more.",
"version": "0.6.2",
"private": true,
"type": "module",
"main": "electron/main.cjs",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"electron:dev": "concurrently -k \"vite\" \"wait-on http://127.0.0.1:5173 && electron .\"",
"electron:build": "vite build && electron-builder",
"electron:build:win": "vite build && electron-builder --win --publish never",
"electron:build:mac": "vite build && electron-builder --mac --publish never",
"electron:build:linux": "vite build && electron-builder --linux --publish never"
},
"dependencies": {
"pitchy": "^4.1.0",
"react": "^19.2.4",
"react-dom": "^19.2.4"
},
"devDependencies": {
"@tailwindcss/vite": "^4.2.1",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.1.4",
"concurrently": "^9.2.1",
"electron": "^40.7.0",
"electron-builder": "^26.8.1",
"tailwindcss": "^4.2.1",
"vite": "^7.3.1",
"vite-plugin-pwa": "^1.3.0",
"wait-on": "^9.0.4"
},
"build": {
"appId": "com.jambuddy.app",
"productName": "JamBuddy",
"files": [
"dist/**/*",
"electron/**/*",
"node_modules/**/*",
"package.json"
],
"directories": {
"buildResources": "dist",
"output": "release"
},
"win": {
"target": "nsis",
"icon": "assets/whattheflat-logo.png",
"forceCodeSigning": false
},
"mac": {
"hardenedRuntime": true,
"entitlements": "electron/entitlements.mac.plist",
"entitlementsInherit": "electron/entitlements.mac.plist",
"extendInfo": {
"NSMicrophoneUsageDescription": "WhatTheFlat needs access to your microphone to detect pitch and provide the tuner."
}
},
"linux": {
"target": "AppImage",
"icon": "assets/whattheflat-logo.png"
},
"nsis": {
"oneClick": false,
"allowToChangeInstallationDirectory": true
}
}
}
-236
View File
@@ -1,236 +0,0 @@
# WhatTheFlat 🎸
### Product Requirements Document v0.1
> *Open-source live jam analyzer — helping musicians find the key, follow the harmony, and level up together.*
---
## 1. Vision
**WhatTheFlat** is a free, open-source web app that listens to a live jam session in real time, identifies the key and chord being played, and displays beginner-friendly guidance — scales, next chords, and simple melodic patterns — so every musician in the room can contribute, regardless of experience level.
The core belief: **jams should be inclusive**. A seasoned guitarist shouldn't have to stop to explain music theory. WhatTheFlat does it for them, silently, in real time.
---
## 2. Problem Statement
- Amateur musicians struggle to find the key when joining a jam they didn't start
- Beginners don't know which notes are "safe" to play over a chord progression
- There's no affordable, low-friction tool that bridges music theory and live performance
- Existing tools (like guitar tuners or DAWs) are either too simple or too complex
---
## 3. Target Users
| User | Description |
|---|---|
| **The Beginner** | Just started an instrument, wants to follow along without killing the vibe |
| **The Intermediate** | Knows a few scales but struggles to apply theory in real time |
| **The Jam Host** | Sets up the session and wants everyone to stay in the same key |
| **The Teacher** | Uses jams as a teaching tool, wants visual aids for students |
---
## 4. Core Features
### 4.1 Live Key Detection
- Capture audio from device microphone in real time
- Analyze incoming audio using pitch detection (e.g. YIN algorithm or ML model)
- Identify the **root note** and **mode** (major, minor, dorian, mixolydian, etc.)
- Display current detected key prominently: e.g. **"You're in A Minor"**
- Show confidence level so users understand when detection is uncertain
- Latency target: < 500ms from sound to display
### 4.2 Chord Recognition
- Detect the chord being played in real time
- Show chord name: e.g. **Am → F → C → G**
- Build a live scrolling chord history for the last 30 seconds
- Highlight the current chord in the progression
### 4.3 Chord Progression Suggestions
- Based on detected key, suggest common chord progressions that fit
- Categorize by genre/feel: Blues, Jazz, Folk, Rock, Pop
- Show the progression in Roman numeral notation (IIVV) AND actual chord names
- Allow user to tap/click a suggested progression to "lock it in" as a reference
### 4.4 Beginner Melody Helper
- For the detected key, show a visual **"safe notes"** panel — a highlighted instrument diagram
- Guitar fretboard view
- Piano keyboard view
- Generic note list (for other instruments)
- Show the **pentatonic scale** first (most beginner-friendly), with option to expand to full scale
- Highlight notes that sound especially good over the current chord (chord tones)
- Show a simple **melodic pattern of the bar** — a looping, beginner-friendly phrase they can follow
### 4.5 Visual Jam Dashboard
- Clean, readable display meant to be seen from across a room
- Show at a glance:
- Current key
- Current chord
- Next likely chord (based on progression history)
- Safe notes to play
- Dark mode by default (stage-friendly)
- Large font, high contrast
### 4.6 AI Music Theory Assistant (Claude Integration)
- Powered by Anthropic's Claude API
- Users can ask questions like:
- *"What's a good lick to play over this chord?"*
- *"Why does the F chord sound tense here?"*
- *"Give me a beginner melody in this key"*
- Claude responds in plain, non-jargon language
- Can suggest chord substitutions, extensions (7ths, 9ths), and passing chords
- All responses are **beginner-aware** — no unexplained jargon
---
## 5. MVP Scope (v0.1)
For the first open-source demo, the MVP should deliver:
- [x] Microphone capture in browser (Web Audio API)
- [x] Pitch detection → key identification
- [x] Display current key and detected chord
- [x] Show pentatonic scale for detected key (note list + basic fretboard)
- [x] 35 suggested chord progressions that fit the key
- [x] Claude-powered chat assistant for theory questions
- [x] Dark mode UI, mobile-friendly
**Not in MVP:**
- Multi-instrument separation
- MIDI input support
- Session recording/export
- User accounts or history
- Real-time collaboration (multiple users same session)
---
## 6. Technical Architecture
### Frontend
- **Framework**: React (Vite)
- **Audio**: Web Audio API + `pitchy` or `aubio.js` for pitch detection
- **Visualizations**: `Tone.js` for music utilities, custom SVG for fretboard/keyboard
- **Styling**: Tailwind CSS
- **Hosting**: Vercel / Netlify (static deploy)
### AI Layer
- **Model**: Claude (`claude-sonnet-4-20250514`) via Anthropic API
- **Usage**:
- Theory assistant chat
- Chord progression generation given key + genre
- Melody suggestion generation
- **Prompt strategy**: System prompt primes Claude as a friendly, beginner-aware music teacher
### Audio Pipeline
```
Microphone Input
Web Audio API (AudioContext)
Pitch Detection (YIN / pitchy)
Note → Chord Identification
Key Estimation (sliding window analysis)
UI Update + Claude Context Refresh
```
### Open Source Stack
- Repo: GitHub (MIT License)
- CI: GitHub Actions
- Contributing: standard fork/PR model with CONTRIBUTING.md
---
## 7. Music Theory Engine
The core theory logic should be implemented as a standalone JS module (`@whattheflat/theory`) so it can be reused or contributed to independently.
### Required functions:
```
detectKey(noteHistory[]) → { root, mode, confidence }
getChordsInKey(root, mode) → Chord[]
getSuggestedProgressions(root, mode, genre?) → Progression[]
getPentatonicScale(root, mode) → Note[]
getFullScale(root, mode) → Note[]
getChordTones(chord) → Note[]
getBeginnerPattern(key, currentChord) → MelodicPattern
```
### Modes to support (MVP):
- Major (Ionian)
- Natural Minor (Aeolian)
- Pentatonic Major
- Pentatonic Minor
### Modes to support (v1+):
- Dorian, Mixolydian, Lydian, Phrygian
- Blues scale
- Harmonic minor
---
## 8. UX Principles
1. **Readable at distance** — primary info visible from 2 metres away
2. **Zero setup** — tap "Start Listening", grant mic permission, done
3. **Non-judgmental** — never says "wrong note", always says "try these"
4. **Progressive complexity** — beginners see pentatonic; advanced users can unlock modes, extensions, substitutions
5. **Mobile first** — works on a phone propped up on a music stand
---
## 9. Beginner Learning Path (stretch goal)
A guided progression for users who want to improve over time:
| Level | Unlocks |
|---|---|
| 🟢 Starter | Pentatonic scale, 3 safe chords |
| 🔵 Follower | Full diatonic scale, chord tones highlighted |
| 🟣 Contributor | Chord extensions (7th, 9th), passing chords |
| 🔴 Improvisor | Modal awareness, substitutions, AI-generated licks |
Progress is stored in localStorage — no account needed.
---
## 10. Open Source Contribution Areas
| Area | Skills needed |
|---|---|
| Pitch detection accuracy | DSP, audio engineering |
| Music theory engine | Music theory + JavaScript |
| Instrument diagrams | SVG, React |
| Genre-specific progressions | Music knowledge |
| Claude prompt engineering | AI, music theory |
| Accessibility (screen readers, colorblind modes) | A11y |
| Mobile app wrapper | React Native / Capacitor |
| Translation / i18n | Language + music terminology |
---
## 11. Success Metrics
- Time from opening app to understanding what key they're in: **< 10 seconds**
- % of beginner users who successfully play a note in the right key on first jam: **target 80%**
- GitHub stars at 3 months: **500+**
- Average Claude assistant response usefulness (self-reported): **> 4/5**
---
## 12. Name & Branding Notes
- **Name**: WhatTheFlat
- **Tagline**: *"Real-time key detection for real humans"*
- **Tone**: Warm, slightly cheeky, musician-coded humour
- **Logo concept**: A flat symbol (♭) with a question mark or waveform integrated
- **Color palette**: Dark background (#0f0f0f), accent in electric purple or warm amber
---
*Document maintained by the WhatTheFlat open source community. PRs welcome.*
Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

-23
View File
@@ -1,23 +0,0 @@
[project]
name = "whattheflat"
version = "0.1.0"
description = "Real-time key detection for real humans"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"fastapi>=0.115.0",
"uvicorn[standard]>=0.30.0",
"anthropic>=0.40.0",
"ollama>=0.4.0",
"python-dotenv>=1.0.0",
"pydantic>=2.0.0",
"pydantic-settings>=2.0.0",
]
[dependency-groups]
dev = [
"httpx>=0.27.0",
]
[tool.uv]
package = false
+185
View File
@@ -0,0 +1,185 @@
// Loop-detection truth fixtures (task C-30) — the contract L-30 must satisfy.
//
// Each fixture is a realistic `chordHistory` as App.jsx commits it (plain chord
// name strings from matchChordFromChroma — "C", "Am", "G7", "Cmaj7"…; the commit
// layer at App.jsx:363-365 suppresses ADJACENT duplicates, so histories here are
// adjacent-dup-free except the one fixture that deliberately tests dups) plus the
// loop a musician would say they are playing (`expect`, or null for "no loop").
//
// Consumed by scripts/smoke.mjs:
// · fixture without expectedFail that fails → smoke exits non-zero (regression)
// · fixture with expectedFail that fails → annotated expected-fail (printed)
// · fixture with expectedFail that PASSES → smoke FAILS: stale marker, flip it
// L-30's definition of done = every expectedFail marker removed, all green.
//
// ─── FAILURE MAP OF THE PRE-L-30 ALGORITHM (historical — all fixed by L-30) ──
// (theory.js `detectRepeatingProgression` as of C-30, every fixture RUN against
// it 2026-07-10; L-30 redesigned the function and removed every expectedFail
// marker — all 17 fixtures now pass as plain regression guards)
//
// The pre-L-30 matcher: window = last 32 commits; candidate lengths 26; EXACT
// contiguous occurrence counting (scan advances by len on match, by 1 on miss);
// requires reps ≥ 2; score = reps × len²; returns the canonical (lexicographically
// smallest) rotation of the best candidate.
//
// 1. len²-weighting artifact — self-overlaps of a short vamp beat the vamp:
// a 2-chord vamp ×4 reports the 3-chord [Am,G,Am] (2 reps × 3² = 18 beats the
// true pair's 4 × 2² = 16); a SUSTAINED 2-chord vamp (full 32 window) reports
// the bogus 5-chord [Am,Am,G,Am,G] (fixtures: vamp-2x4, vamp-2-sustained).
// 2. One SUBSTITUTED misdetection inside one rep of a 3-loop flips the winner to
// a wrong 4-pattern: [F,C,Am,F] straddling the noise scores 2 × 4² = 32 and
// beats the real [C,Am,F] at 3 × 3² = 27 (fixture: spurious-substitution).
// NOTE: one INSERTED extra chord is survivable today — the miss-by-1 scan
// realigns after it (fixture spurious-insert-once stays green).
// 3. Insertions in 2 of 4 reps → the same wrong-4-pattern failure (spurious-2of4).
// 4. Consecutive duplicate commits of one chord create a wrong 4-pattern
// [C,Am,F,C] (2 × 16 > 3 × 9) instead of collapsing to the 3-loop
// (fixture: dup-commit). Unreachable from TODAY'S commit layer (App.jsx
// dedupes adjacent commits) — the fixture makes the detector safe standalone,
// per L-30's "collapse consecutive duplicates" requirement.
// 5. Loop lengths 78 are structurally impossible (len caps at 6): a 7- or
// 8-chord loop ×2 returns a truncated 6-chord slice of itself, not the loop
// (fixtures: seven-x2, eight-x2). This is the likely reading of the user's
// "5 and then 2 others": a 5+2 = 7-chord FORM can never be detected.
// 6. No recency weighting: after a section change (loop A ×3 → loop B ×3) the
// OLD 4-chord loop A still outscores the current 3-chord loop B
// (3 × 4² = 48 > 3 × 3² = 27), so the display is stuck on the previous
// section (fixture: section-change).
//
// What already WORKS at the pure-function level (regression guards — L-30 must
// keep these green): clean 2×3 / 3×2 / 3×3 / 4×3 / 6×2 loops; one inserted
// spurious chord; a 5-chord loop + 2-chord tag/turnaround, both with and without
// the loop resuming (the occurrence scan skips foreign chords). So if the user
// sees the 5+tag case fail live, the loss is in the App.jsx commit layer
// (miss-4-then-clear / 2-consecutive-identical vote) — that is L-31's territory,
// not this function's.
// ─────────────────────────────────────────────────────────────────────────────
/**
* Rotation-minimal normalization a LOCAL REPLICA of theory.js's private
* `canonicalize` (it is not exported, and theory.js is locked to L-30, so we
* must not touch it to export it). Same semantics byte-for-byte: pick the
* lexicographically smallest rotation via '\0'-joined comparison, so [C,Am,F],
* [Am,F,C] and [F,C,Am] all compare equal as loops.
*/
export function canonicalLoop(pattern) {
let best = pattern
for (let i = 1; i < pattern.length; i++) {
const rot = [...pattern.slice(i), ...pattern.slice(0, i)]
if (rot.join('\0') < best.join('\0')) best = rot
}
return best
}
// repeat a loop n times into one flat history
const reps = (loop, n) => Array.from({ length: n }, () => loop).flat()
export const LOOP_FIXTURES = [
// ── Regression guards: what works today MUST keep working ──────────────────
{
id: 'clean-2x3',
description: 'clean 2-chord vamp played 3× — the minimal detectable loop',
history: reps(['Am', 'G'], 3),
expect: ['Am', 'G'],
},
{
id: 'clean-3x2',
description: 'clean 3-chord loop played exactly 2× (6 commits, the minimum history)',
history: reps(['C', 'Am', 'F'], 2),
expect: ['C', 'Am', 'F'],
},
{
id: 'clean-3x3',
description: 'clean 3-chord loop played 3× — the plain "3 chords return" case',
history: reps(['C', 'Am', 'F'], 3),
expect: ['C', 'Am', 'F'],
},
{
id: 'clean-4x3',
description: 'clean 4-chord axis loop played 3×',
history: reps(['C', 'G', 'Am', 'F'], 3),
expect: ['C', 'G', 'Am', 'F'],
},
{
id: 'clean-6x2',
description: 'clean 6-chord loop played 2× — the top of the current length range',
history: reps(['C', 'Am', 'Dm', 'G', 'Em', 'F'], 2),
expect: ['C', 'Am', 'Dm', 'G', 'Em', 'F'],
},
{
id: 'spurious-insert-once',
description: '3-chord loop with ONE spurious chord INSERTED mid-rep (C Am F | C Am E7 F | C Am F) — the scan realigns after an insertion',
history: ['C', 'Am', 'F', 'C', 'Am', 'E7', 'F', 'C', 'Am', 'F'],
expect: ['C', 'Am', 'F'],
},
{
id: 'five-plus-tag-resumes',
description: '5-chord loop ×2, a 2-chord turnaround tag (Dm E7), then the loop resumes — loop must survive the tag',
history: [...reps(['Am', 'F', 'C', 'G', 'Em'], 2), 'Dm', 'E7', 'Am', 'F', 'C', 'G', 'Em'],
expect: ['Am', 'F', 'C', 'G', 'Em'],
},
{
id: 'five-plus-tag-at-end',
description: '5-chord loop ×2 then 2 foreign chords with the history ending there — the just-played loop must still be reported',
history: [...reps(['Am', 'F', 'C', 'G', 'Em'], 2), 'Dm', 'E7'],
expect: ['Am', 'F', 'C', 'G', 'Em'],
},
{
id: 'chromatic-null',
description: 'non-repeating chromatic walk — no loop exists, must report null',
history: ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G'],
expect: null,
},
// ── Failure modes of the pre-L-30 algorithm — fixed by L-30 ────────────────
{
id: 'vamp-2x4',
description: 'clean 2-chord vamp played 4× — must still report the pair, not a self-overlap',
history: reps(['Am', 'G'], 4),
expect: ['Am', 'G'],
},
{
id: 'vamp-2-sustained',
description: 'sustained 2-chord vamp filling the whole window (×16) — the everyday two-chord jam',
history: reps(['Am', 'G'], 16),
expect: ['Am', 'G'],
},
{
id: 'spurious-substitution',
description: '3-chord loop ×4 with ONE substituted misdetection (Am read as E7 in the third rep) — must still report the 3-loop',
history: ['C', 'Am', 'F', 'C', 'Am', 'F', 'C', 'E7', 'F', 'C', 'Am', 'F'],
expect: ['C', 'Am', 'F'],
},
{
id: 'spurious-2of4',
description: '3-chord loop ×4 with an inserted misdetection in two different reps (E7, then Dm7) — realistic sustained noise',
history: ['C', 'Am', 'F', 'C', 'Am', 'E7', 'F', 'C', 'Am', 'F', 'C', 'Dm7', 'Am', 'F'],
expect: ['C', 'Am', 'F'],
},
{
id: 'dup-commit',
description: 'consecutive duplicate commit of the same chord inside an otherwise clean 3-loop (C Am F C C Am F …) — dups must collapse',
history: ['C', 'Am', 'F', 'C', 'C', 'Am', 'F', 'C', 'Am', 'F'],
expect: ['C', 'Am', 'F'],
},
{
id: 'seven-x2',
description: '7-chord loop played 2× — beyond the pre-L-30 length-6 cap',
history: reps(['Em', 'G', 'D', 'A', 'Em', 'C', 'B7'], 2),
expect: ['Em', 'G', 'D', 'A', 'Em', 'C', 'B7'],
},
{
id: 'eight-x2',
description: '8-chord loop (extended andalusian form) played 2× — beyond the pre-L-30 cap',
history: reps(['Am', 'G', 'F', 'E7', 'Am', 'C', 'Dm', 'E7'], 2),
expect: ['Am', 'G', 'F', 'E7', 'Am', 'C', 'Dm', 'E7'],
},
{
id: 'section-change',
description: 'section change: 4-chord loop A ×3, then 3-chord loop B ×3 — must report B, the loop being played NOW',
history: [...reps(['C', 'G', 'Am', 'F'], 3), ...reps(['Dm7', 'G7', 'Cmaj7'], 3)],
expect: ['Dm7', 'G7', 'Cmaj7'],
},
]
export default LOOP_FIXTURES
+1586
View File
File diff suppressed because it is too large Load Diff
+539
View File
@@ -0,0 +1,539 @@
// KB quality gate — validates src/data/kb/ against the contract in src/data/kb/SCHEMA.md.
// Run: node scripts/validate-kb.mjs (exit 1 on any error)
//
// Lib mode: scripts/smoke.mjs imports this file with KB_VALIDATE_AS_LIB=1 set to
// reuse the exported pure checks (checkLick, checkPianoRecipe, checkBassPlay,
// checkPianoLick, LEVELS, LICK_TECHNIQUES, PIANO_LICK_TECHNIQUES,
// PIANO_LICK_APPROACHES, PIANO_LICK_MAX_OFFSET, MAX_HAND_SPAN, MIN_PLAYS_BASS,
// BASS_APPROACHES, BASS_MAX_OFFSET) against in-memory fixtures — same logic,
// no copy. When the env var is absent the script runs the full KB validation
// as before.
import { readdirSync, existsSync } from 'node:fs'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { dirname, join } from 'node:path'
import { CHORD_TYPES } from '../src/lib/theory.js'
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..')
const KB = join(ROOT, 'src', 'data', 'kb')
const MODES = ['major', 'minor', 'dorian', 'phrygian', 'lydian', 'mixolydian']
const OPEN_PC = [4, 9, 2, 7, 11, 4] // EADGBe low-E first
const PERFECT_FIFTH = 7
const MIN_PROGRESSIONS = 4
const MIN_PLAYS = 2
// Bass floor is 1, not 2 (SCHEMA.md "Bass play"): the band wants one bassline
// at a time, and rule 4's "idiomatically different" bar invites filler at 2.
export const MIN_PLAYS_BASS = 1
const MAX_SPAN = 4
// Optional progression/lick difficulty tags (SCHEMA.md — absent = 'foundation').
export const LEVELS = ['foundation', 'intermediate']
// Fixed technique vocabulary for licks — both the techniques[] summary and each
// tab note's optional technique must come from this list (SCHEMA.md).
export const LICK_TECHNIQUES = [
'hammer-on', 'pull-off', 'slide', 'bend',
'double-stop', 'ghost-note', 'chromatic-approach', 'vibrato',
]
const LICK_MAX_FRET = 15
const errors = []
const err = (where, msg) => errors.push(`${where}: ${msg}`)
// Resolve a degree string ('3', 'b9', '13'…) to a pitch class relative to the
// chord root, through the quality's intervals where the degree is quality-dependent.
function resolveDegree(deg, quality) {
const iv = CHORD_TYPES[quality].intervals
const fixed = { 1: 0, b9: 1, 9: 2, '#9': 3, 11: 5, '#11': 6, b5: 6, b13: 8, 13: 9, 6: 9, b3: 3, b7: 10 }
if (deg === '3') return iv.find(i => i === 3 || i === 4) ?? iv.find(i => i === 2 || i === 5) ?? null
if (deg === '5') return iv.find(i => i === 6 || i === 7 || i === 8) ?? null
if (deg === '7') return iv.find(i => i === 9 || i === 10 || i === 11) ?? null
return fixed[deg] ?? null
}
function checkGuitarShape(where, chordStep, quality) {
const { shape, extensions = [] } = chordStep
if (!shape) return err(where, 'missing shape')
const strings = shape.offsets ?? shape.frets
if (!Array.isArray(strings) || strings.length !== 6)
return err(where, 'offsets/frets must be an array of 6 (low E first)')
const isMovable = !!shape.offsets
if (isMovable) {
if (!(shape.rootStr >= 1 && shape.rootStr <= 6)) return err(where, `bad rootStr ${shape.rootStr}`)
if (strings[6 - shape.rootStr] !== 0) return err(where, 'offset on the root string must be 0')
} else {
if (!(shape.onlyRoot >= 0 && shape.onlyRoot <= 11)) return err(where, 'open shape needs onlyRoot (pc 0-11)')
}
const fretted = strings.filter(f => f !== 'x')
if (fretted.some(f => !Number.isInteger(f) || f < -2 || f > 15))
return err(where, `bad fret values: ${JSON.stringify(strings)}`)
const nonOpen = fretted.filter(f => f !== 0)
if (nonOpen.length && Math.max(...nonOpen) - Math.min(...nonOpen) > MAX_SPAN)
return err(where, `fret span > ${MAX_SPAN} — not intermediate-friendly`)
// Pitch-class verification: every sounded note must belong to the chord
// (quality intervals + declared extensions); defining tones must be present.
const iv = CHORD_TYPES[quality].intervals
const allowed = new Set(iv)
for (const ext of extensions) {
const pc = resolveDegree(ext, quality)
if (pc === null) return err(where, `unresolvable extension '${ext}' for ${quality}`)
allowed.add(pc)
}
const rootRel = isMovable ? (12 - OPEN_PC[6 - shape.rootStr]) % 12 : null
const sounded = new Set()
strings.forEach((f, i) => {
if (f === 'x') return
const pc = isMovable
? (OPEN_PC[i] + rootRel + f + 24) % 12
: (OPEN_PC[i] + f - shape.onlyRoot + 24) % 12
sounded.add(pc)
})
for (const pc of sounded)
if (!allowed.has(pc)) return err(where, `sounded pc ${pc} is not in ${quality} (+ext) — shape misspells the chord`)
const required = iv.filter(i =>
i !== PERFECT_FIFTH
&& !(chordStep.rootless && i === 0)
&& !(chordStep.omit3 && (i === 3 || i === 4)))
for (const pc of required)
if (!sounded.has(pc)) return err(where, `defining tone pc ${pc} of ${quality} missing from shape`)
}
// Piano hand-span rule (SCHEMA.md rule 3: "one hand per recipe stays within a
// 10th"). Enforced as ≤ 15 semitones — a minor 10th, the widest reading of
// "a 10th" — so the hand-verified 14-semitone ø11 rootless voicing in
// jazz/piano.js (P-22) stays legal while anything wider fails. Task C-22.
export const MAX_HAND_SPAN = 15
// Resolve one hand's degree list to stacked absolute semitone offsets per the
// documented convention (src/data/kb/jazz/piano.js header, ~line 14): order
// inside a hand = voicing order low→high, each note placed in the nearest
// position strictly above the previous (a repeated pitch class = octave up).
// Returns null if any degree is unresolvable (reported separately by caller).
function stackHand(degs, quality) {
const notes = []
for (const d of degs) {
const pc = resolveDegree(d, quality)
if (pc === null) return null
if (!notes.length) { notes.push(pc); continue }
const prev = notes[notes.length - 1]
const step = (pc - (prev % 12) + 12) % 12
notes.push(prev + (step === 0 ? 12 : step))
}
return notes
}
// Pure piano-recipe validation. Returns an array of where-prefixed error
// strings (empty = valid). Exported for reuse by scripts/smoke.mjs (lib mode).
export function checkPianoRecipe(where, chordStep, quality) {
const out = []
const e = (msg) => out.push(`${where}: ${msg}`)
if (!CHORD_TYPES[quality]) { e(`unknown quality '${quality}'`); return out }
const { recipe } = chordStep
if (!recipe) { e('missing recipe'); return out }
for (const hand of ['LH', 'RH']) {
const degs = recipe[hand]
if (degs === undefined) continue
if (!Array.isArray(degs) || !degs.length) { e(`${hand} must be a non-empty array`); continue }
if (degs.length > 5) e(`${hand} has ${degs.length} notes — one hand, max 5`)
for (const d of degs)
if (resolveDegree(d, quality) === null) e(`unresolvable degree '${d}' for ${quality}`)
const stacked = stackHand(degs, quality)
if (stacked === null) continue // unresolvable degree already reported
const span = stacked[stacked.length - 1] - stacked[0]
if (span > MAX_HAND_SPAN)
e(`${hand} [${degs.join(' ')}] spans ${span} semitones stacked low→high — max ${MAX_HAND_SPAN} (a minor 10th; SCHEMA rule 3, one hand within a 10th)`)
}
if (recipe.LH === undefined && recipe.RH === undefined) e('recipe needs LH and/or RH')
return out
}
// ── Bass plays (SCHEMA.md "Bass play") ────────────────────────────────────────
// Degree-based per-station patterns: one chords[] entry per progression step,
// each a non-empty ORDERED pattern of {deg,…} chord/color tones (resolved
// through the step's quality — a degree can't misspell a pitch class) and
// typed {approach,…} notes whose pitch is DERIVED from the next station's
// root, so the validator can allow the non-chord tone without blessing
// arbitrary chromatics. Data never encodes strings/frets (key-agnostic,
// hard rule 1); the renderer places patterns on EADG, frets 015.
export const BASS_APPROACHES = ['chrom-below', 'chrom-above', 'fifth-of-next']
// Widest legal offset above the root: an octave + a fifth keeps every pattern
// placeable on EADG within frets 015 in one position.
export const BASS_MAX_OFFSET = 19
const BASS_BEATS_PER_BAR = 4 // patterns are notated in 4 — 12/8 is `feel`
const BASS_MAX_NOTES_PER_BAR = 8 // straight-8ths density cap (rule 3)
// Pure bass-play validation. Returns an array of where-prefixed error strings
// (empty = valid). Exported for reuse by scripts/smoke.mjs (lib mode).
export function checkBassPlay(where, play, prog) {
const out = []
const e = (msg) => out.push(`${where}: ${msg}`)
if (typeof play.feel !== 'string' || !play.feel)
e("feel required — the groove in one line (e.g. 'swung 8ths, locked with the kick')")
if (play.level !== undefined && !LEVELS.includes(play.level))
e(`level must be one of ${LEVELS.join(' | ')}, got '${play.level}'`)
if (!Array.isArray(play.chords) || play.chords.length !== prog.degrees.length) {
e(`chords length ${play.chords?.length} ≠ progression length ${prog.degrees.length}`)
return out
}
play.chords.forEach((step, ci) => {
const cw = `chord[${ci}] (${prog.rn?.[ci] ?? ci})`
const quality = prog.qualities[ci]
if (!CHORD_TYPES[quality]) return e(`${cw}: unknown quality '${quality}'`)
const bars = prog.bars?.[ci] ?? 1
const pat = step?.pattern
if (!Array.isArray(pat) || !pat.length)
return e(`${cw}: pattern must be a non-empty ordered array of notes`)
if (pat.length > BASS_MAX_NOTES_PER_BAR * bars)
e(`${cw}: ${pat.length} notes > ${BASS_MAX_NOTES_PER_BAR * bars} (8ths density cap over ${bars} bar(s)) — not intermediate-friendly`)
let approachSeen = false
let rootSeen = false
let lastBeat = -Infinity
pat.forEach((n, ni) => {
const nw = `${cw} pattern[${ni}]`
if (!n || typeof n !== 'object') return e(`${nw}: note must be an object ({deg,…} or {approach,…})`)
const isDeg = n.deg !== undefined
const isApproach = n.approach !== undefined
if (isDeg === isApproach) return e(`${nw}: exactly one of deg | approach per note`)
if (isApproach) {
approachSeen = true
if (!BASS_APPROACHES.includes(n.approach))
e(`${nw}: unknown approach '${n.approach}' — allowed: ${BASS_APPROACHES.join(', ')}`)
if (n.octave !== undefined)
e(`${nw}: octave applies to deg notes only (the renderer places approaches beside the next root)`)
} else {
if (approachSeen)
e(`${nw}: deg note after an approach — approach notes must close the pattern (they lead into the next chord)`)
if (typeof n.deg !== 'string') {
e(`${nw}: deg must be a degree STRING ('1', 'b7', …), got ${JSON.stringify(n.deg)}`)
} else {
const pc = resolveDegree(n.deg, quality)
if (pc === null) e(`${nw}: unresolvable degree '${n.deg}' for ${quality}`)
if (n.deg === '1') rootSeen = true
if (n.octave !== undefined && n.octave !== 0 && n.octave !== 1)
e(`${nw}: octave, when present, must be 0 or 1 — got ${JSON.stringify(n.octave)}`)
else if (pc !== null && pc + 12 * (n.octave === 1 ? 1 : 0) > BASS_MAX_OFFSET)
e(`${nw}: '${n.deg}' octave ${n.octave} sits ${pc + 12} semitones above the root — max ${BASS_MAX_OFFSET} (an octave + a fifth; keeps the pattern in one position on EADG)`)
}
}
if (n.technique !== undefined && !LICK_TECHNIQUES.includes(n.technique))
e(`${nw}: unknown technique '${n.technique}' — allowed: ${LICK_TECHNIQUES.join(', ')}`)
if (n.beat !== undefined) {
const maxBeat = BASS_BEATS_PER_BAR * bars
if (typeof n.beat !== 'number' || !(n.beat >= 1 && n.beat < maxBeat + 1))
e(`${nw}: beat must be a number in [1, ${maxBeat + 1}) for a ${bars}-bar step, got ${JSON.stringify(n.beat)}`)
else if (n.beat < lastBeat)
e(`${nw}: beat ${n.beat} < previous beat ${lastBeat} — beats must be non-decreasing in pattern order`)
else lastBeat = n.beat
}
})
if (!rootSeen)
e(`${cw}: pattern never states the root ('1') — a bassline grounds the chord (SCHEMA "Bass play" root rule)`)
})
return out
}
// Pure lick validation (SCHEMA.md "Licks" section). Returns an array of error
// strings (already where-prefixed); mutates seenIds by adding the lick's id so
// ids stay globally unique across ALL progressions and licks (same rule as
// progression ids). Exported for reuse by scripts/smoke.mjs.
export function checkLick(where, lick, style, seenIds) {
const out = []
const e = (msg) => out.push(`${where}: ${msg}`)
if (!lick || typeof lick !== 'object') { e('lick must be an object'); return out }
if (typeof lick.id !== 'string' || !lick.id.startsWith(`${style}-`))
e(`id must be a string starting with '${style}-'`)
else if (seenIds.has(lick.id)) e(`duplicate id '${lick.id}' (ids are global across progressions AND licks)`)
else seenIds.add(lick.id)
if (!lick.name) e('name missing')
if (!LEVELS.includes(lick.level)) e(`level must be one of ${LEVELS.join(' | ')}, got '${lick.level}'`)
if (typeof lick.chordContext !== 'string' || !lick.chordContext)
e("chordContext missing (which chord/station the lick fits, e.g. 'dom7' or 'over the I7')")
const summary = new Set()
if (!Array.isArray(lick.techniques)) e('techniques must be an array (may be empty for a plain-picked lick)')
else for (const t of lick.techniques) {
if (!LICK_TECHNIQUES.includes(t)) e(`unknown technique '${t}' — allowed: ${LICK_TECHNIQUES.join(', ')}`)
summary.add(t)
}
if (!Array.isArray(lick.tab) || !lick.tab.length) { e('tab must be a non-empty ordered array of notes'); return out }
lick.tab.forEach((note, i) => {
const nw = `tab[${i}]`
if (!note || typeof note !== 'object') return e(`${nw} must be an object {string, fret, technique?}`)
if (!Number.isInteger(note.string) || note.string < 1 || note.string > 6)
e(`${nw} string must be an integer 16 (1 = high e, 6 = low E), got ${JSON.stringify(note.string)}`)
if (!Number.isInteger(note.fret) || note.fret < 0 || note.fret > LICK_MAX_FRET)
e(`${nw} fret must be an integer 0${LICK_MAX_FRET}, got ${JSON.stringify(note.fret)}`)
if (note.technique !== undefined) {
if (!LICK_TECHNIQUES.includes(note.technique))
e(`${nw} unknown technique '${note.technique}' — allowed: ${LICK_TECHNIQUES.join(', ')}`)
else if (!summary.has(note.technique))
e(`${nw} technique '${note.technique}' must also appear in the lick's techniques[] summary`)
}
})
return out
}
// ── Piano licks (SCHEMA.md "Piano licks") ────────────────────────────────────
// Degree-based melodic phrases over ONE explicit quality (guitar tab is
// instrument-truth and needs no quality; degrees need a context to resolve
// through — chordContext stays the human sentence, `quality` is the machine
// truth). Approaches are typed and DERIVED: each targets the next deg note in
// the lick (there is no "next station" inside a self-contained lick), so the
// validator can allow the non-chord tone without blessing arbitrary
// chromatics — and an approach can never close a lick (nothing to target).
//
// Piano technique vocabulary — deliberately NOT LICK_TECHNIQUES: keys don't
// bend, hammer, pull off, or sustain vibrato; chromatic-approach is redundant
// (approaches are typed notes here). The three shared words keep their
// guitar-lick meanings; grace-note (the crushed blues/gospel ornament) is
// piano-specific. smoke.mjs guards both lists' consistency.
export const PIANO_LICK_TECHNIQUES = ['slide', 'double-stop', 'ghost-note', 'grace-note']
export const PIANO_LICK_APPROACHES = ['chrom-below', 'chrom-above']
// Range cap on every RESOLVED offset (deg: pc + 12·octave; approach: derived):
// [0, 25] semitones above the root. Proof against MiniPiano's render window
// (absolute notes [0, 36], 0 = low C): place the root at its pitch class in
// the bottom octave (011); the highest possible note is then 11 + 25 = 36 —
// exactly the window's top key — so every legal lick fits in all 12 keys.
export const PIANO_LICK_MAX_OFFSET = 25
const PIANO_LICK_MAX_NOTES = 16 // 8ths over the 2-bar beat window (rule 3)
const PIANO_LICK_MAX_BEAT = 9 // exclusive: 1 ≤ beat < 9 (two 4/4 bars)
// Pure piano-lick validation. Returns an array of where-prefixed error strings
// (empty = valid); mutates seenIds like checkLick (shared global id
// namespace). Exported for reuse by scripts/smoke.mjs (lib mode).
export function checkPianoLick(where, lick, style, seenIds) {
const out = []
const e = (msg) => out.push(`${where}: ${msg}`)
if (!lick || typeof lick !== 'object') { e('lick must be an object'); return out }
if (typeof lick.id !== 'string' || !lick.id.startsWith(`${style}-`))
e(`id must be a string starting with '${style}-'`)
else if (seenIds.has(lick.id)) e(`duplicate id '${lick.id}' (ids are global across progressions AND licks)`)
else seenIds.add(lick.id)
if (!lick.name) e('name missing')
if (!LEVELS.includes(lick.level)) e(`level must be one of ${LEVELS.join(' | ')}, got '${lick.level}'`)
if (typeof lick.chordContext !== 'string' || !lick.chordContext)
e("chordContext missing (which chord/station the lick fits, e.g. 'over the ii7')")
const quality = lick.quality
if (!CHORD_TYPES[quality]) {
e(`quality must be a CHORD_TYPES key (the context every deg resolves through), got '${quality}'`)
return out // nothing below is checkable without a quality
}
const summary = new Set()
if (!Array.isArray(lick.techniques)) e('techniques must be an array (may be empty for a plain lick)')
else for (const t of lick.techniques) {
if (!PIANO_LICK_TECHNIQUES.includes(t))
e(`unknown piano technique '${t}' — allowed: ${PIANO_LICK_TECHNIQUES.join(', ')}`)
summary.add(t)
}
const notes = lick.notes
if (!Array.isArray(notes) || !notes.length) { e('notes must be a non-empty ordered array'); return out }
if (notes.length > PIANO_LICK_MAX_NOTES)
e(`${notes.length} notes > ${PIANO_LICK_MAX_NOTES} (8ths over two bars) — not intermediate-friendly`)
// Pass 1: resolved offset of every deg note (null = unresolvable/malformed),
// so approaches can look up their target (the NEXT deg note in order).
const degOffsets = notes.map((n) => {
if (!n || typeof n !== 'object' || n.deg === undefined || typeof n.deg !== 'string') return null
const pc = resolveDegree(n.deg, quality)
if (pc === null) return null
const oct = n.octave === undefined ? 0 : n.octave
return oct === 0 || oct === 1 || oct === 2 ? pc + 12 * oct : null
})
let lastBeat = -Infinity
let prevApproach = null // type of the immediately preceding approach note
notes.forEach((n, ni) => {
const nw = `notes[${ni}]`
if (!n || typeof n !== 'object') return e(`${nw}: note must be an object ({deg,…} or {approach,…})`)
const isDeg = n.deg !== undefined
const isApproach = n.approach !== undefined
if (isDeg === isApproach) return e(`${nw}: exactly one of deg | approach per note`)
if (isApproach) {
if (!PIANO_LICK_APPROACHES.includes(n.approach))
e(`${nw}: unknown approach '${n.approach}' — allowed: ${PIANO_LICK_APPROACHES.join(', ')} (piano licks have no next station; 'fifth-of-next' is bass-only)`)
if (n.octave !== undefined)
e(`${nw}: octave applies to deg notes only (approach pitch is derived from its target)`)
if (prevApproach === n.approach)
e(`${nw}: two consecutive '${n.approach}' approaches derive the identical pitch — write the note you mean as a deg, or alternate types (the enclosure)`)
// Target = the NEXT deg note in order (scan past intervening approaches).
const ti = notes.findIndex((m, i) => i > ni && m?.deg !== undefined)
if (ti === -1) {
e(`${nw}: approach cannot close a piano lick — it targets the NEXT deg note (the final note must be a deg)`)
} else if (degOffsets[ti] !== null) {
const derived = degOffsets[ti] + (n.approach === 'chrom-below' ? -1 : 1)
if (derived < 0)
e(`${nw}: chrom-below of a root-position target derives 1 — below the render window; raise the target an octave`)
else if (derived > PIANO_LICK_MAX_OFFSET)
e(`${nw}: derived pitch sits ${derived} semitones above the root — max ${PIANO_LICK_MAX_OFFSET} (fits MiniPiano's 37-key window for all 12 roots)`)
} // target exists but is itself malformed → its own error already reports it
prevApproach = n.approach
} else {
prevApproach = null
if (typeof n.deg !== 'string') {
e(`${nw}: deg must be a degree STRING ('1', 'b7', …), got ${JSON.stringify(n.deg)}`)
} else {
const pc = resolveDegree(n.deg, quality)
if (pc === null) e(`${nw}: unresolvable degree '${n.deg}' for ${quality}`)
if (n.octave !== undefined && n.octave !== 0 && n.octave !== 1 && n.octave !== 2)
e(`${nw}: octave, when present, must be 0, 1 or 2 — got ${JSON.stringify(n.octave)}`)
else if (pc !== null && degOffsets[ni] !== null && degOffsets[ni] > PIANO_LICK_MAX_OFFSET)
e(`${nw}: '${n.deg}' octave ${n.octave} sits ${degOffsets[ni]} semitones above the root — max ${PIANO_LICK_MAX_OFFSET} (fits MiniPiano's 37-key window for all 12 roots)`)
}
}
if (n.technique !== undefined) {
if (!PIANO_LICK_TECHNIQUES.includes(n.technique))
e(`${nw}: unknown piano technique '${n.technique}' — allowed: ${PIANO_LICK_TECHNIQUES.join(', ')}`)
else if (!summary.has(n.technique))
e(`${nw}: technique '${n.technique}' must also appear in the lick's techniques[] summary`)
}
if (n.beat !== undefined) {
if (typeof n.beat !== 'number' || !(n.beat >= 1 && n.beat < PIANO_LICK_MAX_BEAT))
e(`${nw}: beat must be a number in [1, ${PIANO_LICK_MAX_BEAT}) — a lick spans at most two 4/4 bars, got ${JSON.stringify(n.beat)}`)
else if (n.beat < lastBeat)
e(`${nw}: beat ${n.beat} < previous beat ${lastBeat} — beats must be non-decreasing in note order`)
else lastBeat = n.beat
}
})
return out
}
async function loadModule(path) {
return (await import(pathToFileURL(path).href)).default
}
async function main() {
const styleDirs = readdirSync(KB, { withFileTypes: true }).filter(d => d.isDirectory()).map(d => d.name)
if (!styleDirs.length) { console.error('No style folders in src/data/kb/'); process.exit(1) }
const registry = existsSync(join(KB, 'index.js')) ? await loadModule(join(KB, 'index.js')) : null
if (!registry) err('kb/index.js', 'registry missing')
const allIds = new Set()
let totals = { styles: 0, progressions: 0, plays: 0, licks: 0 }
for (const style of styleDirs) {
const dir = join(KB, style)
const w = `kb/${style}`
if (registry && !registry[style]) err('kb/index.js', `style '${style}' not registered`)
const meta = existsSync(join(dir, 'meta.js')) ? await loadModule(join(dir, 'meta.js')) : null
if (!meta) { err(w, 'meta.js missing'); continue }
if (meta.id !== style) err(`${w}/meta.js`, `id '${meta.id}' ≠ folder '${style}'`)
for (const f of ['label', 'feel', 'character']) if (!meta[f]) err(`${w}/meta.js`, `missing ${f}`)
const progs = existsSync(join(dir, 'progressions.js')) ? await loadModule(join(dir, 'progressions.js')) : null
if (!Array.isArray(progs) || !progs.length) { err(w, 'progressions.js missing/empty'); continue }
if (progs.length < MIN_PROGRESSIONS) err(w, `${progs.length} progressions < ${MIN_PROGRESSIONS}`)
const progById = {}
for (const p of progs) {
const pw = `${w}/progressions.js [${p.id}]`
if (!p.id?.startsWith(`${style}-`)) err(pw, `id must start with '${style}-'`)
if (allIds.has(p.id)) err(pw, 'duplicate id'); allIds.add(p.id)
progById[p.id] = p
const n = p.degrees?.length
if (!n) { err(pw, 'degrees missing'); continue }
for (const [field, arr] of [['rn', p.rn], ['qualities', p.qualities], ['bars', p.bars]])
if (!Array.isArray(arr) || arr.length !== n) err(pw, `${field} length ≠ degrees length`)
if (p.degrees.some(d => !Number.isInteger(d) || d < 0 || d > 11)) err(pw, 'degrees must be ints 0-11')
for (const q of p.qualities ?? []) if (!CHORD_TYPES[q]) err(pw, `unknown quality '${q}'`)
if (!MODES.includes(p.mode)) err(pw, `unknown mode '${p.mode}'`)
if (!Array.isArray(p.songs) || !p.songs.length) err(pw, 'songs missing')
if (!p.tip) err(pw, 'tip missing')
// Optional difficulty tag — absent means 'foundation' (consumer default).
if (p.level !== undefined && !LEVELS.includes(p.level))
err(pw, `level, when present, must be one of ${LEVELS.join(' | ')} — got '${p.level}'`)
}
totals.styles++; totals.progressions += progs.length
for (const inst of ['guitar', 'piano', 'bass']) {
const file = join(dir, `${inst}.js`)
if (!existsSync(file)) continue
const pack = await loadModule(file)
const iw = `${w}/${inst}.js`
if (!pack.styleIntro) err(iw, 'styleIntro missing')
if (!Array.isArray(pack.comping) || !pack.comping.length) err(iw, 'comping missing')
if (inst !== 'bass' && (!pack.improv?.scales?.length || !pack.improv?.targetNotes))
err(iw, 'improv.scales / improv.targetNotes required')
const minPlays = inst === 'bass' ? MIN_PLAYS_BASS : MIN_PLAYS
for (const p of progs)
if ((pack.plays?.[p.id]?.length ?? 0) < minPlays)
err(iw, `progression '${p.id}' has < ${minPlays} play(s)`)
for (const [pid, plays] of Object.entries(pack.plays ?? {})) {
const prog = progById[pid]
if (!prog) { err(iw, `plays key '${pid}' is not a progression of this style`); continue }
plays.forEach((play, pi) => {
const lw = `${iw} ${pid} play[${pi}] "${play.label ?? '?'}"`
if (!play.label || !play.level || !play.tips) err(lw, 'label/level/tips required')
totals.plays++
if (inst === 'bass') { for (const m of checkBassPlay(lw, play, prog)) errors.push(m); return }
if (!Array.isArray(play.chords) || play.chords.length !== prog.degrees.length)
return err(lw, `chords length ≠ progression length ${prog.degrees.length}`)
play.chords.forEach((step, ci) => {
const cw = `${lw} chord[${ci}] (${prog.rn[ci]})`
if (inst === 'guitar') checkGuitarShape(cw, step, prog.qualities[ci])
else for (const m of checkPianoRecipe(cw, step, prog.qualities[ci])) errors.push(m)
})
})
}
// Optional structured licks (SCHEMA.md "Licks" / "Piano licks") — a
// top-level `licks` key on the instrument pack. Absent is fine; when
// present it must validate. Routed by instrument: piano licks are
// degree-based (checkPianoLick); guitar licks are tab-based (checkLick).
if (pack.licks !== undefined) {
if (!Array.isArray(pack.licks) || !pack.licks.length) {
err(iw, 'licks, when present, must be a non-empty array')
} else {
const checkInstLick = inst === 'piano' ? checkPianoLick : checkLick
pack.licks.forEach((lick, li) => {
const lkw = `${iw} licks[${li}] "${lick?.id ?? '?'}"`
for (const m of checkInstLick(lkw, lick, style, allIds)) errors.push(m)
})
totals.licks += pack.licks.length
}
}
}
}
// ── Global progression-id uniqueness over the REGISTRY (task C-50) ────────────
// RelatedProgressions' ranking excludes the matched progression by ID ALONE
// (rankRelatedProgressions: `prog.id !== match.id` — no style comparison, task
// L-51), so a progression id repeated anywhere in the registry would silently
// drop an unrelated style's entry from the related list. The per-style loop
// above walks the FILES (kb/*/progressions.js) into `allIds`; this asserts the
// same invariant over kb/index.js — the object the components actually
// consume — so a registry wiring mistake the file walk never sees (a style
// registered against another style's progressions module, a shared/duplicated
// array) cannot reintroduce a duplicate.
if (registry) {
const seenRegIds = new Map() // id → style it first appeared under
for (const style of Object.keys(registry)) {
const progs = registry[style]?.progressions
if (!Array.isArray(progs)) continue
for (const p of progs) {
const rw = `kb/index.js [${style}]`
if (typeof p?.id !== 'string' || !p.id) { err(rw, 'registry progression with missing/non-string id'); continue }
if (seenRegIds.has(p.id))
err(rw, `progression id '${p.id}' already registered under style '${seenRegIds.get(p.id)}' — ids must be globally unique across the registry (RelatedProgressions excludes the matched progression by id alone)`)
else seenRegIds.set(p.id, style)
}
}
}
if (errors.length) {
console.error(`✗ KB validation failed — ${errors.length} error(s):\n`)
for (const e of errors) console.error(' ' + e)
process.exit(1)
}
const lickNote = totals.licks ? `, ${totals.licks} licks` : ''
console.log(`✓ KB valid — ${totals.styles} style(s), ${totals.progressions} progressions, ${totals.plays} plays${lickNote}`)
}
// Run the full validation unless imported as a library (see header comment).
// Safe-by-default: an unset env var always means "run" — the gate can't be
// skipped by a path-comparison quirk.
if (!process.env.KB_VALIDATE_AS_LIB) await main()
+972
View File
@@ -0,0 +1,972 @@
import { useState, useCallback, useRef, useEffect, lazy, Suspense } from 'react'
import AudioCapture from './components/AudioCapture'
import ProgressionBanner from './components/ProgressionBanner'
import Fretboard from './components/Fretboard'
import BassFretboard from './components/BassFretboard'
import Piano from './components/Piano'
import Settings from './components/Settings'
import { NOTES, detectKey, detectTopKeys, matchChordFromChroma, detectRepeatingProgression, getChordTones, getChordCandidates, getNoteHistoryAnalysis } from './lib/theory'
import ChordDetailModal from './components/ChordDetailModal'
import RelatedProgressions from './components/RelatedProgressions'
import TryThis from './components/TryThis'
import LoopStation from './components/LoopStation'
import JamGuide, { KnowledgeDock } from './components/JamGuide'
import { useLoopEngine } from './services/loopEngine'
import kb from './data/kb/index.js'
import { seedableLoop, buildRoulettePool } from './lib/match'
import settingIcon from './assets/setting-icon.png'
// ponytail: collapsible panels most users never open lazy-load so the core
// pitch/chord flow ships in the initial bundle. Suspense fallback null: they
// render behind a toggle button, so there's no visible flash.
const Tuner = lazy(() => import('./components/Tuner'))
const DebugView = lazy(() => import('./components/DebugView'))
const DrumView = lazy(() => import('./components/DrumView'))
const DEFAULTS = {
// Key detection
noteHistorySize: 2000, // ~60s of notes stable across a song section
keyVoteWindow: 30, // rolling window of key votes
keyVoteThreshold: 20, // 67% consensus locks in after a few bars
chordNoteBoost: 3,
// Chord detection
chromaSmooth: 8, // 8 frames 130ms window, checks chord at ~7.5 Hz
chordVoteThreshold: 2, // 2 consecutive matches 260ms works at any BPM
chordMinScore: 0.35, // lenient enough for live guitar signal
// Audio input
minClarity: 0.80,
minVolume: 0.01,
// Selected device (null = system default)
audioDeviceId: null,
}
function loadStored(key, fallback) {
try { const v = localStorage.getItem(key); return v !== null ? JSON.parse(v) : fallback }
catch { return fallback }
}
export default function App() {
// Config
const [config, setConfig] = useState(() => ({ ...DEFAULTS, ...loadStored('wtf_config', {}) }))
const configRef = useRef(config)
useEffect(() => { configRef.current = config; localStorage.setItem('wtf_config', JSON.stringify(config)) }, [config])
const [showSettings, setShowSettings] = useState(false)
function updateConfig(key, val) {
setConfig(prev => ({ ...prev, [key]: val }))
}
// Listening state
const [isListening, setIsListening] = useState(false)
// Instrument view + tuner
const [instrument, setInstrument] = useState('piano') // 'piano' | 'guitar' | 'bass'
const [showTuner, setShowTuner] = useState(false)
const [showDebug, setShowDebug] = useState(false)
const [showDrumView, setShowDrumView] = useState(false)
const [monoColor, setMonoColor] = useState(() => loadStored('wtf_monoColor', false))
// Jam view (task L-50, one-screen.md §1.1) pure UI/layout state
// Layer 1: CSS lock at xl the page root becomes h-screen overflow-hidden and
// everything below the dashboard is unmounted. Layer 2: best-effort browser
// fullscreen (Promise-caught a refusal leaves layer 1 fully working). The
// toggle never starts/stops listening and never touches audio state.
const [jamView, setJamView] = useState(false)
function enterJamView() {
setJamView(true)
document.documentElement.requestFullscreen?.()?.catch(() => {})
}
function exitJamView() {
setJamView(false)
if (document.fullscreenElement) document.exitFullscreen?.()?.catch(() => {})
}
// Escape and the native fullscreen exit (any means) both restore normal flow
// one state, never half-exited. Listeners active only while jamView.
useEffect(() => {
if (!jamView) return
const onKey = (e) => { if (e.key === 'Escape') exitJamView() }
const onFsChange = () => { if (!document.fullscreenElement) setJamView(false) }
window.addEventListener('keydown', onKey)
document.addEventListener('fullscreenchange', onFsChange)
return () => {
window.removeEventListener('keydown', onKey)
document.removeEventListener('fullscreenchange', onFsChange)
}
}, [jamView]) // eslint-disable-line react-hooks/exhaustive-deps
// Jam Guide Fretboard cross-link (D-03)
// When a Roadmap station is tapped, JamGuide reports its {rootPc, quality}
// here and the main Fretboard highlights that chord's guide tones (3rd/7th).
// null = no station focused (Fretboard renders normally). Purely UI state
// NOT read by any audio callback, so it stays out of the ref-sync contract.
const [jamFocusChord, setJamFocusChord] = useState(null) // { rootPc, quality } | null
// Mic permission error
const [micError, setMicError] = useState(null)
// Debug data
const [debugChroma, setDebugChroma] = useState(null)
const [debugCandidates, setDebugCandidates] = useState([])
const [debugNoteAnalysis, setDebugNoteAnalysis] = useState(null)
const [debugWaveform, setDebugWaveform] = useState(null)
// Stable refs for values used inside callbacks
const showDebugRef = useRef(showDebug)
const showDrumViewRef = useRef(showDrumView)
const lockedKeyRef = useRef(null)
const listenStartRef = useRef(null)
useEffect(() => { showDebugRef.current = showDebug }, [showDebug])
useEffect(() => { showDrumViewRef.current = showDrumView }, [showDrumView])
useEffect(() => { localStorage.setItem('wtf_monoColor', JSON.stringify(monoColor)) }, [monoColor])
useEffect(() => { if (isListening) listenStartRef.current = Date.now() }, [isListening])
// BPM estimation from onset timestamps
const [bpm, setBpm] = useState(null)
const onsetTimestampsRef = useRef([])
const bpmSmoothRef = useRef(null)
// Loop station
const {
slots,
masterLen,
setStream: loopSetStream,
handleSlotClick,
commitTrim,
cancelRecord,
retrimSlot,
deleteSlot,
setVolume: loopSetVolume,
addSlot: loopAddSlot,
audioCtxRef: loopAudioCtxRef,
masterStartRef: loopMasterStartRef,
masterLenRef: loopMasterLenRef,
} = useLoopEngine(bpm)
// Key: auto-detected + optional lock
const [keyInfo, setKeyInfo] = useState(null) // auto-detected
const [lockedKey, setLockedKey] = useState(null) // { root, mode } or null
useEffect(() => { lockedKeyRef.current = lockedKey }, [lockedKey])
const [lockRoot, setLockRoot] = useState('A')
const [lockMode, setLockMode] = useState('minor')
const effectiveKey = lockedKey ?? keyInfo
// Chord state
const [chordHistory, setChordHistory] = useState([])
const [detectedProgression, setDetectedProgression] = useState(null)
const [selectedChord, setSelectedChord] = useState(null)
// Jam Roulette (task L-60, jam-roulette.md) pure UI/display state
// seedInfo: provenance of an unconfirmed rolled loop { styleLabel, name, bars }
// (null once live detection confirms or replaces it). Invariant (§3.5):
// seedInfo !== null progressionVoteRef.current?.seeded === true.
const [seedInfo, setSeedInfo] = useState(null)
const [rouletteMenuOpen, setRouletteMenuOpen] = useState(false)
// Top key candidates (shown as quick-lock chips)
const [topKeyCandidates, setTopKeyCandidates] = useState([])
// Internal refs
const noteHistoryRef = useRef([])
const keyVotesRef = useRef([])
const effectiveKeyRef = useRef(null)
const chromaRingRef = useRef(
Array.from({ length: DEFAULTS.chromaSmooth }, () => new Float32Array(12))
)
const chromaIdxRef = useRef(0)
const chordVotesRef = useRef([])
const progressionVoteRef = useRef(null)
const progressionMissRef = useRef(0)
const pendingKeyRef = useRef(null)
// Roulette session memory (UI-state refs, never read by audio code): the last
// 6 rolled progression ids (no-repeat), the last rolled root pc (§2), and the
// last resolved style id (for the "Re-roll {style}" row).
const rouletteMemoryRef = useRef([])
const prevRootPcRef = useRef(null)
const lastRolledStyleRef = useRef(null)
const rouletteRef = useRef(null)
// Keep refs in sync
useEffect(() => { effectiveKeyRef.current = effectiveKey }, [effectiveKey])
// Re-init chroma ring when chromaSmooth changes
useEffect(() => {
chromaRingRef.current = Array.from(
{ length: config.chromaSmooth },
() => new Float32Array(12)
)
chromaIdxRef.current = 0
}, [config.chromaSmooth])
// Progression commit layer (task L-31)
// Runs once per chord commit. progressionVoteRef holds
// { committedKey, candidateKey, candidateCount } null until first evidence.
//
// Thresholds are in chord-commits (one detector run each):
// · COMMIT_VOTES = 2 first commit needs 2 consecutive identical detections
// ( one bar). Post-L-30 detection is stable on clean loops so this lands
// immediately; a noisy 2-rep history flaps through data-faithful sub-cycles
// that never repeat twice in a row, so noise can't commit early.
// · REPLACE_VOTES = 3 replacing a committed loop needs 3 consecutive
// detections of the SAME new loop: one transient detection (or an
// alternating flap) must never displace the loop the musician is still in;
// a genuine section change is detected consistently and just lands one
// commit later than a first commit would.
// · NULL_CLEAR = 6 the detector only returns null once the loop has
// aged out of its 32-commit window (it needs 2 exact in-window
// occurrences): traced, that is ~28 commits of foreign material after
// the loop last played. Fills, turnarounds and window-boundary resumes
// yield non-null sub-cycle detections rather than nulls (traced), so
// they can NEVER clear a committed loop a new established loop
// replaces via REPLACE_VOTES instead. A null run therefore means the
// jam truly left loop-land ~30 commits ago; 6 more ( two bars of
// structureless playing) confirms it wasn't a flicker before the
// display goes dark. (The old value 4 was sized as if nulls happened
// during fills post-L-30 they don't.)
const COMMIT_VOTES = 2
const REPLACE_VOTES = 3
const NULL_CLEAR = 6
useEffect(() => {
const detected = detectRepeatingProgression(chordHistory)
const vote = progressionVoteRef.current
if (!detected) {
progressionMissRef.current++
// L-60 flag 1 (§3.4): a SEEDED card is an instruction, not an observation
// ramp-up nulls (every seed's own effect run is miss 1, and no detection can
// land before commit 6) must NOT wipe it. It stays until confirmed, replaced
// by a consistently-detected different loop, re-rolled, or New Song.
if (progressionMissRef.current >= NULL_CLEAR && !vote?.seeded) {
setDetectedProgression(null)
progressionVoteRef.current = null
}
return
}
progressionMissRef.current = 0 // any detected structure keeps the committed loop alive
const key = detected.join(',')
if (vote && vote.committedKey === key) {
// Agreement with the committed loop refresh it, drop any pending rival.
setDetectedProgression(detected)
vote.candidateKey = null
vote.candidateCount = 0
// L-60 (§3.4): the seed is now a normal committed loop the first agreeing
// live detection confirms it; drop the provenance flag + chip.
if (vote.seeded) { vote.seeded = false; setSeedInfo(null) }
return
}
const committedKey = vote ? vote.committedKey : null
if (vote && vote.candidateKey === key) {
vote.candidateCount++
} else {
// L-60 flag 3 (§3.4): preserve `seeded` across candidate rebuilds a
// transient ghost sub-cycle must not strip the flag and resurrect flag 1's
// ramp-up kill through the side door.
progressionVoteRef.current = { committedKey, candidateKey: key, candidateCount: 1, seeded: vote?.seeded ?? false }
}
if (progressionVoteRef.current.candidateCount >= (committedKey ? REPLACE_VOTES : COMMIT_VOTES)) {
setDetectedProgression(detected)
progressionVoteRef.current = { committedKey: key, candidateKey: null, candidateCount: 0 }
// L-60 (§3.4/§3.5): a genuinely different loop replaced the seed the new
// vote is detection-owned; end the seed provenance.
setSeedInfo(null)
}
}, [chordHistory])
// New song full reset
function newSong() {
const cfg = configRef.current
noteHistoryRef.current = []
keyVotesRef.current = []
chordVotesRef.current = []
progressionVoteRef.current = null
progressionMissRef.current = 0
pendingKeyRef.current = null
chromaIdxRef.current = 0
chromaRingRef.current = Array.from({ length: cfg.chromaSmooth }, () => new Float32Array(12))
onsetTimestampsRef.current = []
bpmSmoothRef.current = null
listenStartRef.current = Date.now()
setKeyInfo(null)
setLockedKey(null)
effectiveKeyRef.current = null
setChordHistory([])
setDetectedProgression(null)
setSeedInfo(null) // L-60 (§3.6): the seed clears with the full reset
setTopKeyCandidates([])
setBpm(null)
setMicError(null)
setDebugChroma(null)
setDebugCandidates([])
setDebugNoteAnalysis(null)
setDebugWaveform(null)
}
// Key lock handlers
function applyLock() {
const info = { root: lockRoot, mode: lockMode, confidence: 1 }
setLockedKey(info)
effectiveKeyRef.current = info
chordVotesRef.current = []
}
function quickLock({ root, mode, confidence }) {
const info = { root, mode, confidence }
setLockedKey(info)
effectiveKeyRef.current = info
chordVotesRef.current = []
}
function removeLock() {
setLockedKey(null)
effectiveKeyRef.current = keyInfo
}
// Jam Roulette (task L-60, jam-roulette.md §2/§3.1)
// Rolls a random key + interesting KB progression and seeds the EXACT state
// live detection writes (lockedKey + detectedProgression + a committed-shape
// progressionVoteRef), so the whole dashboard populates as if detected. All
// randomness is here (plain Math.random, no audio contact); inputs = the KB
// registry only. `styleId === 'surprise'` picks uniformly over the 10 styles.
function rollJam(styleId) {
const pool = buildRoulettePool(kb) // lazy memo round-trip passers, len 28
const sid = styleId === 'surprise'
? Object.keys(kb)[Math.floor(Math.random() * Object.keys(kb).length)]
: styleId
const members = pool.byStyle.get(sid) ?? []
if (!members.length) return
// No-repeat memory (§2.2): exclude the last 6 rolled ids; if that empties the
// pool (small styles), fall back to excluding only the immediately previous.
const mem = rouletteMemoryRef.current
let candidates = members.filter(m => !mem.includes(m.id))
if (!candidates.length) {
const prev = mem[mem.length - 1]
candidates = members.filter(m => m.id !== prev)
if (!candidates.length) candidates = members
}
// Weighted draw: weight = levelW × lenW (§2.2). Intermediate leans in (×2),
// the collapsed "4-bar-ish" sweet spot 37 leans in (×2).
const weightOf = (m) => {
const levelW = m.progression.level === 'intermediate' ? 2 : 1
const lenW = (m.collapsedLen >= 3 && m.collapsedLen <= 7) ? 2 : 1
return levelW * lenW
}
const totalW = candidates.reduce((s, m) => s + weightOf(m), 0)
let r = Math.random() * totalW
let picked = candidates[candidates.length - 1]
for (const m of candidates) { r -= weightOf(m); if (r <= 0) { picked = m; break } }
const prog = picked.progression
// Root: uniform over 12 pcs, SHARP spelling (§2.1 only sharp names
// string-match live detection); don't repeat the previous roll's root.
let rolledPc = Math.floor(Math.random() * 12)
if (prevRootPcRef.current != null && rolledPc === prevRootPcRef.current) {
rolledPc = Math.floor(Math.random() * 12) // re-draw once
}
const loop = seedableLoop(prog, rolledPc)
if (!loop) return // pool guarantees this, but stay defensive
prevRootPcRef.current = rolledPc
// The seed writes (§3.1) clean slate, then key + loop + committed vote
newSong() // §3.6: roulette = New Song + seed (a stale window poisons handoff)
const info = { root: NOTES[rolledPc], mode: prog.mode, confidence: 1 }
setLockedKey(info)
effectiveKeyRef.current = info // the quickLock precedent detection uses it NOW
chordVotesRef.current = []
setDetectedProgression(loop)
progressionVoteRef.current = {
committedKey: loop.join(','), // the committed shape, L-31's own key
candidateKey: null,
candidateCount: 0,
seeded: true, // the one flag L-60 adds (§3.4)
}
progressionMissRef.current = 0
setSeedInfo({ styleLabel: kb[sid]?.meta?.label ?? sid, name: prog.name, bars: prog.bars })
// Session bookkeeping (§2.2) survives New Song deliberately.
lastRolledStyleRef.current = sid
mem.push(picked.id)
while (mem.length > 6) mem.shift()
setRouletteMenuOpen(false)
}
// Escape / click-outside closes the roulette menu; focus returns to the button.
useEffect(() => {
if (!rouletteMenuOpen) return
const onKey = (e) => {
if (e.key === 'Escape') {
setRouletteMenuOpen(false)
rouletteRef.current?.querySelector('button')?.focus()
}
}
const onDown = (e) => { if (!rouletteRef.current?.contains(e.target)) setRouletteMenuOpen(false) }
document.addEventListener('keydown', onKey)
document.addEventListener('mousedown', onDown)
return () => {
document.removeEventListener('keydown', onKey)
document.removeEventListener('mousedown', onDown)
}
}, [rouletteMenuOpen])
// Waveform handler: feeds oscilloscope / drum view
const handleWaveform = useCallback((data) => {
if (showDebugRef.current || showDrumViewRef.current) {
setDebugWaveform({ ...data, onsets: [...onsetTimestampsRef.current] })
}
}, [])
// Note handler: drives key detection (pitch-based)
const handleNote = useCallback(({ pitchClass }) => {
const cfg = configRef.current
const history = noteHistoryRef.current
history.push(pitchClass)
if (history.length > cfg.noteHistorySize) history.shift()
if (history.length < 10) return
if (history.length % 5 !== 0) return
const result = detectKey(history)
setTopKeyCandidates(detectTopKeys(history))
if (showDebugRef.current) {
const analysis = getNoteHistoryAnalysis(history)
analysis.sessionSecs = listenStartRef.current ? Math.floor((Date.now() - listenStartRef.current) / 1000) : 0
setDebugNoteAnalysis(analysis)
}
if (result.confidence < 0.5) return
const votes = keyVotesRef.current
votes.push(`${result.root}_${result.mode}`)
if (votes.length > cfg.keyVoteWindow) votes.shift()
const counts = {}
for (const v of votes) counts[v] = (counts[v] || 0) + 1
const [winner, count] = Object.entries(counts).sort((a, b) => b[1] - a[1])[0]
if (count >= cfg.keyVoteThreshold) {
const [root, mode] = winner.split('_')
const candidateKey = `${root}_${mode}`
setKeyInfo(prev => {
const currentKey = prev ? `${prev.root}_${prev.mode}` : null
if (currentKey === candidateKey) {
pendingKeyRef.current = null
return { root, mode, confidence: result.confidence }
}
if (pendingKeyRef.current === candidateKey) {
pendingKeyRef.current = null
if (!lockedKeyRef.current) chordVotesRef.current = []
return { root, mode, confidence: result.confidence }
}
pendingKeyRef.current = candidateKey
return prev
})
}
}, [])
// Chroma handler: drives chord detection
const handleChroma = useCallback((chroma, bassPC) => {
const cfg = configRef.current
const ring = chromaRingRef.current
ring[chromaIdxRef.current % cfg.chromaSmooth] = chroma
chromaIdxRef.current++
if (chromaIdxRef.current % cfg.chromaSmooth !== 0) return
const key = effectiveKeyRef.current
if (!key) return
const avg = new Float32Array(12)
for (const frame of ring) for (let i = 0; i < 12; i++) avg[i] += frame[i]
for (let i = 0; i < 12; i++) avg[i] /= cfg.chromaSmooth
if (showDebugRef.current) {
setDebugChroma([...avg])
setDebugCandidates(getChordCandidates(avg, key, bassPC, 5))
}
// Stability gate if chroma is still changing across frames, we're mid-transition.
// Compute per-bin variance across the ring; bail if any bin is fluctuating heavily.
let maxVar = 0
for (let i = 0; i < 12; i++) {
let v = 0
for (const frame of ring) { const d = frame[i] - avg[i]; v += d * d }
if (v / cfg.chromaSmooth > maxVar) maxVar = v / cfg.chromaSmooth
}
if (maxVar > 0.05) return
const chord = matchChordFromChroma(avg, key, bassPC, false, cfg.chordMinScore)
if (!chord) {
chordVotesRef.current = []
return
}
const votes = chordVotesRef.current
votes.push(chord)
if (votes.length > cfg.chordVoteThreshold) votes.shift()
if (votes.length >= cfg.chordVoteThreshold && votes.every(v => v === votes[0])) {
const winner = votes[0]
setChordHistory(prev => {
if (prev[prev.length - 1] === winner) return prev
return [...prev.slice(-48), winner]
})
// Inject chord tones into note history to anchor key detection
const chordPCs = getChordTones(winner)
.map(n => NOTES.indexOf(n))
.filter(i => i >= 0)
const history = noteHistoryRef.current
for (let j = 0; j < cfg.chordNoteBoost; j++) {
for (const pc of chordPCs) history.push(pc)
}
while (history.length > cfg.noteHistorySize) history.shift()
}
}, [])
// Onset handler: drives BPM estimation via tempo histogram
// Pairwise inter-onset intervals are folded into 55-220 BPM and vote in a
// histogram. Works with drums, guitar, piano, or mixed whatever fires most
// consistently wins. Only updates when there's a clear peak (20% of votes).
const handleOnset = useCallback(() => {
const ts = onsetTimestampsRef.current
ts.push(performance.now())
if (ts.length > 64) ts.shift()
if (ts.length < 4) return
const recent = ts.slice(-24)
const bins = new Float32Array(221) // index = BPM (55220)
for (let i = 0; i < recent.length - 1; i++) {
for (let j = i + 1; j < recent.length && j < i + 8; j++) {
const ms = recent[j] - recent[i]
if (ms < 140 || ms > 6000) continue
// Fold interval into 55-220 BPM range (handles subdivisions & half-time)
let beatMs = ms
while (beatMs > 1091) beatMs /= 2
while (beatMs < 273) beatMs *= 2
if (beatMs < 273 || beatMs > 1091) continue
const bpm = Math.round(60000 / beatMs)
if (bpm >= 55 && bpm <= 220) bins[bpm] += 1 / (j - i) // weight closer pairs more
}
}
// Find peak with ±1 BPM smoothing
let best = 0, bestBpm = 0
for (let b = 56; b <= 219; b++) {
const s = bins[b - 1] + bins[b] + bins[b + 1]
if (s > best) { best = s; bestBpm = b }
}
const total = bins.reduce((a, v) => a + v, 0)
if (total < 1 || best / total < 0.2) return // no clear consensus yet
const prev = bpmSmoothRef.current
bpmSmoothRef.current = prev === null ? bestBpm : 0.25 * bestBpm + 0.75 * prev
setBpm(Math.round(bpmSmoothRef.current))
}, [])
const currentChord = chordHistory[chordHistory.length - 1]
if (showSettings) {
return (
<Settings
config={config}
onChange={updateConfig}
onClose={() => setShowSettings(false)}
onReset={() => { setConfig(DEFAULTS); setMonoColor(false) }}
monoColor={monoColor}
onMonoColorChange={setMonoColor}
/>
)
}
return (
<div className={`min-h-screen bg-surface text-white p-3${jamView ? ' xl:h-screen xl:overflow-hidden xl:flex xl:flex-col' : ''}`}>
{/* ── Header ── */}
<header className="mb-2 flex items-center justify-between gap-2 flex-wrap">
<div>
<h1 className="text-xl font-bold text-accent">
WhatTheFlat <span className="text-gray-600">&#9837;?</span> <span className="text-amber-400">- JamBuddy</span>
</h1>
<p className="text-xs text-gray-600 hidden sm:block">Real-time key detection for live jams</p>
</div>
<div className="flex gap-2 items-center">
<button
onClick={() => setShowSettings(true)}
className="p-2 rounded-full border border-border hover:border-gray-400 transition-all"
title="Settings"
>
<img src={settingIcon} alt="Settings" className="w-5 h-5" style={{ filter: 'invert(1) opacity(0.75)' }} />
</button>
<button
onClick={newSong}
className="group px-5 py-2 rounded-full text-sm font-semibold border border-border text-gray-400 hover:text-gray-200 hover:border-gray-400 transition-all"
>
<span className="group-hover:hidden">New Song</span>
<span className="hidden group-hover:inline">Clear History</span>
</button>
<button
onClick={() => { setMicError(null); setIsListening(l => !l) }}
className={`px-5 py-2 rounded-full font-semibold text-sm transition-all ${
isListening
? 'bg-red-600 hover:bg-red-700 text-white'
: 'bg-accent hover:bg-purple-600 text-white'
}`}
>
{isListening ? 'Stop' : 'Start Listening'}
</button>
</div>
</header>
{/* ── Controls bar ── */}
<div className="mb-2 flex flex-wrap gap-2 items-center p-2 bg-panel border border-border rounded-xl">
{/* Instrument select */}
<div className="relative">
<select
value={instrument}
onChange={e => setInstrument(e.target.value)}
className="appearance-none bg-surface border border-border hover:border-gray-500 focus:border-accent focus:outline-none rounded-lg pl-3 pr-7 py-1 text-sm text-gray-200 cursor-pointer transition-colors"
>
<option value="piano">Piano</option>
<option value="guitar">Guitar</option>
<option value="bass">Bass</option>
</select>
<span className="pointer-events-none absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 text-xs"></span>
</div>
{/* BPM badge */}
{bpm && (
<span className="px-3 py-1 bg-accent/10 border border-accent/30 rounded-lg text-sm text-accent font-mono tabular-nums">
<span className="inline-block w-[3ch] text-right">{Math.round(bpm)}</span> <span className="text-accent/50 text-xs">BPM</span>
</span>
)}
<div className="w-px h-5 bg-border shrink-0" />
{lockedKey ? (
<div className="flex items-center gap-2 px-3 py-1 bg-accent/20 border border-accent rounded-full">
<span className="text-accent text-sm font-semibold shrink-0">🔒 {lockedKey.root}</span>
<div className="relative">
<select
value={lockedKey.mode}
onChange={e => {
const info = { ...lockedKey, mode: e.target.value }
setLockedKey(info)
effectiveKeyRef.current = info
chordVotesRef.current = []
}}
className="appearance-none bg-transparent text-accent text-sm font-semibold border-none outline-none cursor-pointer pr-4"
>
<option value="major">Major</option>
<option value="minor">Minor</option>
<option value="dorian">Dorian</option>
<option value="mixolydian">Mixolydian</option>
<option value="phrygian">Phrygian</option>
<option value="lydian">Lydian</option>
</select>
<span className="pointer-events-none absolute right-0 top-1/2 -translate-y-1/2 text-accent/60 text-xs"></span>
</div>
<button onClick={removeLock} className="text-xs text-accent/50 hover:text-accent transition-colors">
unlock
</button>
</div>
) : (
<div className="flex flex-wrap gap-2 items-center">
{topKeyCandidates.map((k, i) => (
<button
key={i}
onClick={() => quickLock(k)}
className={`px-3 py-1 rounded-full text-sm font-semibold border transition-all ${
i === 0
? 'border-accent text-accent hover:bg-accent/10'
: 'border-border text-gray-400 hover:border-gray-500 hover:text-gray-200'
}`}
>
{k.root} {k.mode === 'major' ? 'maj' : 'min'} · {Math.round(k.confidence * 100)}%
</button>
))}
{topKeyCandidates.length > 0 && <span className="text-gray-600 text-xs">or</span>}
<div className="relative">
<select
value={lockRoot}
onChange={e => setLockRoot(e.target.value)}
className="appearance-none bg-surface border border-border hover:border-gray-500 focus:border-accent focus:outline-none rounded-lg pl-3 pr-7 py-1 text-sm text-gray-200 cursor-pointer transition-colors"
>
{NOTES.map(n => <option key={n}>{n}</option>)}
</select>
<span className="pointer-events-none absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 text-xs"></span>
</div>
<div className="relative">
<select
value={lockMode}
onChange={e => setLockMode(e.target.value)}
className="appearance-none bg-surface border border-border hover:border-gray-500 focus:border-accent focus:outline-none rounded-lg pl-3 pr-7 py-1 text-sm text-gray-200 cursor-pointer transition-colors"
>
<option value="major">Major</option>
<option value="minor">Minor</option>
<option value="dorian">Dorian</option>
<option value="mixolydian">Mixolydian</option>
<option value="phrygian">Phrygian</option>
<option value="lydian">Lydian</option>
</select>
<span className="pointer-events-none absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 text-xs"></span>
</div>
<button
onClick={applyLock}
className="px-3 py-1 bg-accent/10 hover:bg-accent/20 border border-accent/40 hover:border-accent text-accent text-sm rounded-lg transition-all"
>
Lock key
</button>
</div>
)}
{/* ── Jam roulette (L-60, jam-roulette.md §1.1/§1.2) ── */}
<div className="relative ml-auto" ref={rouletteRef}>
<button
type="button"
onClick={() => setRouletteMenuOpen(o => !o)}
aria-haspopup="menu"
aria-expanded={rouletteMenuOpen}
aria-pressed={seedInfo ? true : undefined}
title="Jam roulette — roll a random key + progression to jam on"
className={`min-h-[32px] px-3 py-1 rounded-lg border text-sm transition-colors outline-none focus-visible:ring-2 focus-visible:ring-accent ${
seedInfo
? 'border-accent/40 text-accent bg-accent/10 font-semibold'
: 'border-border text-gray-200 hover:border-gray-500'
}`}
>
🎲 Jam roulette
</button>
{rouletteMenuOpen && (
<div
role="menu"
aria-label="Pick a genre to roll"
className="absolute right-0 mt-1 w-56 bg-panel border border-border rounded-xl shadow-lg p-1 z-20"
>
{seedInfo && (
<button
type="button"
role="menuitem"
onClick={() => rollJam(lastRolledStyleRef.current)}
className="w-full text-left px-3 py-1.5 rounded-lg text-sm text-gray-200 hover:bg-accent/10 border-b border-border outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
Re-roll {seedInfo.styleLabel}
</button>
)}
<button
type="button"
role="menuitem"
onClick={() => rollJam('surprise')}
className="w-full text-left px-3 py-1.5 rounded-lg text-sm text-gray-200 hover:bg-accent/10 border-b border-border outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
Surprise me
</button>
{Object.entries(kb).map(([id, s]) => (
<button
key={id}
type="button"
role="menuitem"
onClick={() => rollJam(id)}
className="w-full text-left px-3 py-1.5 rounded-lg text-sm text-gray-200 hover:bg-accent/10 outline-none focus-visible:ring-2 focus-visible:ring-accent"
>
{s.meta?.label ?? id}
</button>
))}
</div>
)}
</div>
{/* ── Jam view toggle (L-50, one-screen.md §1.1) — layout-only ── */}
<button
type="button"
onClick={jamView ? exitJamView : enterJamView}
aria-pressed={jamView}
title={jamView ? 'Exit jam view' : 'Jam view — the one-screen dashboard, fullscreen'}
className={`ml-auto min-h-[32px] px-3 py-1 rounded-lg text-sm border transition-all outline-none focus-visible:ring-2 focus-visible:ring-accent ${
jamView
? 'bg-accent/20 border-accent text-accent font-semibold'
: 'border-border text-gray-400 hover:border-gray-500 hover:text-gray-200'
}`}
>
{jamView ? '✕ Exit' : '⛶ Jam view'}
</button>
</div>
<AudioCapture
onNote={handleNote}
onChroma={handleChroma}
onOnset={handleOnset}
onWaveform={handleWaveform}
isListening={isListening}
minClarity={config.minClarity}
minVolume={config.minVolume}
audioDeviceId={config.audioDeviceId}
onPermissionError={() => {
setMicError(true)
setIsListening(false)
}}
onStreamReady={loopSetStream}
/>
{micError && (
<div className="mb-2 px-4 py-3 rounded-xl border border-red-800 bg-red-900/20 text-sm text-red-400 flex items-center justify-between">
<span>Microphone permission denied. Please allow microphone access in your browser or OS settings and try again.</span>
<button onClick={() => setMicError(null)} className="ml-4 text-red-600 hover:text-red-400 text-lg leading-none">×</button>
</div>
)}
{/* ── Chord detail modal ── */}
<ChordDetailModal chord={selectedChord} onClose={() => setSelectedChord(null)} onChordClick={setSelectedChord} keyInfo={effectiveKey} chordHistory={chordHistory} />
{/* ── Progression banner ── */}
<ProgressionBanner
chordHistory={chordHistory}
keyInfo={effectiveKey}
detectedProgression={detectedProgression}
seedInfo={seedInfo}
onChordClick={setSelectedChord}
/>
{/* ── The jam dashboard grid (task L-50, one-screen.md §1/§6): JamGuide
owns the two-column layout LEFT: compact instrument view (chosen
here, passed as the mainView slot) + licks strip + the related-
progressions slot (RelatedProgressions, task L-51); RIGHT: the
suggested-voicings rail. ProgressionSuggestions is unmounted (file
kept) its job split into the rail + RelatedProgressions per the
user directive. Follows the one global instrument selector. */}
<JamGuide
detectedProgression={detectedProgression}
keyInfo={effectiveKey}
chordHistory={chordHistory}
currentChord={currentChord}
onFocusChord={setJamFocusChord}
instrument={instrument}
mainView={
<>
{instrument === 'guitar' && <Fretboard keyInfo={effectiveKey} currentChord={currentChord} pentatonicOnly={false} monoColor={monoColor} jamFocusChord={jamFocusChord} compact />}
{instrument === 'bass' && <BassFretboard keyInfo={effectiveKey} currentChord={currentChord} monoColor={monoColor} compact />}
{instrument === 'piano' && <Piano keyInfo={effectiveKey} currentChord={currentChord} monoColor={monoColor} compact />}
</>
}
relatedSlot={
<div className="flex flex-col gap-3">
<TryThis
loop={detectedProgression}
keyInfo={effectiveKey}
currentChord={currentChord}
onChordClick={setSelectedChord}
instrument={instrument}
/>
<RelatedProgressions
loop={detectedProgression}
keyInfo={effectiveKey}
onChordClick={setSelectedChord}
/>
</div>
}
fill={jamView}
/>
{/* ── Below the dashboard — the learning / behind-the-scenes area (page
scroll in normal mode; UNMOUNTED in jam view, one-screen.md §1.1/§3:
conditional mount, not `hidden`, so collapsed chrome can't leak
height). */}
{!jamView && (
<>
{/* ── Loop station ── */}
<LoopStation
slots={slots}
bpm={bpm}
masterLen={masterLen}
audioCtxRef={loopAudioCtxRef}
masterStartRef={loopMasterStartRef}
masterLenRef={loopMasterLenRef}
onSlotClick={handleSlotClick}
onCommitTrim={commitTrim}
onCancelRecord={cancelRecord}
onRetrim={retrimSlot}
onDelete={deleteSlot}
onVolumeChange={loopSetVolume}
onAddSlot={loopAddSlot}
/>
{/* ── Behind the scenes — collapsible ── */}
<div className="mb-3 bg-panel border border-border rounded-xl overflow-hidden">
<button
onClick={() => setShowDebug(v => !v)}
className="w-full flex items-center justify-between px-4 py-2 text-sm text-gray-400 hover:text-gray-200 transition-all"
>
<span>BEHIND THE SCENES</span>
<span>{showDebug ? '▲' : '▼'}</span>
</button>
{showDebug && (
<div className="border-t border-border p-4">
<Suspense fallback={null}>
<DebugView
chroma={debugChroma}
chordCandidates={debugCandidates}
noteAnalysis={debugNoteAnalysis}
waveform={debugWaveform}
keyInfo={effectiveKey}
currentChord={currentChord}
instrument={instrument}
monoColor={monoColor}
/>
</Suspense>
</div>
)}
</div>
{/* ── Rhythm / drum analyser — collapsible ── */}
<div className="mb-3 bg-panel border border-border rounded-xl overflow-hidden">
<button
onClick={() => setShowDrumView(v => !v)}
className="w-full flex items-center justify-between px-4 py-2 text-sm text-gray-400 hover:text-gray-200 transition-all"
>
<span>RHYTHM ANALYSER</span>
<span>{showDrumView ? '▲' : '▼'}</span>
</button>
{showDrumView && (
<div className="border-t border-border p-4">
<Suspense fallback={null}>
<DrumView waveform={debugWaveform} bpm={bpm} />
</Suspense>
</div>
)}
</div>
{/* ── Tuner — collapsible ── */}
<div className="bg-panel border border-border rounded-xl overflow-hidden">
<button
onClick={() => setShowTuner(v => !v)}
className="w-full flex items-center justify-between px-4 py-2 text-sm text-gray-400 hover:text-gray-200 transition-all"
>
<span>TUNER</span>
<span>{showTuner ? '▲' : '▼'}</span>
</button>
{showTuner && <div className="border-t border-border"><Suspense fallback={null}><Tuner /></Suspense></div>}
</div>
{/* ── Knowledge Center — bottom browse & study dock (L-40, D-40 §5) ── */}
<KnowledgeDock
keyInfo={effectiveKey}
chordHistory={chordHistory}
currentChord={currentChord}
onChordClick={setSelectedChord}
instrument={instrument}
/>
</>
)}
</div>
)
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 KiB

+277
View File
@@ -0,0 +1,277 @@
import { useEffect, useRef, useCallback } from 'react'
import { PitchDetector } from 'pitchy'
import { NOTES } from '../lib/theory'
// Why two analysers?
//
// The Web Audio FFT has linearly-spaced bins: bin width = sampleRate / fftSize.
//
// fftSize 4096 ~10.8 Hz/bin (default we were using)
// fftSize 16384 ~2.7 Hz/bin (multi-rate chord analyser)
//
// On the low guitar strings the gap between adjacent semitones is only ~5-6 Hz.
// At 10.8 Hz/bin we literally cannot separate A2 (110 Hz) from A#2 (116 Hz).
// That is the single biggest source of wrong chord notes on the low strings.
//
// Solution: run a second, larger analyser just for chord/chroma detection.
// The pitch analyser stays small (4096) so pitchy has a 90ms window fast
// enough for responsive pitch detection. The chord analyser uses 16384 (~370ms
// window) slower to respond but with 2.7 Hz bins that can cleanly separate
// every semitone across the guitar's entire range.
//
// This is an approximation of the Constant-Q Transform (CQT) your friend
// mentioned: CQT achieves log-spaced bins mathematically; we approximate it
// by simply using a much larger FFT window.
//
const PITCH_FFT = 4096 // ~90ms window good temporal resolution for pitch
const CHORD_FFT = 16384 // ~370ms window 2.7 Hz/bin, separates low semitones
const NOISE_FLOOR = -65 // dB
// Harmonic summation chroma
// Each FFT bin votes back toward lower fundamentals that could have generated
// it as an overtone. This undoes the harmonic contamination that makes minor
// chords look like major ones (the 5th harmonic of the root lands on the major
// 3rd, which is NOT in the minor chord).
const HARMONIC_WEIGHTS = [1.0, 0.5, 0.33, 0.25, 0.2] // h = 15
function computeChroma(freqData, sampleRate, fftSize) {
const chroma = new Float32Array(12)
const binHz = sampleRate / fftSize
const N = freqData.length
for (let bin = 2; bin < N; bin++) {
const freq = bin * binHz
if (freq < 80 || freq > 4000) continue
const db = freqData[bin]
if (db < NOISE_FLOOR) continue
const amp = Math.sqrt(Math.pow(10, db / 10)) // amplitude, not power
for (let h = 1; h <= HARMONIC_WEIGHTS.length; h++) {
const fundamental = freq / h
if (fundamental < 40 || fundamental > 2000) continue
const midi = 12 * Math.log2(fundamental / 440) + 69
const pc = ((Math.round(midi) % 12) + 12) % 12
chroma[pc] += amp * HARMONIC_WEIGHTS[h - 1]
}
}
for (let i = 0; i < 12; i++) chroma[i] = Math.log1p(chroma[i])
const max = Math.max(...chroma)
if (max > 0) for (let i = 0; i < 12; i++) chroma[i] /= max
return chroma
}
function detectBassPC(freqData, sampleRate, fftSize) {
const binHz = sampleRate / fftSize
let maxPower = 0, bestMidi = -1
for (let bin = 2; bin < freqData.length; bin++) {
const freq = bin * binHz
if (freq < 40 || freq > 350) continue
const db = freqData[bin]
if (db < NOISE_FLOOR) continue
const power = Math.pow(10, db / 10)
if (power > maxPower) {
maxPower = power
bestMidi = Math.round(12 * Math.log2(freq / 440) + 69)
}
}
if (bestMidi < 0) return null
return ((bestMidi % 12) + 12) % 12
}
export default function AudioCapture({ onNote, onChroma, onOnset, onWaveform, isListening, minClarity = 0.80, minVolume = 0.01, onPermissionError, audioDeviceId = null, onStreamReady = null }) {
const audioCtxRef = useRef(null)
const timeBufRef = useRef(null)
const freqBufRef = useRef(null)
const detectorRef = useRef(null)
const rafRef = useRef(null)
const streamRef = useRef(null)
const activeRef = useRef(false) // guards against stale tick callbacks
// All callbacks and thresholds read via refs so start/stop never need to recreate
const onNoteRef = useRef(onNote)
const onChromaRef = useRef(onChroma)
const onOnsetRef = useRef(onOnset)
const onWaveformRef = useRef(onWaveform)
const onPermissionErrorRef = useRef(onPermissionError)
const onStreamReadyRef = useRef(onStreamReady)
const minClarityRef = useRef(minClarity)
const minVolumeRef = useRef(minVolume)
const smoothRmsRef = useRef(0)
const lastOnsetRef = useRef(0)
const specPeakRef = useRef(null) // peak-hold spectrum for display lingering
useEffect(() => { onNoteRef.current = onNote }, [onNote])
useEffect(() => { onChromaRef.current = onChroma }, [onChroma])
useEffect(() => { onOnsetRef.current = onOnset }, [onOnset])
useEffect(() => { onWaveformRef.current = onWaveform }, [onWaveform])
useEffect(() => { onPermissionErrorRef.current = onPermissionError }, [onPermissionError])
useEffect(() => { onStreamReadyRef.current = onStreamReady }, [onStreamReady])
useEffect(() => { minClarityRef.current = minClarity }, [minClarity])
useEffect(() => { minVolumeRef.current = minVolume }, [minVolume])
const stop = useCallback(() => {
activeRef.current = false
specPeakRef.current = null
if (rafRef.current) { cancelAnimationFrame(rafRef.current); rafRef.current = null }
if (streamRef.current) { streamRef.current.getTracks().forEach(t => t.stop()); streamRef.current = null }
if (audioCtxRef.current) { audioCtxRef.current.close(); audioCtxRef.current = null }
}, [])
const start = useCallback(async () => {
stop()
let stream
try {
// Helpful debug: list available media devices before requesting permission
try {
if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) {
const devices = await navigator.mediaDevices.enumerateDevices()
const audioIns = devices.filter(d => d.kind === 'audioinput')
console.log('Audio inputs available:', audioIns)
}
} catch (e) {
console.warn('enumerateDevices failed', e)
}
const constraints = audioDeviceId
? { audio: { deviceId: { exact: audioDeviceId } } }
: { audio: true }
console.log('Requesting getUserMedia with constraints:', constraints)
stream = await navigator.mediaDevices.getUserMedia(constraints)
} catch (err) {
// If permission denied or other error, surface extra diagnostics when possible
console.warn('getUserMedia failed', err)
try {
if (navigator.permissions && navigator.permissions.query) {
const p = await navigator.permissions.query({ name: 'microphone' })
console.log('microphone permission state:', p.state)
}
} catch (e) {
// ignore; not all environments support Permissions API for microphone
}
onPermissionErrorRef.current?.(err)
return
}
streamRef.current = stream
activeRef.current = true
onStreamReadyRef.current?.(stream)
smoothRmsRef.current = 0
lastOnsetRef.current = 0
const ctx = new AudioContext()
audioCtxRef.current = ctx
const source = ctx.createMediaStreamSource(stream)
// Debug: log the acquired audio tracks and labels/deviceIds
try {
const tracks = stream.getAudioTracks()
console.log('Acquired audio tracks:', tracks.map(t => ({ label: t.label, id: t.id, enabled: t.enabled, muted: t.muted })))
} catch (e) {
console.warn('Could not inspect stream tracks', e)
}
// Small analyser pitch detection needs fast time-domain data
const pa = ctx.createAnalyser()
pa.fftSize = PITCH_FFT
pa.smoothingTimeConstant = 0.0
source.connect(pa)
timeBufRef.current = new Float32Array(pa.fftSize)
detectorRef.current = PitchDetector.forFloat32Array(pa.fftSize)
// Large analyser chord detection needs fine frequency resolution
const ca = ctx.createAnalyser()
ca.fftSize = CHORD_FFT
ca.smoothingTimeConstant = 0.5 // reduced from 0.65 clears faster between chords
source.connect(ca)
freqBufRef.current = new Float32Array(ca.frequencyBinCount)
function tick() {
if (!activeRef.current) return // stop() was called bail immediately
const timeBuf = timeBufRef.current
pa.getFloatTimeDomainData(timeBuf)
const rms = Math.sqrt(timeBuf.reduce((s, v) => s + v * v, 0) / timeBuf.length)
// Onset detection RMS spike significantly above smoothed baseline
const sr = smoothRmsRef.current
smoothRmsRef.current = 0.85 * sr + 0.15 * rms
const nowMs = performance.now()
if (rms > sr * 2.2 && rms > minVolumeRef.current * 1.5 && nowMs - lastOnsetRef.current > 120) {
lastOnsetRef.current = nowMs
onOnsetRef.current?.()
}
// Always fire waveform callback downsample 4096 512 points + log-binned spectrum
if (onWaveformRef.current) {
const stride = 8 // 4096 / 8 = 512 points
const wave = new Float32Array(PITCH_FFT / stride)
for (let i = 0; i < wave.length; i++) wave[i] = timeBuf[i * stride]
// Log-binned frequency spectrum: 256 bins from 40 Hz 4000 Hz
const LOG_BINS = 256
const F_MIN = 40, F_MAX = 4000
const binHz = ctx.sampleRate / ca.fftSize
const freqBuf = freqBufRef.current
ca.getFloatFrequencyData(freqBuf)
const spectrum = new Float32Array(LOG_BINS)
for (let b = 0; b < LOG_BINS; b++) {
const f = F_MIN * Math.pow(F_MAX / F_MIN, b / (LOG_BINS - 1))
const bin = Math.round(f / binHz)
if (bin < freqBuf.length) {
const db = freqBuf[bin]
spectrum[b] = db < NOISE_FLOOR ? 0 : Math.max(0, (db - NOISE_FLOOR) / (-NOISE_FLOOR))
}
}
// Peak-hold with exponential decay spectrum rises instantly, falls slowly
if (!specPeakRef.current) specPeakRef.current = new Float32Array(LOG_BINS)
const peak = specPeakRef.current
for (let b = 0; b < LOG_BINS; b++) {
peak[b] = spectrum[b] > peak[b] ? spectrum[b] : peak[b] * 0.92
}
let detectedFreq = null, detectedNote = null
if (rms >= minVolumeRef.current) {
const [f, c] = detectorRef.current.findPitch(timeBuf, ctx.sampleRate)
if (c >= minClarityRef.current && f > 60 && f < 4200) {
detectedFreq = f
detectedNote = NOTES[((Math.round(12 * Math.log2(f / 440) + 69) % 12) + 12) % 12]
}
}
onWaveformRef.current({ wave, rms, detectedFreq, detectedNote, spectrum: peak })
}
if (rms >= minVolumeRef.current) {
const [freq, clarity] = detectorRef.current.findPitch(timeBuf, ctx.sampleRate)
if (clarity >= minClarityRef.current && freq > 60 && freq < 4200) {
const midi = Math.round(12 * Math.log2(freq / 440) + 69)
const pitchClass = ((midi % 12) + 12) % 12
onNoteRef.current({ noteName: NOTES[pitchClass], pitchClass, freq, midi, clarity })
}
if (onChromaRef.current) {
const freqBuf = freqBufRef.current
ca.getFloatFrequencyData(freqBuf)
onChromaRef.current(
computeChroma(freqBuf, ctx.sampleRate, ca.fftSize),
detectBassPC(freqBuf, ctx.sampleRate, ca.fftSize)
)
}
}
rafRef.current = requestAnimationFrame(tick)
}
tick()
}, [stop])
useEffect(() => {
if (isListening) start().catch(console.error)
else stop()
return stop
}, [isListening, start, stop])
return null
}
+169
View File
@@ -0,0 +1,169 @@
import { getPentatonicScale, getFullScale, getChordTones, NOTES } from '../lib/theory'
// Standard bass tuning (top of diagram = highest string)
const STRINGS = [
{ label: 'G', root: 7, thickness: 1.5 },
{ label: 'D', root: 2, thickness: 2 },
{ label: 'A', root: 9, thickness: 2.5 },
{ label: 'E', root: 4, thickness: 3 },
]
const NUM_FRETS = 13
const FRET_MARKERS = [3, 5, 7, 9]
const DOUBLE_MARKER = 12
// Layout
const NUT_X = 40
const OPEN_X = 18
const FRET_W = 52
const STRING_H = 36 // wider spacing than guitar 4 strings feel more spread
const PAD_T = 28
const PAD_B = 18
const BOARD_W = NUT_X + (NUM_FRETS - 1) * FRET_W + 10
const BOARD_H = PAD_T + 3 * STRING_H + PAD_B
const DOT_R = 10
const fretX = f => NUT_X + (f - 0.5) * FRET_W
const stringY = si => PAD_T + si * STRING_H
function noteColor(isChordTone, isPenta, isScale, mono = false) {
if (isChordTone) return { fill: '#a855f7', text: '#fff' }
if (isPenta) return mono ? { fill: '#c084fc', text: '#1e1b4b' } : { fill: '#f59e0b', text: '#000' }
if (isScale) return mono ? { fill: '#e9d5ff', text: '#581c87' } : { fill: '#374151', text: '#d1d5db' }
return null
}
// `compact` (task L-50, one-screen.md §2): trimmed card chrome (p-3, legend
// merged onto the heading line) + a natural-width cap on the SVG (max-width =
// its viewBox width, so it never renders above scale 1.0).
export default function BassFretboard({ keyInfo, currentChord, monoColor = false, compact = false }) {
const { root, mode } = keyInfo ?? {}
if (!root) return null
const pentaSet = new Set(getPentatonicScale(root, mode).map(n => NOTES.indexOf(n)))
const scaleSet = new Set(getFullScale(root, mode).map(n => NOTES.indexOf(n)))
const chordSet = currentChord
? new Set(getChordTones(currentChord).map(n => NOTES.indexOf(n)))
: new Set()
const heading = (
<p className={`text-sm text-gray-500 uppercase tracking-widest ${compact ? '' : 'mb-4'}`}>
Bass {root} {mode}
{currentChord && <span className="text-amber-400 ml-2">/ {currentChord}</span>}
</p>
)
const legend = (
// Critic mechanical fix (L-50 gate): non-compact keeps HEAD's exact class
// string so the non-compact render stays byte-identical to the committed one.
<div className={compact ? 'flex items-center text-xs text-gray-500 flex-wrap gap-3' : 'mt-3 flex gap-5 text-xs text-gray-500'}>
<span><span className="text-accent"></span> Chord tone</span>
<span style={{ color: monoColor ? '#c084fc' : '#f59e0b' }}></span><span> Pentatonic</span>
<span style={{ color: monoColor ? '#e9d5ff' : '#6b7280' }}></span><span> Scale</span>
</div>
)
return (
<div className={`bg-panel border border-border rounded-2xl ${compact ? 'p-3' : 'p-6'}`}>
{compact ? (
<div className="mb-2 flex flex-wrap items-center justify-between gap-x-4 gap-y-1">
{heading}
{legend}
</div>
) : (
heading
)}
<div>
<svg
viewBox={`0 0 ${BOARD_W} ${BOARD_H}`}
width="100%"
height="auto"
style={{ display: 'block', ...(compact ? { maxWidth: BOARD_W } : null) }}
>
{/* Fretboard background */}
<rect x={NUT_X} y={PAD_T - 6} width={BOARD_W - NUT_X - 4} height={3 * STRING_H + 12}
fill="#1a120b" rx={2} />
{/* Position marker dots (centred between strings 12) */}
{FRET_MARKERS.map(f => (
<circle key={f}
cx={fretX(f)} cy={PAD_T + 1.5 * STRING_H}
r={5} fill="#3a2a1a" />
))}
{/* Double dot at 12 */}
<circle cx={fretX(DOUBLE_MARKER)} cy={PAD_T + 0.5 * STRING_H} r={5} fill="#3a2a1a" />
<circle cx={fretX(DOUBLE_MARKER)} cy={PAD_T + 2.5 * STRING_H} r={5} fill="#3a2a1a" />
{/* Fret lines */}
{Array.from({ length: NUM_FRETS - 1 }, (_, i) => i + 1).map(f => (
<line key={f}
x1={NUT_X + f * FRET_W} y1={PAD_T - 6}
x2={NUT_X + f * FRET_W} y2={PAD_T + 3 * STRING_H + 6}
stroke={f === DOUBLE_MARKER ? '#888' : '#4a3a2a'}
strokeWidth={f === DOUBLE_MARKER ? 2 : 1} />
))}
{/* Nut */}
<line x1={NUT_X} y1={PAD_T - 6} x2={NUT_X} y2={PAD_T + 3 * STRING_H + 6}
stroke="#c0b090" strokeWidth={4} />
{/* Strings — thicker as pitch drops */}
{STRINGS.map((s, si) => (
<line key={si}
x1={OPEN_X - DOT_R - 2} y1={stringY(si)}
x2={BOARD_W - 8} y2={stringY(si)}
stroke="#9ca3af"
strokeWidth={s.thickness} />
))}
{/* Fret numbers */}
{[3, 5, 7, 9, 12].map(f => (
<text key={f}
x={fretX(f)} y={PAD_T - 10}
textAnchor="middle" fontSize={10} fill="#6b7280"
>{f}</text>
))}
{/* String labels */}
{STRINGS.map((s, si) => (
<text key={si}
x={6} y={stringY(si) + 4}
textAnchor="middle" fontSize={10} fill="#6b7280"
>{s.label}</text>
))}
{/* Note dots */}
{STRINGS.flatMap((str, si) =>
Array.from({ length: NUM_FRETS }, (_, fi) => {
const pc = (str.root + fi) % 12
const color = noteColor(chordSet.has(pc), pentaSet.has(pc), scaleSet.has(pc), monoColor)
if (!color) return null
const cx = fi === 0 ? OPEN_X : fretX(fi)
const cy = stringY(si)
return (
<g key={`${si}-${fi}`}>
<circle cx={cx} cy={cy} r={DOT_R} fill={color.fill} />
<text
x={cx} y={cy + 4}
textAnchor="middle"
fontSize={9}
fontWeight="600"
fill={color.text}
>
{NOTES[pc]}
</text>
</g>
)
})
)}
</svg>
</div>
{!compact && legend}
</div>
)
}
+415
View File
@@ -0,0 +1,415 @@
// BassPatternCard per-station authored bass pattern as compact 4-string tab
// (task L-42, per docs/design/integrated-glance.md §3's gallery-slot contract
// and SCHEMA.md "Bass play").
//
// Given a station's { rootPc, quality }, one play's per-station `pattern`, and
// the NEXT station's root (approach pitches derive from it the loop wraps),
// this renders the REALIZED line: the degree/approach data resolved to actual
// pitches and placed on the bass. Visually it rhymes with LickCard's tab SVG
// (same string-line + surface-pill-number language, same technique-glyph
// vocabulary) but with the bass rendering convention from SCHEMA.md:
//
// standard 4-string tuning EADG, string 1 = G (HIGHEST) rendered on top,
// string 4 = low E at the bottom the same "1 = highest string" counting as
// lick tab and `rootStr`, so no third scheme exists in this codebase.
//
// Realization rules (SCHEMA.md "Bass play")
// Pitch space: semitones above open low E (E1). Open strings sit at 0 (E),
// 5 (A), 10 (D), 15 (G); the playable ceiling is 30 (G string, fret 15).
//
// · The station ROOT lands on its lowest playable position:
// rootAbs = (rootPc 4) mod 12 (open E's pitch class is 4).
// · A `deg` note sits at rootAbs + resolveDegree(deg, quality) + 12·octave.
// The schema caps the resolved offset at 19 semitones, so every deg note
// fits 30 by construction (11 + 19); anything unresolvable nulls the
// whole pattern and the card renders its placeholder instead of lying.
// · An `approach` note's PITCH CLASS derives from the next station's root:
// chrom-below = next1 · chrom-above = next+1 · fifth-of-next = next+7
// (mod 12). Its OCTAVE is the placement nearest the previous realized note
// (approaches are terminal, so a previous note always exists), which keeps
// the walkup/walkdown contour the author described e.g. the 12-bar bar-4
// walkup CDE lands its E right above the E, not two octaves away.
// · 🚨 C-41 gate rule the open-E floor: a chrom-below into a next root at
// open E (abs 0) has NO pitch below the instrument (1 does not exist).
// When the nearest placement falls below abs 0 it is OCTAVE-DISPLACED up
// (+12): the approach plays a half-step under the OCTAVE root instead
// e.g. D at abs 11 leading into E. The symmetric ceiling guard (> 30
// 12) exists for completeness. This is the displacement rule the ledger
// row mandates; keep it.
// · String/fret: each realized pitch takes the HIGHEST-tuned open string at
// or below it the minimum-fret assignment. Because the root starts at
// its lowest position (fret 11 worst case, usually 8) and strings are
// tuned in fourths, the whole pattern lands in one hand position within
// frets 015 (the schema's 19-semitone span guarantee).
//
// Rendering
// Beat spacing when every note carries a `beat` (columns proportional to beat,
// faint beat numbers under the bottom string); plain even columns otherwise.
// Approach notes draw AMBER (the established secondary-tone colour) with a
// small arrow after the final one they belong to the NEXT chord. Technique
// marks reuse the lick glyph vocabulary in its light form (amber letter/symbol
// above the note; ghost notes parenthesise and dim, as in LickCard).
//
// Playback ()
// Sequential single-note scheduling through chordAudio's playVoicing (one call
// per note playVoicing itself sorts/dedupes, which is wrong for a melodic
// line, so the ORDER lives here in setTimeout scheduling). Bass register:
// realized abs 20 puts open E at chordAudio note 20 = E1 41.2 Hz
// (chordAudio's space is 0 = C3; negatives are documented-legal input).
// Timing: beats at a fixed preview tempo when present, else even eighths.
// One pattern at a time module-wide: each play stops the previous sequence
// AND calls stopAll() so it never layers over a VoicingBrowser preview.
import { useEffect } from 'react'
import { NOTES } from '../lib/theory'
import { resolveDegree } from './JamGuide'
import { playVoicing, stopAll } from '../lib/chordAudio'
// SVG palette mirrors LickCard's token constants (SVG fills can't read
// Tailwind classes): amber = technique/approach, surface = backing pills.
const AMBER = '#f59e0b'
const FRET_TEXT = '#e5e7eb' // gray-200
const GHOST_TEXT = '#9ca3af' // gray-400
const STRING_LINE = '#3a3a3a'
const STRING_LABEL = '#6b7280' // gray-500
const BEAT_LABEL = '#6b7280'
const CARD_BG = '#0f0f0f' // token `surface`
// Strings top bottom: 1 = G (highest), 4 = low E. `open` = semitones above E1.
const STRINGS = [
{ n: 1, name: 'G', open: 15 },
{ n: 2, name: 'D', open: 10 },
{ n: 3, name: 'A', open: 5 },
{ n: 4, name: 'E', open: 0 },
]
const OPEN_E_PC = 4 // pitch class of the low E string
const ABS_MAX = 30 // G string fret 15 the playable ceiling
// Approach-type semitone delta from the NEXT station's root (SCHEMA.md).
const APPROACH_DELTA = { 'chrom-below': -1, 'chrom-above': 1, 'fifth-of-next': 7 }
// Technique mark drawn above the note (light form of LickCard's glyphs; the
// full vocabulary is legal per SCHEMA.md ghost-note is handled by the
// parenthesised dim label, double-stop by equal beats, chromatic-approach and
// unknown words get no mark, exactly like LickCard's graceful default).
const TECH_MARK = {
'hammer-on': 'h',
'pull-off': 'p',
slide: '',
bend: '↑',
vibrato: '~',
}
const mod12 = (n) => ((n % 12) + 12) % 12
// abs (semitones above open E1 = MIDI 28) "E1"/"C2" scientific spelling.
function absName(abs) {
return `${NOTES[mod12(abs + OPEN_E_PC)]}${Math.floor((abs + 28) / 12) - 1}`
}
// Min-fret string assignment: highest-tuned open string at or below the pitch.
function placeOnString(abs) {
for (const s of STRINGS) {
if (abs >= s.open && abs - s.open <= 15) return { string: s.n, fret: abs - s.open }
}
return null // abs outside [0, 30] caller nulls the pattern
}
/**
* realizeBassPattern(pattern, rootPc, quality, nextRootPc)
* [{ abs, string, fret, beat?, technique?, approach }] | null
*
* Pure realization per the header rules. Returns null on ANY malformed or
* unplaceable note so the caller can render a placeholder authored data is
* validator-guaranteed, but a renderer must never crash on bad input.
*/
export function realizeBassPattern(pattern, rootPc, quality, nextRootPc) {
if (!Array.isArray(pattern) || pattern.length === 0) return null
if (!Number.isFinite(rootPc)) return null
const rootAbs = mod12(rootPc - OPEN_E_PC) // lowest playable root position
const out = []
let prev = rootAbs // approach placement anchor (root until a note lands)
for (const note of pattern) {
if (!note || typeof note !== 'object') return null
let abs
if (note.deg !== undefined && note.approach === undefined) {
const off = resolveDegree(String(note.deg), quality)
if (off === null || off === undefined) return null
abs = rootAbs + off + (note.octave === 1 ? 12 : 0)
} else if (note.approach !== undefined && note.deg === undefined) {
const delta = APPROACH_DELTA[note.approach]
if (delta === undefined || !Number.isFinite(nextRootPc)) return null
const pc = mod12(nextRootPc + delta)
const base = mod12(pc - OPEN_E_PC)
// Nearest octave placement to the previous note (ties resolve upward).
abs = base + 12 * Math.round((prev - base) / 12)
// C-41 open-E floor: chrom-below into a next root at open E resolves to
// abs 1, which does not exist on the instrument octave-displace the
// approach up (+12: a half-step under the OCTAVE root). Ceiling mirror.
if (abs < 0) abs += 12
if (abs > ABS_MAX) abs -= 12
} else {
return null // exactly one of deg | approach per note (schema)
}
const placed = placeOnString(abs)
if (!placed) return null
out.push({
abs,
string: placed.string,
fret: placed.fret,
beat: Number.isFinite(note.beat) ? note.beat : undefined,
technique: typeof note.technique === 'string' ? note.technique : undefined,
approach: note.approach !== undefined,
})
prev = abs
}
return out
}
// Sequential playback (module-level: one pattern at a time, app-wide)
const PREVIEW_BPM = 96 // relaxed shuffle-ish preview tempo (display is tempo-free)
let currentSeq = null // { timeouts: number[], handles: {stop}[] }
function stopPattern() {
if (!currentSeq) return
for (const t of currentSeq.timeouts) clearTimeout(t)
for (const h of currentSeq.handles) h.stop()
currentSeq = null
}
function playPattern(realized) {
stopPattern()
stopAll() // never layer over a VoicingBrowser (or any other) preview
const beatMs = 60000 / PREVIEW_BPM
const hasBeats = realized.every((n) => Number.isFinite(n.beat))
// Beats drive onsets when authored; otherwise even eighths.
const times = realized.map((n, i) => (hasBeats ? (n.beat - 1) * beatMs : (i * beatMs) / 2))
const seq = { timeouts: [], handles: [] }
realized.forEach((n, i) => {
// Ring until the next distinct onset (equal beats = a dyad, same onset);
// the last note gets one beat. Small floor so ghost-short gaps still sound.
const nextT = times.slice(i + 1).find((t) => t > times[i])
const durMs = Math.max(160, (nextT !== undefined ? nextT - times[i] : beatMs) + 120)
seq.timeouts.push(
setTimeout(() => {
// abs 20: open E1 in chordAudio's 0 = C3 note space (negatives legal).
seq.handles.push(playVoicing([n.abs - 20], { strumMs: 0, durMs, gain: 0.5 }))
}, times[i]),
)
})
currentSeq = seq
}
// SVG geometry (LickCard's idiom, 4 strings)
const STR_GAP = 13
const PAD_T = 14
const PAD_B = 6
const PAD_L = 20
const PAD_R = 12
const COL_W = 26
const BEAT_ROW = 10 // extra bottom room for beat numbers when beats render
function layoutPattern(realized) {
const hasBeats =
realized.every((n) => Number.isFinite(n.beat)) &&
realized.every((n, i) => i === 0 || n.beat >= realized[i - 1].beat)
let xs, width, maxBeat, unit = null
if (hasBeats) {
// Columns proportional to beat; scale so the tightest gap one column.
const gaps = realized
.map((n, i) => (i > 0 ? n.beat - realized[i - 1].beat : 0))
.filter((g) => g > 0)
const minGap = gaps.length ? Math.min(...gaps) : 1
unit = Math.min(COL_W / minGap, COL_W * 4)
xs = realized.map((n) => PAD_L + (n.beat - 1) * unit + 10)
maxBeat = realized[realized.length - 1].beat
width = PAD_L + (maxBeat - 1) * unit + 20 + PAD_R
} else {
xs = realized.map((_, i) => PAD_L + i * COL_W + COL_W / 2)
width = PAD_L + realized.length * COL_W + PAD_R
maxBeat = null
}
return {
hasBeats,
maxBeat,
unit,
width,
height: PAD_T + 3 * STR_GAP + PAD_B + (hasBeats ? BEAT_ROW : 0),
notes: realized.map((n, i) => ({
...n,
x: xs[i],
y: PAD_T + (n.string - 1) * STR_GAP,
ghost: n.technique === 'ghost-note',
label: n.technique === 'ghost-note' ? `(${n.fret})` : String(n.fret),
})),
}
}
function PatternSvg({ layout, ariaLabel }) {
const { notes, width, height, hasBeats, maxBeat, unit } = layout
const bottomY = PAD_T + 3 * STR_GAP
return (
<svg
viewBox={`0 0 ${width} ${height}`}
width="100%"
style={{ display: 'block', height: 'auto', maxWidth: width * 1.4 }}
role="img"
aria-label={ariaLabel}
>
{/* String lines — string 1 (G) on top, string 4 (low E) at the bottom. */}
{STRINGS.map((s, i) => {
const y = PAD_T + i * STR_GAP
return (
<g key={s.name}>
<line
x1={PAD_L - 6} y1={y} x2={width - PAD_R + 6} y2={y}
stroke={STRING_LINE} strokeWidth={i === 3 ? 1.4 : 1}
/>
<text x={7} y={y + 3} textAnchor="middle" fontSize={7} fill={STRING_LABEL}>
{s.name}
</text>
</g>
)
})}
{/* Beat numbers under the bottom string (only when beats are authored;
x mirrors the note columns: beat 1 at PAD_L + 10, `unit` px per beat). */}
{hasBeats &&
Array.from({ length: Math.floor(maxBeat + 1e-6) }, (_, b) => (
<text
key={`b${b}`}
x={PAD_L + b * unit + 10}
y={bottomY + BEAT_ROW}
textAnchor="middle" fontSize={6.5} fill={BEAT_LABEL}
>
{b + 1}
</text>
))}
{/* Technique marks (light lick vocabulary) above their notes. */}
{notes.map((n, i) =>
TECH_MARK[n.technique] ? (
<text
key={`t${i}`} x={n.x} y={n.y - 8} textAnchor="middle" fontSize={8}
fontStyle="italic" fill={AMBER}
>
{TECH_MARK[n.technique]}
</text>
) : null,
)}
{/* Fret numbers on surface pills; approach notes amber (next chord's). */}
{notes.map((n, i) => {
const w = n.label.length * 5.2 + 3
const isLast = i === notes.length - 1
return (
<g key={`n${i}`}>
<rect x={n.x - w / 2} y={n.y - 5.5} width={w} height={11} rx={2} fill={CARD_BG} />
<text
x={n.x} y={n.y + 3.2} textAnchor="middle" fontSize={9.5} fontWeight="600"
fill={n.approach ? AMBER : n.ghost ? GHOST_TEXT : FRET_TEXT}
>
{n.label}
</text>
{/* The final approach points at the next chord. */}
{n.approach && isLast && (
<text x={n.x + w / 2 + 5} y={n.y + 3} textAnchor="middle" fontSize={8} fill={AMBER}>
</text>
)}
</g>
)
})}
</svg>
)
}
// The card
// Same pill as VoicingBrowser's gallery cells (its PlayButton is file-local;
// classes mirrored so the two galleries read identically).
function PlayButton({ ariaLabel, onClick }) {
return (
<button
type="button"
aria-label={ariaLabel}
onClick={onClick}
className={
'inline-flex h-7 shrink-0 items-center gap-1.5 rounded-full border border-accent ' +
'bg-surface px-2.5 text-xs font-semibold text-accent outline-none transition ' +
'hover:bg-accent hover:text-black focus-visible:ring-2 focus-visible:ring-accent'
}
>
<svg aria-hidden="true" viewBox="0 0 12 12" className="h-3 w-3 fill-current">
<path d="M2.5 1.5v9l8-4.5z" />
</svg>
Play
</button>
)
}
/**
* <BassPatternCard rootPc quality nextRootPc pattern playLabel feel note chordLabel />
*
* Pure/presentational gallery cell for one station of one bass play. Renders
* the realized 4-string tab + the authored per-station note + its own .
* Malformed/unplaceable patterns render an honest placeholder, never crash.
*/
export default function BassPatternCard({
rootPc,
quality,
nextRootPc,
pattern,
playLabel,
feel,
note,
chordLabel,
}) {
const realized = realizeBassPattern(pattern, rootPc, quality, nextRootPc)
// Unmount (loop/style/instrument change) silences any running sequence
// module-level state, so this is idempotent across sibling cards.
useEffect(() => () => stopPattern(), [])
if (!realized) {
return (
<div
role="group"
aria-label={`${playLabel ?? 'bass pattern'} — unavailable`}
className="flex min-h-[72px] min-w-[140px] flex-col items-center justify-center rounded-md border border-dashed border-border p-2 text-gray-500"
>
<span className="text-lg leading-none" aria-hidden="true"></span>
<span className="mt-1 text-[10px]">pattern unavailable</span>
</div>
)
}
const layout = layoutPattern(realized)
const pitchNames = realized.map((n) => absName(n.abs)).join(', ')
const label = playLabel ?? 'Bass pattern'
return (
<figure className="flex w-[220px] min-w-0 shrink-0 flex-col gap-1.5 rounded-md border border-border bg-surface p-2">
<figcaption
className="text-[11px] font-medium leading-tight text-gray-300"
title={feel ?? undefined}
>
{label}
</figcaption>
<div className="max-w-full overflow-x-auto">
<PatternSvg
layout={layout}
ariaLabel={`Bass tab for ${chordLabel ?? 'this chord'}${label}: ${pitchNames}`}
/>
</div>
{note && <p className="text-[10px] leading-snug text-gray-500">{note}</p>}
<PlayButton
ariaLabel={`Play ${chordLabel ?? 'chord'} bass pattern — ${label}`}
onClick={() => playPattern(realized)}
/>
</figure>
)
}
+137
View File
@@ -0,0 +1,137 @@
// SVG chord diagram 6 strings × 5 visible frets
// Props:
// frets[] [s6s1]: fret number or 'x' (muted)
// fingers[] [s6s1]: finger 1-4, 0 = open/barre indicator
// barre { fret, fromStr, toStr } or null
// baseFret which fret number is at the top of the diagram (1 = standard)
// label caption below the box
const STRINGS = 6
const ROWS = 5 // visible frets
const SX = 32 // left margin (open/mute indicators)
const SY = 28 // top margin (nut / baseFret label)
const GX = 26 // gap between strings
const GY = 22 // gap between frets
const DOT_R = 9 // dot radius
const W = SX + GX * (STRINGS - 1) + 24 // total width
const H = SY + GY * ROWS + 20 // total height
function strX(s) { return SX + (STRINGS - 1 - s) * GX } // s=0 is s6 (low E, leftmost)
function fretY(f) { return SY + f * GY } // f=0 is above first fret, f=15 are fret centers
export default function ChordBox({ frets, fingers, barre, baseFret = 1, label }) {
const isOpen = baseFret === 1
// Map fret numbers to diagram row (0-indexed from top)
function toRow(absF) {
return absF - baseFret + 1 // fret at baseFret row 1 (center of first fret)
}
// Barre bar: draw a rounded rect across strings
function renderBarre() {
if (!barre) return null
const row = toRow(barre.fret)
if (row < 1 || row > ROWS) return null
const x1 = strX(STRINGS - barre.toStr) // toStr is highest string number = leftmost
const x2 = strX(STRINGS - barre.fromStr) // fromStr is lowest string number = rightmost
const cy = fretY(row) - GY / 2
return (
<rect
key="barre"
x={x1 - DOT_R}
y={cy - DOT_R}
width={x2 - x1 + DOT_R * 2}
height={DOT_R * 2}
rx={DOT_R}
fill="#a855f7"
opacity={0.9}
/>
)
}
return (
<div className="flex flex-col items-center gap-1">
<svg width={W} height={H} viewBox={`0 0 ${W} ${H}`} className="overflow-visible">
{/* ── Nut or baseFret indicator ── */}
{isOpen ? (
<rect x={SX - 2} y={SY - 4} width={GX * (STRINGS - 1) + 4} height={4} rx={2} fill="#e5e7eb" />
) : (
<text x={SX - 6} y={SY + GY * 0.5} textAnchor="end" dominantBaseline="middle"
fill="#9ca3af" fontSize={10} fontFamily="monospace">
{baseFret}
</text>
)}
{/* ── Fret lines ── */}
{Array.from({ length: ROWS + 1 }, (_, i) => (
<line key={`fl${i}`}
x1={SX} y1={fretY(i) - GY / 2}
x2={SX + GX * (STRINGS - 1)} y2={fretY(i) - GY / 2}
stroke="#374151" strokeWidth={i === 0 && isOpen ? 3 : 1}
/>
))}
{/* ── String lines ── */}
{Array.from({ length: STRINGS }, (_, s) => (
<line key={`sl${s}`}
x1={strX(s)} y1={SY - GY / 2}
x2={strX(s)} y2={fretY(ROWS) - GY / 2}
stroke="#4b5563" strokeWidth={1}
/>
))}
{/* ── Barre ── */}
{renderBarre()}
{/* ── Dots + open/mute indicators ── */}
{frets.map((f, s) => {
const cx = strX(STRINGS - 1 - s)
if (f === 'x') {
return (
<text key={`m${s}`} x={cx} y={SY - GY / 2 - 7}
textAnchor="middle" fill="#6b7280" fontSize={12} fontWeight="bold">
×
</text>
)
}
if (f === 0) {
return (
<circle key={`o${s}`} cx={cx} cy={SY - GY / 2 - 7}
r={5} fill="none" stroke="#6b7280" strokeWidth={1.5} />
)
}
const row = toRow(f)
if (row < 1 || row > ROWS) return null
const cy = fretY(row) - GY / 2
const finger = fingers?.[s] ?? 0
return (
<g key={`d${s}`}>
<circle cx={cx} cy={cy} r={DOT_R} fill="#a855f7" />
{finger > 0 && (
<text x={cx} y={cy} textAnchor="middle" dominantBaseline="middle"
fill="white" fontSize={9} fontWeight="bold">
{finger}
</text>
)}
</g>
)
})}
{/* ── String name labels ── */}
{['e','B','G','D','A','E'].map((n, i) => (
<text key={`sn${i}`}
x={strX(i)} y={H - 4}
textAnchor="middle" fill="#4b5563" fontSize={8}>
{n}
</text>
))}
</svg>
{label && (
<p className="text-[11px] text-gray-400 text-center leading-tight max-w-[120px]">{label}</p>
)}
</div>
)
}
+815
View File
@@ -0,0 +1,815 @@
import { useState, useEffect } from 'react'
import ChordBox from './ChordBox'
import MiniPiano from './MiniPiano'
import VoicingBrowser from './VoicingBrowser'
import { getGuitarVoicings, getPianoTechniques, parseChord } from '../lib/voicings'
import { CHORD_TYPES, NOTES, getChordsInKey, toRomanNumeral, getSuggestedProgressions } from '../lib/theory'
import { FAMOUS_PROGRESSIONS, progressionInKey, getChordSubstitutions, CHORD_PLAYBOOK } from '../lib/education'
const CHORD_SUFFIX_OPTIONS = [
{ key: 'maj', label: 'Major' },
{ key: 'min', label: 'Minor' },
{ key: 'dom7', label: '7' },
{ key: 'maj7', label: 'maj7' },
{ key: 'min7', label: 'm7' },
{ key: 'dim', label: 'dim' },
{ key: 'dim7', label: 'dim7' },
{ key: 'half_dim', label: 'm7♭5' },
{ key: 'aug', label: 'aug' },
{ key: 'sus4', label: 'sus4' },
{ key: 'sus2', label: 'sus2' },
{ key: 'maj6', label: '6' },
{ key: 'min6', label: 'm6' },
{ key: 'add9', label: 'add9' },
]
function chordDisplayName(root, typeKey) {
const type = CHORD_TYPES[typeKey]
if (!type) return root
return root + type.suffix
}
function GuitarTab({ chordName }) {
// parseChord's `type` is a CHORD_TYPES key exactly VoicingBrowser's
// `quality` prop (same mapping PianoTab/ExploreTab already rely on). L-21.
const parsed = parseChord(chordName)
const voicings = getGuitarVoicings(chordName)
if (!parsed && !voicings.length) {
return <p className="text-gray-500 text-sm text-center py-8">No guitar voicings found for {chordName}.</p>
}
return (
<div className="flex flex-col gap-5">
{/* Playable voicing browser (D-21) browse + audition shapes.
Instrument-scoped to this tab via `show` (task L-25). */}
{parsed && <VoicingBrowser rootPc={parsed.rootPc} quality={parsed.type} show="guitar" />}
{/* Static grid kept as the fingering reference it carries finger
numbers and barre info the browser doesn't show. */}
{voicings.length > 0 && (
<div>
<p className="text-[11px] uppercase tracking-wider text-gray-600 mb-2">More grips fingering reference</p>
<p className="text-xs text-gray-500 mb-4">
Click any voicing to learn it. Purple = chord tones. Finger numbers inside dots (1=index, 4=pinky).
Barre chords show the fret number on the left.
</p>
<div className="flex flex-wrap gap-6 justify-start">
{voicings.map((v, i) => (
<div key={i} className="flex flex-col items-center gap-1 p-3 rounded-xl bg-surface border border-border hover:border-accent/40 transition-colors">
<ChordBox
frets={v.frets}
fingers={v.fingers}
barre={v.barre}
baseFret={v.baseFret}
/>
<p className="text-[11px] text-gray-400 text-center mt-1 max-w-[120px] leading-tight">{v.label}</p>
</div>
))}
</div>
<div className="mt-4 p-3 rounded-lg bg-surface border border-border">
<p className="text-xs text-gray-500">
<span className="text-accent font-semibold">Pro tip:</span> Learn the E-shape and A-shape barres first
they cover all 12 roots. Then add open voicings for the keys you play in most.
High-fret voicings (above fret 7) work great as jazz comping shapes in a band mix.
</p>
</div>
</div>
)}
</div>
)
}
function PianoTab({ chordName }) {
const parsed = parseChord(chordName)
const techniques = getPianoTechniques(chordName)
const rootPc = parsed?.rootPc ?? 0
if (!parsed && !techniques.length) {
return <p className="text-gray-500 text-sm text-center py-8">No piano techniques for {chordName}.</p>
}
return (
<div className="flex flex-col gap-4">
{/* Playable voicing browser (D-21) parseChord's `type` maps 1:1 to the
browser's `quality` (CHORD_TYPES key). L-21. Piano-scoped via `show` (L-25). */}
{parsed && <VoicingBrowser rootPc={parsed.rootPc} quality={parsed.type} show="piano" />}
{/* Technique cards kept below the name/desc/tip text and LH/RH note
breakdown are not covered by the browser. */}
{techniques.length > 0 && (
<p className="text-[11px] uppercase tracking-wider text-gray-600 mt-1">Techniques how to use it at the keys</p>
)}
{techniques.length > 0 && (
<p className="text-xs text-gray-500">
<span className="text-blue-400 font-semibold">Blue = Left hand</span> &nbsp;·&nbsp;
<span className="text-accent font-semibold">Purple = Right hand</span> &nbsp;·&nbsp;
R marks the root.
</p>
)}
{techniques.map((t, i) => (
<div key={i} className="p-4 rounded-xl bg-surface border border-border hover:border-accent/30 transition-colors">
<div className="flex flex-col lg:flex-row gap-4 items-start">
<div className="shrink-0 overflow-x-auto">
<MiniPiano rootPc={rootPc} lh={t.lh} rh={t.rh} />
</div>
<div className="flex flex-col gap-1.5 min-w-0">
<h3 className="font-bold text-white text-sm">{t.name}</h3>
<p className="text-gray-400 text-xs">{t.desc}</p>
<p className="text-xs text-amber-400/80 mt-1">
<span className="text-amber-400 font-semibold">Tip:</span> {t.tip}
</p>
<div className="flex gap-3 mt-1 text-xs text-gray-600">
{t.lh.length > 0 && (
<span className="text-blue-400">LH: {t.lh.map(iv => {
const n = NOTES[(rootPc + iv) % 12]
return iv === 0 ? `${n} (root)` : n
}).join(', ')}</span>
)}
{t.rh.length > 0 && (
<span className="text-accent">RH: {t.rh.map(iv => {
const n = NOTES[(rootPc + iv) % 12]
return n
}).join(', ')}</span>
)}
</div>
</div>
</div>
</div>
))}
</div>
)
}
function ChordQuickPick({ label, chords, active, keyInfo, onSelect }) {
if (!chords.length) return null
return (
<div className="flex flex-wrap items-center gap-2">
<span className="text-[11px] text-gray-600 uppercase tracking-wider shrink-0 w-20">{label}</span>
<div className="flex flex-wrap gap-1.5">
{chords.map(chord => {
const rn = keyInfo?.root ? toRomanNumeral(chord, keyInfo.root, keyInfo.mode) : ''
return (
<button key={chord}
onClick={() => onSelect(chord)}
className={`flex flex-col items-center px-2.5 py-1 rounded-lg border text-xs font-bold transition-all ${
active === chord
? 'bg-accent border-accent text-white'
: 'bg-surface border-border text-gray-300 hover:border-accent/50 hover:text-white'
}`}>
<span>{chord}</span>
{rn && <span className="text-[9px] font-normal opacity-60 leading-none">{rn}</span>}
</button>
)
})}
</div>
</div>
)
}
// Progressions sub-tab
// Determine whether a chord type is major-ish or minor-ish for matching
const MAJOR_TYPES = new Set(['maj','maj7','maj6','add9','sus4','sus2','aug','dom7'])
const MINOR_TYPES = new Set(['min','min7','min6','half_dim','dim','dim7'])
function isMajorType(t) { return MAJOR_TYPES.has(t) }
function isMinorType(t) { return MINOR_TYPES.has(t) }
function ProgressionsSubTab({ chordName, onChordClick }) {
const parsed = parseChord(chordName)
if (!parsed) return null
const { rootPc, type } = parsed
const root = NOTES[rootPc]
// Famous progressions where this chord can be the tonic (degree 0)
const isMajor = isMajorType(type)
const isMinor = isMinorType(type)
const tonicProgs = FAMOUS_PROGRESSIONS.filter(p => {
const q0 = p.qualities[0]
if (isMajor && isMajorType(q0)) return true
if (isMinor && isMinorType(q0)) return true
return false
})
// Genre-based suggestions from theory.js
const genreProgs = getSuggestedProgressions(root, isMajor ? 'major' : 'minor')
// Roles this chord plays in other keys
const ROLES = []
for (let keyPc = 0; keyPc < 12; keyPc++) {
for (const mode of ['major', 'minor']) {
const diatonicChords = getChordsInKey(NOTES[keyPc], mode)
const idx = diatonicChords.indexOf(chordName)
if (idx !== -1) {
const rn = toRomanNumeral(chordName, NOTES[keyPc], mode)
ROLES.push({ keyRoot: NOTES[keyPc], mode, rn, diatonicChords })
break
}
}
}
return (
<div className="flex flex-col gap-5">
{/* ── Famous progressions starting from this chord ── */}
<div>
<p className="text-[11px] uppercase tracking-wider text-gray-600 mb-3">
Famous progressions {chordName} as tonic
</p>
{tonicProgs.length === 0 && (
<p className="text-gray-600 text-sm">No exact matches try a major or minor chord.</p>
)}
<div className="flex flex-col gap-3">
{tonicProgs.slice(0, 6).map(prog => {
const chordsHere = progressionInKey(prog, root)
return (
<div key={prog.id} className="p-3 bg-surface border border-border rounded-xl hover:border-accent/30 transition-colors">
<div className="flex items-center gap-2 flex-wrap mb-2">
<span className="font-bold text-white text-sm">{prog.name}</span>
<span className="text-[10px] font-mono text-gray-500">{prog.pattern}</span>
{prog.genre.map(g => (
<span key={g} className="px-1.5 py-0.5 bg-accent/10 border border-accent/20 rounded text-[10px] text-accent">{g}</span>
))}
</div>
{/* Chord sequence */}
<div className="flex flex-wrap gap-1.5 items-center mb-2">
{chordsHere.map((c, i) => (
<span key={i} className="flex items-center gap-1">
<button
onClick={() => onChordClick?.(c)}
className={`px-2.5 py-1 rounded-lg font-bold text-sm border transition-all ${
i === 0
? 'bg-accent border-accent text-white'
: 'bg-panel border-border text-gray-200 hover:border-accent/50 hover:text-accent'
}`}
title={`Voicings for ${c}`}
>
{c}
</button>
{i < chordsHere.length - 1 && <span className="text-gray-700 text-xs"></span>}
</span>
))}
</div>
<p className="text-xs text-gray-500 leading-snug">{prog.description}</p>
{prog.songs[0] && (
<p className="text-[11px] text-gray-600 mt-1">e.g. {prog.songs.slice(0, 3).join(' · ')}</p>
)}
</div>
)
})}
</div>
</div>
{/* ── Genre-based next-chord suggestions ── */}
{genreProgs.length > 0 && (
<div>
<p className="text-[11px] uppercase tracking-wider text-gray-600 mb-3">
Genre suggestions starting from {chordName}
</p>
<div className="flex flex-col gap-2">
{genreProgs.slice(0, 6).map((prog, pi) => (
<div key={pi} className="flex items-center gap-2 p-2 bg-surface border border-border rounded-lg flex-wrap">
<span className="text-[10px] font-bold text-gray-500 w-14 shrink-0">{prog.genre}</span>
<div className="flex gap-1.5 flex-wrap items-center">
{prog.chords.map((c, i) => (
<span key={i} className="flex items-center gap-1">
<button
onClick={() => onChordClick?.(c)}
className="px-2 py-0.5 bg-panel border border-border hover:border-accent/50 rounded text-xs font-bold text-gray-200 hover:text-accent transition-all"
title={`Voicings for ${c}`}
>
{c}
</button>
{i < prog.chords.length - 1 && <span className="text-gray-700 text-[10px]"></span>}
</span>
))}
</div>
<span className="text-[10px] text-gray-600 font-mono ml-1">{prog.rn?.join(' ')}</span>
</div>
))}
</div>
</div>
)}
{/* ── Roles this chord plays ── */}
{ROLES.length > 0 && (
<div>
<p className="text-[11px] uppercase tracking-wider text-gray-600 mb-3">
{chordName} appears in these keys
</p>
<div className="flex flex-wrap gap-2">
{ROLES.slice(0, 8).map(({ keyRoot, mode, rn, diatonicChords }) => (
<div key={`${keyRoot}-${mode}`}
className="px-3 py-2 bg-surface border border-border rounded-xl text-xs flex flex-col gap-1">
<div className="flex items-center gap-1.5">
<span className="font-bold text-white">{keyRoot}</span>
<span className="text-gray-500 capitalize">{mode}</span>
<span className="text-amber-400 font-bold">{rn}</span>
</div>
<div className="flex gap-1 flex-wrap">
{diatonicChords.map((c, i) => (
<button key={i}
onClick={() => onChordClick?.(c)}
className={`px-1.5 py-0.5 rounded text-[10px] font-bold transition-all ${
c === chordName
? 'bg-accent text-white'
: 'text-gray-500 hover:text-gray-300'
}`}>
{c}
</button>
))}
</div>
</div>
))}
</div>
</div>
)}
</div>
)
}
// Theory tab
const CHORD_THEORY = {
maj: {
name: 'Major',
formula: 'Root + Major 3rd (4 semitones) + Perfect 5th (7 semitones)',
vibe: 'Bright, happy, resolved. The most "complete" sound in Western music.',
beginner: 'Major chords are the foundation of almost every song you know. They feel stable and uplifting — like a musical full stop.',
tension: 'Low — very stable',
color: 'text-yellow-400',
},
min: {
name: 'Minor',
formula: 'Root + Minor 3rd (3 semitones) + Perfect 5th (7 semitones)',
vibe: 'Dark, melancholic, introspective. The 3rd is lowered by just one semitone — that one note changes everything.',
beginner: 'One note separates major from minor. Minor chords carry emotion and depth — sadness, mystery, tension.',
tension: 'Low-medium — stable but moody',
color: 'text-blue-400',
},
dom7: {
name: 'Dominant 7th',
formula: 'Major triad + Minor 7th (10 semitones)',
vibe: 'Tense, bluesy, urgent. Wants desperately to resolve to a chord a 5th lower.',
beginner: 'The 7th chord is the engine of blues and jazz. It creates tension that begs to resolve — like holding your breath. Play G7 then C to feel it.',
tension: 'High — strongly pulls to resolution',
color: 'text-red-400',
},
maj7: {
name: 'Major 7th',
formula: 'Major triad + Major 7th (11 semitones)',
vibe: 'Dreamy, lush, sophisticated. Jazz-infused warmth without the tension of a dominant 7th.',
beginner: 'The major 7th is the note just below the octave. Adding it to a major chord gives you that smooth jazz-bossa nova sound — think "Autumn Leaves".',
tension: 'Very low — ethereal and floating',
color: 'text-purple-400',
},
min7: {
name: 'Minor 7th',
formula: 'Minor triad + Minor 7th (10 semitones)',
vibe: 'Smooth, soulful, relaxed. Darker than major 7th but less tense than a dominant 7th.',
beginner: 'Minor 7ths are everywhere in soul, R&B, and jazz. They\'re minor chords with added warmth — moody but not harsh.',
tension: 'Low-medium — smooth and flowing',
color: 'text-indigo-400',
},
dim: {
name: 'Diminished',
formula: 'Root + Minor 3rd (3 semitones) + Diminished 5th (6 semitones)',
vibe: 'Dark, tense, unstable. The flattened 5th creates a tritone interval — historically called "diabolus in musica" (the devil in music).',
beginner: 'Diminished chords are passing chords — they create maximum tension so the next chord feels like a huge relief. Like a musical cliffhanger.',
tension: 'Very high — wants to resolve immediately',
color: 'text-orange-400',
},
dim7: {
name: 'Diminished 7th',
formula: 'Diminished triad + Diminished 7th (9 semitones) — fully symmetric, all minor 3rds',
vibe: 'Extremely tense and dramatic. Used in horror film scores and dramatic classical passages.',
beginner: 'All four notes are equally spaced (all minor 3rds apart), making it the most symmetrical and unstable chord. Classic "villain arrives" sound.',
tension: 'Extreme — maximum instability',
color: 'text-red-600',
},
half_dim: {
name: 'Half-Diminished (m7♭5)',
formula: 'Diminished triad + Minor 7th (10 semitones)',
vibe: 'Dark and tense but with slightly more resolution than full dim7. The "ii" chord in minor iiVi jazz progressions.',
beginner: 'Half-diminished sits between a minor 7th and a fully diminished chord. It\'s the moody jazz workhorse — think the intro to "Autumn Leaves".',
tension: 'High — tense but musical',
color: 'text-orange-500',
},
aug: {
name: 'Augmented',
formula: 'Root + Major 3rd (4 semitones) + Augmented 5th (8 semitones) — all major 3rds',
vibe: 'Eerie, floating, dreamlike. The raised 5th creates instability that can resolve either up or down.',
beginner: 'Augmented chords sound like something is about to happen. They\'re often used as a passing chord between major and minor — the 5th feels like it\'s "reaching" upward.',
tension: 'High — ambiguous direction',
color: 'text-emerald-400',
},
sus4: {
name: 'Suspended 4th',
formula: 'Root + Perfect 4th (5 semitones) + Perfect 5th (7 semitones)',
vibe: 'Open, unresolved, expectant. The 3rd is replaced by a 4th — neither major nor minor, just floating.',
beginner: '"Sus" means suspended — the 3rd is suspended in mid-air. It wants to drop down to a major or minor chord. Classic rock move: sus4 → major.',
tension: 'Medium — pleasant tension, easy on the ear',
color: 'text-cyan-400',
},
sus2: {
name: 'Suspended 2nd',
formula: 'Root + Major 2nd (2 semitones) + Perfect 5th (7 semitones)',
vibe: 'Airy, spacious, ambiguous. Like sus4 but lighter — the 2nd sits high above the root.',
beginner: 'Sus2 is a favourite of modern pop and ambient music. Without a 3rd, it has no major/minor quality — it just floats. Think Sting, U2, Coldplay.',
tension: 'Low-medium — open and spacious',
color: 'text-teal-400',
},
maj6: {
name: 'Major 6th',
formula: 'Major triad + Major 6th (9 semitones)',
vibe: 'Sweet, vintage, nostalgic. The 6th adds a note from the scale without the tension of a 7th.',
beginner: "The 6th is a colour tone that sweetens a major chord. Common in jazz, bossa nova, and 50s pop — \"Misty\" and \"Fly Me To The Moon\" territory.",
tension: 'Very low — sweeter than major triad',
color: 'text-amber-300',
},
min6: {
name: 'Minor 6th',
formula: 'Minor triad + Major 6th (9 semitones)',
vibe: 'Bittersweet, exotic, dramatic. A major 6th over a minor chord creates a striking contrast.',
beginner: 'Minor 6ths have a flamenco/tango feel. The bright 6th sitting on top of a dark minor chord creates a sophisticated tension — think Django Reinhardt.',
tension: 'Medium — intriguing contrast',
color: 'text-amber-400',
},
add9: {
name: 'Add 9',
formula: 'Major triad + Major 9th (14 semitones = octave + 2)',
vibe: 'Open, modern, slightly epic. The 9th adds colour without the smoothness of a 7th.',
beginner: 'Add9 is the chord of modern rock and pop. Unlike maj9 (which also has a 7th), add9 keeps things clean and direct. Coldplay, Radiohead, and U2 love it.',
tension: 'Very low — bright and open',
color: 'text-lime-400',
},
}
const INTERVAL_NAMES = {
0: 'Root', 2: 'Major 2nd', 3: 'Minor 3rd', 4: 'Major 3rd',
5: 'Perfect 4th', 6: 'Tritone (♭5)', 7: 'Perfect 5th',
8: 'Aug 5th', 9: 'Major 6th', 10: 'Minor 7th', 11: 'Major 7th',
14: 'Major 9th',
}
function TheoryTab({ chordName }) {
const parsed = parseChord(chordName)
if (!parsed) return <p className="text-gray-500 text-sm text-center py-8">Could not parse chord.</p>
const { rootPc, type } = parsed
const typeInfo = CHORD_TYPES[type]
const theory = CHORD_THEORY[type]
const subs = getChordSubstitutions(chordName)
// Actual note names
const noteNames = (typeInfo?.intervals ?? []).map(iv => NOTES[(rootPc + iv) % 12])
// Roles this chord can play
const ROLES = []
for (let keyPc = 0; keyPc < 12; keyPc++) {
for (const mode of ['major', 'minor']) {
const diatonicChords = getChordsInKey(NOTES[keyPc], mode)
const idx = diatonicChords.indexOf(chordName)
if (idx !== -1) {
const rn = toRomanNumeral(chordName, NOTES[keyPc], mode)
ROLES.push({ keyRoot: NOTES[keyPc], mode, rn })
}
}
}
return (
<div className="flex flex-col gap-5">
{/* ── What is this chord? ── */}
<div className="p-4 bg-surface border border-border rounded-xl">
<div className="flex items-baseline gap-3 mb-3">
<span className={`text-lg font-black ${theory?.color ?? 'text-accent'}`}>{chordName}</span>
<span className="text-sm text-gray-400">{theory?.name ?? type}</span>
</div>
{theory && (
<>
<p className="text-sm text-gray-200 leading-relaxed mb-2">{theory.beginner}</p>
<p className="text-xs text-gray-500 italic leading-relaxed">{theory.vibe}</p>
</>
)}
</div>
{/* ── Notes & Formula ── */}
<div className="p-4 bg-surface border border-border rounded-xl">
<p className="text-[11px] uppercase tracking-wider text-gray-600 mb-3">Notes in this chord</p>
<div className="flex flex-wrap gap-2 mb-3">
{(typeInfo?.intervals ?? []).map((iv, i) => (
<div key={i} className={`flex flex-col items-center px-3 py-2 rounded-xl border ${
i === 0 ? 'bg-accent/20 border-accent text-accent' : 'bg-panel border-border text-gray-300'
}`}>
<span className="text-base font-black">{noteNames[i]}</span>
<span className="text-[10px] text-gray-500 leading-none mt-0.5">{INTERVAL_NAMES[iv] ?? `+${iv}`}</span>
</div>
))}
</div>
{theory && (
<div className="text-xs text-gray-600 font-mono bg-panel/50 rounded-lg px-3 py-2 border border-border">
{theory.formula}
</div>
)}
{theory && (
<div className="flex items-center gap-2 mt-2">
<span className="text-[10px] uppercase tracking-wider text-gray-600">Tension:</span>
<span className="text-xs text-gray-400">{theory.tension}</span>
</div>
)}
</div>
{/* ── Chord substitutions ── */}
{subs.length > 0 && (
<div>
<p className="text-[11px] uppercase tracking-wider text-gray-600 mb-3">Colour swaps try these instead</p>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
{subs.map((sub, i) => (
<div key={i} className="flex items-start gap-3 p-3 bg-surface border border-border rounded-xl hover:border-accent/30 transition-colors">
<span className="text-sm font-black text-accent shrink-0 w-16">{sub.chord}</span>
<p className="text-xs text-gray-400 leading-snug">{sub.tip}</p>
</div>
))}
</div>
</div>
)}
{/* ── Keys this chord belongs to ── */}
{ROLES.length > 0 && (
<div>
<p className="text-[11px] uppercase tracking-wider text-gray-600 mb-3">{chordName} appears in these keys</p>
<div className="flex flex-wrap gap-2">
{ROLES.slice(0, 10).map(({ keyRoot, mode, rn }) => (
<div key={`${keyRoot}-${mode}`}
className="px-3 py-2 bg-surface border border-border rounded-xl text-xs flex items-center gap-2">
<span className="font-bold text-white">{keyRoot}</span>
<span className="text-gray-500 capitalize">{mode}</span>
<span className="text-amber-400 font-bold">{rn}</span>
</div>
))}
</div>
<p className="text-[11px] text-gray-700 mt-2">
Roman numerals show the chord's role: I/i = home, IV = subdominant, V = dominant tension, vi/VI = relative minor/major, etc.
</p>
</div>
)}
</div>
)
}
// Learn tab
function LearnTab({ chordName }) {
const parsed = parseChord(chordName)
const playbook = parsed ? CHORD_PLAYBOOK[parsed.type] : null
if (!playbook) {
return <p className="text-gray-500 text-sm text-center py-8">No jam content for {chordName} yet.</p>
}
return (
<div className="flex flex-col gap-5">
{/* ── Jam role ── */}
<div className="px-4 py-3 bg-accent/10 border border-accent/20 rounded-xl">
<p className="text-[10px] uppercase tracking-wider text-accent/60 mb-1">Your role in the jam</p>
<p className="text-sm text-white leading-relaxed">{playbook.jamRole}</p>
</div>
{/* ── Voicings for jamming ── */}
<div>
<p className="text-[11px] uppercase tracking-wider text-gray-600 mb-2">Voicings when to use which</p>
<div className="flex flex-col gap-2">
{playbook.voicings.map((v, i) => (
<div key={i} className="flex gap-3 p-3 bg-surface border border-border rounded-xl hover:border-accent/20 transition-colors">
<span className="text-accent font-black text-lg shrink-0 leading-none mt-0.5">{i + 1}</span>
<div>
<p className="text-xs font-bold text-white mb-0.5">{v.name}</p>
<p className="text-xs text-gray-400 leading-relaxed">{v.use}</p>
</div>
</div>
))}
</div>
<p className="text-[10px] text-gray-700 mt-2">See the Guitar tab for the actual fingerings of each shape.</p>
</div>
{/* ── Licks & fills ── */}
<div>
<p className="text-[11px] uppercase tracking-wider text-gray-600 mb-2">Licks &amp; fills</p>
<div className="flex flex-col gap-3">
{playbook.licks.map((l, i) => (
<div key={i} className="p-4 bg-surface border border-border rounded-xl hover:border-accent/30 transition-colors">
<div className="flex items-center gap-2 mb-2 flex-wrap">
<p className="text-sm font-bold text-white">{l.title}</p>
<span className="text-[9px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-full bg-accent/10 border border-accent/20 text-accent">{l.style}</span>
</div>
<pre className="text-[10px] font-mono text-accent/70 bg-black/40 border border-border rounded-lg px-3 py-2 overflow-x-auto leading-relaxed whitespace-pre mb-2">{l.tab}</pre>
<p className="text-xs text-amber-400/80">
<span className="font-semibold text-amber-400">Key insight: </span>{l.tip}
</p>
</div>
))}
</div>
</div>
{/* ── Jam tips ── */}
<div>
<p className="text-[11px] uppercase tracking-wider text-gray-600 mb-2">Jam tips</p>
<div className="flex flex-col gap-2">
{playbook.jamTips.map((tip, i) => (
<div key={i} className="flex gap-2.5 text-xs text-gray-300 leading-relaxed p-2.5 rounded-lg bg-surface border border-border">
<span className="text-accent shrink-0 font-bold mt-0.5"></span>
<p>{tip}</p>
</div>
))}
</div>
</div>
{/* ── Loop station practice ── */}
{playbook.loopPractice?.length > 0 && (
<div>
<p className="text-[11px] uppercase tracking-wider text-gray-600 mb-2">Loop station practice</p>
<div className="flex flex-col gap-2">
{playbook.loopPractice.map((lp, i) => (
<div key={i} className="p-3 bg-surface border border-border rounded-xl border-l-2 border-l-accent/40">
<p className="text-xs font-bold text-white mb-1">🔁 {lp.title}</p>
<p className="text-xs text-gray-400 leading-relaxed">{lp.body}</p>
</div>
))}
</div>
</div>
)}
</div>
)
}
// Explore tab
function ExploreTab({ initialChord, keyInfo, chordHistory }) {
const parsed = parseChord(initialChord)
const [root, setRoot] = useState(parsed ? NOTES[parsed.rootPc] : 'C')
const [typeKey, setTypeKey] = useState(parsed?.type ?? 'maj')
const [subTab, setSubTab] = useState('guitar')
const [active, setActive] = useState(initialChord ?? '')
const chordName = chordDisplayName(root, typeKey)
function selectChord(chord) {
setActive(chord)
const p = parseChord(chord)
if (p) { setRoot(NOTES[p.rootPc]); setTypeKey(p.type) }
}
const recentChords = [...new Set([...(chordHistory ?? [])].reverse())].slice(0, 12)
const keyChords = keyInfo?.root ? getChordsInKey(keyInfo.root, keyInfo.mode ?? 'major') : []
return (
<div className="flex flex-col gap-4">
{/* ── Contextual quick-picks ── */}
{(recentChords.length > 0 || keyChords.length > 0) && (
<div className="flex flex-col gap-3 p-3 bg-surface border border-border rounded-xl">
<ChordQuickPick label="History" chords={recentChords} active={active} keyInfo={keyInfo} onSelect={selectChord} />
{keyChords.length > 0 && (
<>
{recentChords.length > 0 && <div className="h-px bg-border" />}
<ChordQuickPick
label={`${keyInfo.root} ${keyInfo.mode ?? ''}`}
chords={keyChords} active={active} keyInfo={keyInfo} onSelect={selectChord}
/>
</>
)}
</div>
)}
{/* ── Manual picker ── */}
<div className="flex flex-wrap gap-2 items-center p-3 bg-surface border border-border rounded-xl">
<span className="text-xs text-gray-500 shrink-0">Root:</span>
<div className="flex flex-wrap gap-1">
{NOTES.map(n => (
<button key={n}
onClick={() => { setRoot(n); setActive('') }}
className={`px-2 py-0.5 rounded text-xs font-bold transition-all ${
root === n ? 'bg-accent text-white' : 'bg-border text-gray-400 hover:text-white'
}`}>
{n}
</button>
))}
</div>
<div className="w-px h-4 bg-border shrink-0" />
<span className="text-xs text-gray-500 shrink-0">Type:</span>
<div className="relative">
<select
value={typeKey}
onChange={e => { setTypeKey(e.target.value); setActive('') }}
className="appearance-none bg-panel border border-border rounded-lg pl-2 pr-6 py-1 text-xs text-gray-200 cursor-pointer focus:outline-none focus:border-accent"
>
{CHORD_SUFFIX_OPTIONS.map(o => (
<option key={o.key} value={o.key}>{o.label}</option>
))}
</select>
<span className="pointer-events-none absolute right-1.5 top-1/2 -translate-y-1/2 text-gray-500 text-xs"></span>
</div>
<div className="ml-auto text-xl font-black text-accent">{chordName}</div>
</div>
{/* ── Sub-tabs ── */}
<div className="flex gap-1 bg-surface border border-border rounded-xl p-1 overflow-x-auto">
{[
{ key: 'guitar', label: '🎸 Guitar' },
{ key: 'piano', label: '🎹 Piano' },
].map(t => (
<button key={t.key}
onClick={() => setSubTab(t.key)}
className={`px-4 py-1.5 rounded-lg text-sm font-semibold transition-all whitespace-nowrap ${
subTab === t.key ? 'bg-accent text-white' : 'text-gray-400 hover:text-white'
}`}>
{t.label}
</button>
))}
</div>
{subTab === 'guitar' && <GuitarTab chordName={chordName} />}
{subTab === 'piano' && <PianoTab chordName={chordName} />}
</div>
)
}
// Main modal
export default function ChordDetailModal({ chord, onClose, onChordClick, keyInfo, chordHistory }) {
const [tab, setTab] = useState('guitar')
// Reset tab when chord changes
useEffect(() => { setTab('guitar') }, [chord])
// Close on Escape
useEffect(() => {
function onKey(e) { if (e.key === 'Escape') onClose() }
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose])
if (!chord) return null
const parsed = parseChord(chord)
const typeName = parsed ? (CHORD_SUFFIX_OPTIONS.find(o => o.key === parsed.type)?.label ?? parsed.type) : ''
return (
<div
className="fixed inset-0 z-50 flex items-start justify-center bg-black/70 backdrop-blur-sm p-4 overflow-y-auto"
onClick={e => { if (e.target === e.currentTarget) onClose() }}
>
<div className="w-full max-w-3xl bg-panel border border-border rounded-2xl shadow-2xl mt-8 mb-8">
{/* Header */}
<div className="flex items-center justify-between px-6 py-4 border-b border-border">
<div>
<h2 className="text-3xl font-black text-accent leading-none">{chord}</h2>
<p className="text-xs text-gray-500 mt-0.5">{typeName} chord · tap a voicing to study it</p>
</div>
<button
onClick={onClose}
className="p-2 text-gray-500 hover:text-white transition-colors text-xl leading-none"
aria-label="Close"
>
×
</button>
</div>
{/* Tab bar */}
<div className="flex gap-1 px-6 pt-4 overflow-x-auto">
{[
{ key: 'guitar', label: '🎸 Guitar' },
{ key: 'piano', label: '🎹 Piano' },
{ key: 'theory', label: '📚 Theory' },
{ key: 'learn', label: '🎓 Learn' },
{ key: 'progressions', label: '🎵 Progressions' },
{ key: 'explore', label: '🔍 Explore' },
].map(t => (
<button key={t.key}
onClick={() => setTab(t.key)}
className={`px-4 py-2 rounded-t-xl text-sm font-semibold transition-all border-b-2 whitespace-nowrap ${
tab === t.key
? 'text-accent border-accent bg-accent/10'
: 'text-gray-500 border-transparent hover:text-gray-300'
}`}>
{t.label}
</button>
))}
</div>
{/* Content */}
<div className="px-6 py-5">
{tab === 'guitar' && <GuitarTab chordName={chord} />}
{tab === 'piano' && <PianoTab chordName={chord} />}
{tab === 'theory' && <TheoryTab chordName={chord} />}
{tab === 'learn' && <LearnTab chordName={chord} />}
{tab === 'progressions' && <ProgressionsSubTab chordName={chord} onChordClick={c => { onChordClick?.(c) }} />}
{tab === 'explore' && <ExploreTab initialChord={chord} keyInfo={keyInfo} chordHistory={chordHistory} />}
</div>
</div>
</div>
)
}
+312
View File
@@ -0,0 +1,312 @@
// Compact SVG guitar chord-diagram. Renders the KB guitar shape format (D-01b).
// Secondary per-station voicing thumbnail in the Roadmap panel.
//
// Two shape forms (see src/data/kb/SCHEMA.md):
// movable: { rootStr, offsets, fingers }
// - offsets: 6 entries low-Ehigh-E, integers = fret offset from the barre
// (base) fret, 'x' = muted. The base fret is derived from where the chord
// root (rootPc) sits on rootStr in standard tuning.
// open: { frets, onlyRoot, fingers }
// - frets: 6 entries low-Ehigh-E, 0 = open, 'x' = muted, integers = absolute.
//
// Props:
// shape movable or open form above
// keyRoot tonic pitch class 011 (accepted; see note below)
// rootPc chord root pitch class 011 (drives movable placement)
// size 'thumb' (compact ~64px grid) | 'full' (enlarged + finger #s + label)
// label optional chord label shown under the grid
//
// Note on key-awareness: the SCHEMA derives the movable base fret from where the
// root note sits "for the current key". In practice the absolute fret depends only
// on the chord root pitch class on rootStr, which is supplied directly as `rootPc`.
// keyRoot is accepted for contract compatibility and used as a fallback for rootPc.
// Standard tuning open-string pitch classes, indexed low-E (0) high-E (5).
const OPEN_PCS = [4, 9, 2, 7, 11, 4] // E A D G B E
// We render strings topbottom as high-E first (matches Fretboard.jsx idiom),
// so display index 0 = high E, 5 = low E. Data arrays are low-E first, so the
// data index for display row `di` is `5 - di`.
const ACCENT = '#a855f7' // chord-tone tier (root highlight)
const DOT = '#e5e7eb' // non-root finger dots (light gray, AA on dark board)
const DOT_TEXT_DARK = '#1a1a1a'
const BOARD = '#1a120b' // matches Fretboard board fill
const FRET_LINE = '#4a3a2a'
const NUT_COL = '#c0b090'
const STRING_COL = '#9ca3af'
const MUTE_OPEN = '#9ca3af'
const FRET_LABEL = '#9ca3af'
const NUM_STRINGS = 6
const NUM_FRETS = 5 // visible fret rows in the grid
// Fret resolution
// Returns { frets: number|'x' per display row (high-E first), baseFret, rootRow }
// where baseFret is the absolute fret of the top visible grid line (1 = nut shown).
function resolveShape(shape, rootPc, keyRoot) {
if (!shape) return null
// Open shape: absolute frets, low-E first.
if (Array.isArray(shape.frets)) {
const abs = shape.frets // low-E first
const fretted = abs.filter(f => typeof f === 'number' && f > 0)
const minFret = fretted.length ? Math.min(...fretted) : 0
const maxFret = fretted.length ? Math.max(...fretted) : 0
// Show the nut (baseFret 1) when the shape reaches up to fret ~4 from the nut.
const baseFret = maxFret <= NUM_FRETS ? 1 : minFret
return {
open: true,
absLowE: abs,
baseFret,
rootPc: typeof shape.onlyRoot === 'number' ? shape.onlyRoot : rootPc,
}
}
// Movable shape: offsets relative to a base (barre) fret on rootStr.
if (Array.isArray(shape.offsets)) {
const rootStr = shape.rootStr // 6 = low E 1 = high E
const rootStrIdx = 6 - rootStr // low-E-first array index
const targetPc = typeof rootPc === 'number' ? rootPc
: typeof keyRoot === 'number' ? keyRoot : 0
const openPc = OPEN_PCS[rootStrIdx] ?? 4
// Smallest fret >= 1 where the root pc lands on rootStr.
let baseFret = ((targetPc - openPc) % 12 + 12) % 12
if (baseFret === 0) baseFret = 12 // root at open string use the octave barre
return {
open: false,
offsets: shape.offsets, // low-E first
baseFret,
rootStrIdx,
rootPc: targetPc,
}
}
return null
}
// Build per-display-row absolute fret + root flag from a resolved shape.
// Returns null if the shape cannot be placed gracefully (root above ~fret 12).
function buildRows(resolved) {
if (!resolved) return null
// Absolute fret per low-E-first data index.
let absLowE
if (resolved.open) {
absLowE = resolved.absLowE
} else {
absLowE = resolved.offsets.map(o =>
o === 'x' || o == null ? 'x' : resolved.baseFret + o
)
}
// Highest fretted note degrade if unplayably high.
const fretted = absLowE.filter(f => typeof f === 'number' && f > 0)
const maxFret = fretted.length ? Math.max(...fretted) : 0
if (maxFret > 15) return null
// Window: lowest visible fret of the grid.
// Show the nut if everything fits within NUM_FRETS of it; else start at the
// lowest fretted note so the grip sits at the top of the window.
const minFret = fretted.length ? Math.min(...fretted) : 0
const startFret = maxFret <= NUM_FRETS ? 1 : minFret
// Root pitch class for colouring.
const rootPc = resolved.rootPc
// Convert to display rows (high-E first reverse of low-E-first).
const rows = []
for (let di = 0; di < NUM_STRINGS; di++) {
const dataIdx = NUM_STRINGS - 1 - di
const f = absLowE[dataIdx]
const stringPc = (OPEN_PCS[dataIdx] + (typeof f === 'number' ? f : 0)) % 12
const isRoot = typeof f === 'number' && f >= 0 && stringPc === rootPc
rows.push({ fret: f, isRoot, stringPc })
}
return { rows, startFret, showNut: startFret === 1 }
}
export default function ChordDiagram({
shape,
keyRoot,
rootPc,
size = 'thumb',
label,
}) {
const resolved = resolveShape(shape, rootPc, keyRoot)
const built = buildRows(resolved)
const full = size === 'full'
// Geometry. thumb grid ~64px wide; full ~2x.
const scale = full ? 2 : 1
const cell = 11 * scale // px per fret row (vertical)
const sw = 11 * scale // px per string gap (horizontal)
const padL = 14 * scale // left pad (mute/open markers + start-fret label)
const padR = 6 * scale
const padT = 11 * scale // top pad (mute/open marker row)
const padB = (full ? 16 : 6) * scale // bottom pad (finger numbers / breathing room)
const gridW = (NUM_STRINGS - 1) * sw
const gridH = NUM_FRETS * cell
const svgW = padL + gridW + padR
const svgH = padT + gridH + padB
const stringX = si => padL + si * sw // si: 0 = high E (left) 5 = low E
const fretY = fi => padT + fi * cell // fi: 0 = top line NUM_FRETS
if (!built) {
// Graceful degradation: shape can't be placed.
return (
<div
className="inline-flex flex-col items-center justify-center bg-panel border border-border rounded-lg text-gray-500"
style={{ width: svgW, minHeight: svgH }}
role="img"
aria-label={label ? `${label}: voicing unavailable` : 'voicing unavailable'}
>
<span style={{ fontSize: 9 * scale }}></span>
{label && full && <span style={{ fontSize: 8 * scale }} className="mt-1">{label}</span>}
</div>
)
}
const { rows, startFret, showNut } = built
const fingers = shape?.fingers // low-E first, optional
const ariaLabel = label
? `${label} guitar chord diagram`
: 'guitar chord diagram'
return (
<div className="inline-flex flex-col items-center" role="img" aria-label={ariaLabel}>
<svg
width={svgW}
height={svgH}
viewBox={`0 0 ${svgW} ${svgH}`}
style={{ display: 'block' }}
>
{/* Board background */}
<rect
x={padL - 1}
y={padT - 1}
width={gridW + 2}
height={gridH + 2}
fill={BOARD}
rx={2 * scale}
/>
{/* Start-fret indicator ("5fr") when the grid begins above the nut */}
{!showNut && (
<text
x={padL - 4 * scale}
y={fretY(0) + cell * 0.62}
textAnchor="end"
fontSize={7 * scale}
fill={FRET_LABEL}
>
{startFret}fr
</text>
)}
{/* Frets (horizontal lines) */}
{Array.from({ length: NUM_FRETS + 1 }, (_, fi) => fi).map(fi => {
const topNut = showNut && fi === 0
return (
<line
key={fi}
x1={stringX(0)}
y1={fretY(fi)}
x2={stringX(NUM_STRINGS - 1)}
y2={fretY(fi)}
stroke={topNut ? NUT_COL : FRET_LINE}
strokeWidth={topNut ? 3 * scale : 1 * scale}
/>
)
})}
{/* Strings (vertical lines) */}
{rows.map((_, si) => (
<line
key={si}
x1={stringX(si)}
y1={fretY(0)}
x2={stringX(si)}
y2={fretY(NUM_FRETS)}
stroke={STRING_COL}
strokeWidth={(si >= 4 ? 1.4 : si >= 2 ? 1.1 : 0.8) * scale}
/>
))}
{/* Per-string markers: mute ✕ / open ○ above the nut, dots on the grid */}
{rows.map((row, si) => {
const x = stringX(si)
const dataIdx = NUM_STRINGS - 1 - si
const finger = fingers ? fingers[dataIdx] : 0
// Muted string above the board.
if (row.fret === 'x' || row.fret == null) {
const my = padT - 4 * scale
const r = 3 * scale
return (
<g key={si} stroke={MUTE_OPEN} strokeWidth={1 * scale} strokeLinecap="round">
<line x1={x - r} y1={my - r} x2={x + r} y2={my + r} />
<line x1={x - r} y1={my + r} x2={x + r} y2={my - r} />
</g>
)
}
// Open string (absolute fret 0, only meaningful when nut is shown) .
if (row.fret === 0) {
return (
<circle
key={si}
cx={x}
cy={padT - 4 * scale}
r={3 * scale}
fill="none"
stroke={MUTE_OPEN}
strokeWidth={1 * scale}
/>
)
}
// Fretted note dot, positioned in its fret row within the window.
const rowInWindow = row.fret - startFret // 0-based row from top
if (rowInWindow < 0 || rowInWindow >= NUM_FRETS) return null
const cy = fretY(rowInWindow) + cell / 2
const r = (full ? 4 : 3.5) * scale
const fill = row.isRoot ? ACCENT : DOT
const showFinger = full && finger > 0
return (
<g key={si}>
<circle cx={x} cy={cy} r={r} fill={fill} />
{showFinger && (
<text
x={x}
y={cy + 3 * scale}
textAnchor="middle"
fontSize={7 * scale}
fontWeight="700"
fill={row.isRoot ? '#fff' : DOT_TEXT_DARK}
>
{finger}
</text>
)}
</g>
)
})}
</svg>
{label && (
<span
className="text-gray-300 leading-none mt-1"
style={{ fontSize: full ? 12 : 9 }}
>
{label}
</span>
)}
</div>
)
}
+391
View File
@@ -0,0 +1,391 @@
// CircleOfFifths the Knowledge Center's live key map (task D-61).
//
// A read-only SVG circle of fifths for a jamming musician, not a textbook
// poster:
//
// · Outer ring: the 12 major keys, C at 12 o'clock, fifths clockwise.
// Each wedge carries its key-signature glyph ( / n / n).
// · Inner ring: the relative minors, aligned with their majors.
// · LIVE: the detected/locked key (keyInfo = App's effectiveKey, flowing
// through KnowledgeDock ExploreSection) lights its wedge in accent; its
// fifths neighbours (subdominant, dominant) and its relative get a soft
// accent tier the "safe keys to wander to" story with zero interaction.
// Modal keys pick their ring by the mode's third (dorian/phrygian the
// minor ring), derived from theory.js SCALES never re-derived here.
// · The highlighted key's diatonic chords (theory.js getChordsInKey) are
// listed beside the circle inline no hover, no click required.
// · OPTIONAL tap: any wedge previews that key's diatonics in the side panel
// (dashed outline marks the previewed wedge; the live highlight never
// moves). Tapping NEVER changes app key state this surface is read-only.
// · No key detected neutral circle with honest microcopy.
//
// Purely presentational: props in ({ keyInfo, onChordClick }), nothing out.
// Keyboard: every wedge is a focusable button (Enter/Space previews); focus
// draws an explicit accent-soft stroke (SVG-safe no reliance on box-shadow).
//
// Design tokens (tailwind.config.js) literal here because SVG paint
// attributes can't read Tailwind classes (MiniPiano/Fretboard precedent):
// accent #a855f7, surface #0f0f0f, panel #1a1a1a, border #2a2a2a. No new
// colours: #c084fc is MiniPiano's established soft accent; greys are the
// Tailwind gray-300/400 already used across the app's SVGs.
import { useMemo, useState } from 'react'
import { NOTES, SCALES, getChordsInKey, toRomanNumeral } from '../lib/theory'
import { parseChord } from '../lib/voicings'
// Token literals (SVG paint attrs; see header)
const ACCENT = '#a855f7' // bg-accent the live key wedge
const ACCENT_SOFT = '#c084fc' // MiniPiano's soft accent neighbour-tier text
const SURFACE = '#0f0f0f' // bg-surface wedge gaps + text on accent (AA 4.84:1)
const PANEL = '#1a1a1a' // bg-panel idle wedge fill
const BORDER = '#2a2a2a' // border-border centre hub stroke
const TEXT_MAIN = '#d1d5db' // gray-300 idle key names (11.4:1 on panel)
const TEXT_DIM = '#9ca3af' // gray-400 signature glyphs, microcopy (6.4:1)
// The circle, index 0 = 12 o'clock, fifths clockwise
// Display spelling is the conventional poster mix (flats on the flat side);
// all LOGIC runs on pitch classes so detection's sharp spellings match fine.
const MAJOR_LABELS = ['C','G','D','A','E','B','F♯','D♭','A♭','E♭','B♭','F']
const MINOR_LABELS = ['Am','Em','Bm','F♯m','C♯m','G♯m','E♭m','B♭m','Fm','Cm','Gm','Dm']
const SIG_GLYPHS = ['♮','1♯','2♯','3♯','4♯','5♯','6♯','5♭','4♭','3♭','2♭','1♭']
const majorPcAt = (i) => (i * 7) % 12 // wedge index major tonic pc
const minorPcAt = (i) => (i * 7 + 9) % 12 // wedge index relative minor pc
const majorIdxOf = (pc) => (pc * 7) % 12 // 7·7 1 (mod 12): self-inverse
const minorIdxOf = (pc) => majorIdxOf((pc + 3) % 12)
const sigWords = (i) =>
i === 0 ? 'no sharps or flats' : i <= 6 ? `${i} sharp${i > 1 ? 's' : ''}` : `${12 - i} flat${12 - i > 1 ? 's' : ''}`
// The MODE's parent major: the unique major scale whose pc-set equals the
// mode's pc-set ITS signature is the mode's true signature (A dorian =
// G major's notes = 1, not A major's 3, and not the tonic wedge's glyph).
// Uniqueness proof: the diatonic pc-set has no transpositional symmetry, so
// its 12 transpositions are 12 DISTINCT 7-note sets a given 7-note set can
// therefore equal AT MOST one of them. Every key-dropdown mode (major, minor,
// dorian, phrygian, lydian, mixolydian) is by definition a rotation of the
// diatonic set, so for all 6 modes × 12 roots exactly one parent major exists
// (existence: rotating the mode back to its parent). Non-heptatonic scales
// (pentatonics, blues) match none we return null and the hub omits the
// signature line rather than guessing.
function parentMajorPc(tonicPc, scale) {
const pcs = new Set(scale.map((s) => (tonicPc + s) % 12))
if (pcs.size !== 7) return null
const hits = []
for (let p = 0; p < 12; p++) {
if (SCALES.major.every((s) => pcs.has((p + s) % 12))) hits.push(p)
}
return hits.length === 1 ? hits[0] : null
}
// Geometry (viewBox 0 0 300 300, centre 150)
const CX = 150, CY = 150
const R_OUT = 142, R_MID = 96, R_IN = 58, R_HUB = 54
function pt(r, deg) {
const t = (deg * Math.PI) / 180 // 0° = 12 o'clock, clockwise
return `${(CX + r * Math.sin(t)).toFixed(2)},${(CY - r * Math.cos(t)).toFixed(2)}`
}
function wedgePath(i, r0, r1) {
const a0 = i * 30 - 15, a1 = i * 30 + 15
return `M ${pt(r1, a0)} A ${r1},${r1} 0 0 1 ${pt(r1, a1)} L ${pt(r0, a1)} A ${r0},${r0} 0 0 0 ${pt(r0, a0)} Z`
}
function labelXY(i, r) {
const t = (i * 30 * Math.PI) / 180
return { x: CX + r * Math.sin(t), y: CY - r * Math.cos(t) }
}
// Diatonic chord chips (inline the core, zero-click payload)
function ChordChips({ root, mode, onChordClick }) {
const chords = getChordsInKey(root, mode)
if (!chords.length) return null
return (
<div className="flex flex-wrap gap-1.5">
{chords.map((c) => {
const rn = toRomanNumeral(c, root, mode)
const inner = (
<>
<span>{c}</span>
{rn && rn !== '?' && (
<span className="text-[9px] font-normal opacity-60 leading-none mt-0.5">{rn}</span>
)}
</>
)
return onChordClick ? (
<button
key={c} type="button" onClick={() => onChordClick(c)}
title={`Open ${c} voicings`}
className="flex flex-col items-center px-2.5 py-1 rounded-lg border text-xs font-bold bg-panel border-border text-gray-300 transition-all outline-none hover:border-accent/50 hover:text-accent focus-visible:ring-2 focus-visible:ring-accent"
>
{inner}
</button>
) : (
<span key={c} className="flex flex-col items-center px-2.5 py-1 rounded-lg border text-xs font-bold bg-panel border-border text-gray-300">
{inner}
</span>
)
})}
</div>
)
}
// The component
export default function CircleOfFifths({ keyInfo, onChordClick }) {
const [preview, setPreview] = useState(null) // { ring, idx } | null local only
const [hot, setHot] = useState(null) // 'ring-idx' hovered/focused wedge
// Live key ring + wedge index. Ring by the MODE'S THIRD (SCALES, theory.js):
// minor/dorian/phrygian sit on the minor ring at their tonic A minor (or
// A dorian) lights the inner "Am" wedge, NOT outer C.
const live = useMemo(() => {
if (!keyInfo?.root) return null
const pc = parseChord(keyInfo.root)?.rootPc
if (pc == null) return null
const mode = keyInfo.mode ?? 'major'
const scale = SCALES[mode] ?? SCALES.major
// Minor third AND no major third a bare scale[2] === 3 check would
// misfile the hexatonic blues scale [0,3,5,6,7,10] (carries both colours)
// if it ever reached the key dropdown.
const minorish = scale.includes(3) && !scale.includes(4)
const parentPc = parentMajorPc(pc, scale)
return {
pc, mode,
ring: minorish ? 'minor' : 'major',
idx: minorish ? minorIdxOf(pc) : majorIdxOf(pc),
// circle position of the mode's PARENT MAJOR the true signature glyph
sigIdx: parentPc == null ? null : majorIdxOf(parentPc),
}
}, [keyInfo])
// Tier per wedge: 2 = the live key (accent), 1 = its safe neighbours
// (subdominant · dominant on the same ring, relative on the other), 0 = idle.
function tierOf(ring, idx) {
if (!live) return 0
if (live.ring === ring) {
if (idx === live.idx) return 2
if (idx === (live.idx + 1) % 12 || idx === (live.idx + 11) % 12) return 1
return 0
}
return idx === live.idx ? 1 : 0
}
const isLiveWedge = (ring, idx) => live && live.ring === ring && live.idx === idx
function tapWedge(ring, idx) {
if (isLiveWedge(ring, idx)) { setPreview(null); return } // tapping home = back to live
setPreview((p) => (p && p.ring === ring && p.idx === idx ? null : { ring, idx }))
}
// Build both rings' wedges; paint order = idle neighbours live preview
// hot, so highlight strokes always win the shared edges.
const wedges = []
for (const ring of ['major', 'minor']) {
const outer = ring === 'major'
for (let idx = 0; idx < 12; idx++) {
const tier = tierOf(ring, idx)
const previewed = preview && preview.ring === ring && preview.idx === idx
const id = `${ring}-${idx}`
const name = outer ? MAJOR_LABELS[idx] : MINOR_LABELS[idx]
const aria = outer
? `${name} major, ${sigWords(idx)}${tier === 2 ? ' — the live key' : ''}. Preview its chords.`
: `${MINOR_LABELS[idx].replace(/m$/, '')} minor, relative of ${MAJOR_LABELS[idx]} major${tier === 2 ? ' — the live key' : ''}. Preview its chords.`
wedges.push({
ring, idx, id, tier, previewed, outer, aria,
z: hot === id ? 5 : previewed ? 4 : tier + 1,
})
}
}
wedges.sort((a, b) => a.z - b.z)
// Side panel: the previewed key wins the panel; the LIVE view stays complete
// without any tap (live highlight + its chords render by default).
// Preview title is spelled SHARP-side from NOTES, matching its chips:
// getChordsInKey emits the app-wide sharp spelling (theory.js noteName), and
// those names flow into onChordClick ChordDetailModal, so re-spelling the
// chips flat would add a divergent naming layer in front of the modal. One
// spelling authority (NOTES) for title + chips + modal; the WEDGE keeps its
// poster label (E) for at-a-glance reading.
let shown = null
if (preview) {
const root = NOTES[preview.ring === 'major' ? majorPcAt(preview.idx) : minorPcAt(preview.idx)]
const mode = preview.ring === 'major' ? 'major' : 'minor'
shown = { root, mode, title: `${root} ${mode}`, isPreview: true }
} else if (live) {
shown = { root: keyInfo.root, mode: live.mode, title: `${keyInfo.root} ${live.mode}`, isPreview: false }
}
// Neighbour names for the live key (the tier-1 wedges, spelled out).
const neighbours = live && {
sub: (live.ring === 'major' ? MAJOR_LABELS : MINOR_LABELS)[(live.idx + 11) % 12],
dom: (live.ring === 'major' ? MAJOR_LABELS : MINOR_LABELS)[(live.idx + 1) % 12],
rel: (live.ring === 'major' ? MINOR_LABELS : MAJOR_LABELS)[live.idx],
relWord: live.ring === 'major' ? 'relative minor' : 'relative major',
}
return (
<section
aria-label="Circle of fifths"
className="p-3 bg-surface border border-border rounded-xl flex flex-wrap gap-x-5 gap-y-3 items-start"
>
{/* ── The circle ── */}
<svg
viewBox="0 0 300 300"
role="group"
aria-label={live
? `Circle of fifths, live key ${keyInfo.root} ${live.mode}`
: 'Circle of fifths, no key detected yet'}
className="w-[248px] max-w-full h-auto shrink-0 mx-auto select-none"
>
{/* wedges (paint-ordered) */}
{wedges.map((w) => {
const [r0, r1] = w.outer ? [R_MID, R_OUT] : [R_IN, R_MID]
const stroke = hot === w.id ? ACCENT_SOFT : w.previewed ? ACCENT : SURFACE
return (
<path
key={w.id}
d={wedgePath(w.idx, r0, r1)}
fill={w.tier === 0 ? PANEL : ACCENT}
fillOpacity={w.tier === 1 ? 0.22 : 1}
stroke={stroke}
strokeWidth={hot === w.id || w.previewed ? 2 : 1.25}
strokeDasharray={w.previewed && hot !== w.id ? '4 3' : undefined}
role="button"
tabIndex={0}
aria-label={w.aria}
aria-pressed={!!w.previewed}
className="cursor-pointer outline-none"
onClick={() => tapWedge(w.ring, w.idx)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); tapWedge(w.ring, w.idx) }
}}
onPointerEnter={() => setHot(w.id)}
onPointerLeave={() => setHot((h) => (h === w.id ? null : h))}
onFocus={() => setHot(w.id)}
onBlur={() => setHot((h) => (h === w.id ? null : h))}
/>
)
})}
{/* labels (own layer, never swallow clicks) */}
{Array.from({ length: 12 }, (_, i) => {
const tMaj = tierOf('major', i), tMin = tierOf('minor', i)
const name = labelXY(i, 123)
const glyph = labelXY(i, 106)
const minor = labelXY(i, 77)
return (
<g key={i} pointerEvents="none">
<text x={name.x} y={name.y} textAnchor="middle" dominantBaseline="middle"
fontSize="13" fontWeight="700"
fill={tMaj === 2 ? SURFACE : tMaj === 1 ? ACCENT_SOFT : TEXT_MAIN}>
{MAJOR_LABELS[i]}
</text>
<text x={glyph.x} y={glyph.y} textAnchor="middle" dominantBaseline="middle"
fontSize="8.5"
fill={tMaj === 2 ? SURFACE : tMaj === 1 ? ACCENT_SOFT : TEXT_DIM}>
{SIG_GLYPHS[i]}
</text>
<text x={minor.x} y={minor.y} textAnchor="middle" dominantBaseline="middle"
fontSize="11" fontWeight={tMin === 2 ? '700' : '600'}
fill={tMin === 2 ? SURFACE : tMin === 1 ? ACCENT_SOFT : TEXT_DIM}>
{MINOR_LABELS[i]}
</text>
</g>
)
})}
{/* centre hub — always the LIVE state (the glance anchor) */}
<circle cx={CX} cy={CY} r={R_HUB} fill={SURFACE} stroke={BORDER} strokeWidth="1" />
{live ? (
<g pointerEvents="none">
<text x={CX} y={CY - 10} textAnchor="middle" fontSize="14" fontWeight="800" fill={ACCENT}>
{keyInfo.root} {live.mode}
</text>
{/* The MODE's signature (parent major), not the wedge's A dorian
reads "1♯ · G major's notes", matching the F in its chips. */}
{live.sigIdx != null && (
<text x={CX} y={CY + 6} textAnchor="middle" fontSize="8.5" fill={TEXT_DIM}>
{SIG_GLYPHS[live.sigIdx]} · {live.mode === 'major'
? sigWords(live.sigIdx)
: `${MAJOR_LABELS[live.sigIdx]} major's notes`}
</text>
)}
<text x={CX} y={CY + 21} textAnchor="middle" fontSize="8" fontWeight="700"
letterSpacing="1.5" fill={ACCENT_SOFT}>
LIVE
</text>
</g>
) : (
<g pointerEvents="none">
<text x={CX} y={CY - 8} textAnchor="middle" fontSize="11" fontWeight="700" fill={TEXT_MAIN}>
No key yet
</text>
<text x={CX} y={CY + 7} textAnchor="middle" fontSize="8.5" fill={TEXT_DIM}>
play a few chords
</text>
<text x={CX} y={CY + 18} textAnchor="middle" fontSize="8.5" fill={TEXT_DIM}>
the circle lights up
</text>
</g>
)}
</svg>
{/* ── Beside the circle: the highlighted key's diatonics, inline ── */}
<div className="flex-1 min-w-[220px] flex flex-col gap-2.5">
<h4 className="text-[10px] font-semibold uppercase tracking-widest text-gray-500">
Circle of fifths
</h4>
{shown ? (
<>
<div className="flex items-center flex-wrap gap-2">
<span className="font-bold text-white text-sm">{shown.title}</span>
{shown.isPreview ? (
<>
<span className="text-[9px] uppercase tracking-wide font-semibold text-amber border border-amber/40 rounded px-1.5 py-px">
preview
</span>
<button
type="button"
onClick={() => setPreview(null)}
className="text-[11px] text-accent underline underline-offset-2 outline-none hover:text-white focus-visible:ring-2 focus-visible:ring-accent rounded"
>
back to live
</button>
</>
) : (
<span className="text-[9px] uppercase tracking-wide font-semibold text-accent border border-accent/40 rounded px-1.5 py-px">
live
</span>
)}
</div>
<ChordChips root={shown.root} mode={shown.mode} onChordClick={onChordClick} />
{!shown.isPreview && neighbours && (
<p className="text-[11px] text-gray-400">
Safe keys to wander to:{' '}
<span className="text-accent font-semibold">{neighbours.sub}</span> (subdominant) ·{' '}
<span className="text-accent font-semibold">{neighbours.dom}</span> (dominant) ·{' '}
<span className="text-accent font-semibold">{neighbours.rel}</span> ({neighbours.relWord})
</p>
)}
</>
) : (
<p className="text-sm text-gray-400">
When a key is detected (or locked), its wedge lights up here with the chords that
live in it. Tap any wedge to peek at another key meanwhile.
</p>
)}
<p className="text-xs text-gray-400 leading-snug">
Keys next to each other on the circle share six of their seven notes, so sliding one
step clockwise to the dominant, counter-clockwise to the subdominant barely moves
the ground under the band. The inner ring is each key&apos;s relative minor: the same
notes with a darker home base. The further apart two keys sit, the bolder the jump sounds.
</p>
</div>
</section>
)
}
+367
View File
@@ -0,0 +1,367 @@
import { useState } from 'react'
import ChordBox from './ChordBox'
import RiffDiagram from './RiffDiagram'
import { getGuitarVoicings, parseChord } from '../lib/voicings'
import { CHORD_TYPES, NOTES, toRomanNumeral } from '../lib/theory'
import { findSimilarProgressions, progressionInKey } from '../lib/education'
// Scale ideas per mode
const SCALE_IDEAS = {
major: [
{ name: 'Major Pentatonic', intervals: '12356', scaleIntervals: [0,2,4,7,9], desc: 'Safe and bright. Everything you play will land. Start on the root, end on the root.' },
{ name: 'Mixolydian', intervals: '123456–♭7', scaleIntervals: [0,2,4,5,7,9,10], desc: 'Major with a bluesy ♭7. The defining sound of classic rock — Sweet Home Alabama lives here.' },
{ name: 'Lydian', intervals: '123–♯4567', scaleIntervals: [0,2,4,6,7,9,11], desc: 'Dreamy and floating. The ♯4 is the magic note — use it on long sustained notes for instant wonder.' },
],
minor: [
{ name: 'Minor Pentatonic', intervals: '1–♭345–♭7', scaleIntervals: [0,3,5,7,10], desc: 'The blues box. Bends on ♭3 and slides to 5 are gold. Start here every time.' },
{ name: 'Natural Minor', intervals: '12–♭345–♭6–♭7', scaleIntervals: [0,2,3,5,7,8,10], desc: 'Full Aeolian scale. Melodic and dark. The ♭6 gives it a cinematic quality.' },
{ name: 'Dorian', intervals: '12–♭3456–♭7', scaleIntervals: [0,2,3,5,7,9,10], desc: "Minor with a raised 6th — smooth and soulful. Santana's go-to. That major 6th is everything." },
],
dorian: [
{ name: 'Dorian Mode', intervals: '12–♭3456–♭7', scaleIntervals: [0,2,3,5,7,9,10], desc: "The raised 6th over minor is the colour. Mix freely with minor pentatonic and touch that 6th note." },
{ name: 'Minor Pentatonic', intervals: '1–♭345–♭7', scaleIntervals: [0,3,5,7,10], desc: 'Safe backbone in Dorian. You can ignore the 6th — or highlight it for that Dorian sparkle.' },
{ name: 'Blues Scale', intervals: '1–♭34–♭55–♭7', scaleIntervals: [0,3,5,6,7,10], desc: 'Add the ♭5 passing tone through the 5 — that slide is the essence of blues expression.' },
],
mixolydian: [
{ name: 'Mixolydian Mode', intervals: '123456–♭7', scaleIntervals: [0,2,4,5,7,9,10], desc: 'The ♭7 is your signature note. Hit it and slide down — instant swagger.' },
{ name: 'Major Pentatonic', intervals: '12356', scaleIntervals: [0,2,4,7,9], desc: 'Works beautifully over the I chord. Clean and reliable when you need to land safely.' },
{ name: 'Blues Scale', intervals: '1–♭3345–♭7', scaleIntervals: [0,3,4,5,7,10], desc: 'The hybrid blues scale. Bend the ♭3 up to the 3 — that tension and release is everything.' },
],
phrygian: [
{ name: 'Phrygian Mode', intervals: '1–♭2–♭345–♭6–♭7', scaleIntervals: [0,1,3,5,7,8,10], desc: 'That ♭2 is the spine-chilling note. Lean on it. Spanish fire and metal darkness in one scale.' },
{ name: 'Phrygian Dominant',intervals: '1–♭2345–♭6–♭7', scaleIntervals: [0,1,4,5,7,8,10], desc: 'Raise the ♭3 to a major 3rd. Flamenco and Middle-Eastern intensity. Dramatic every time.' },
{ name: 'Minor Pentatonic', intervals: '1–♭345–♭7', scaleIntervals: [0,3,5,7,10], desc: 'Avoid the ♭2 and play safe pentatonic runs — then hit the ♭2 as a surprise.' },
],
lydian: [
{ name: 'Lydian Mode', intervals: '123–♯4567', scaleIntervals: [0,2,4,6,7,9,11], desc: 'Float on the ♯4. John Williams writes entire film scores in Lydian. Sustain everything.' },
{ name: 'Major Pentatonic', intervals: '12356', scaleIntervals: [0,2,4,7,9], desc: 'The reliable base. Use Lydian mode sparingly on top for colour.' },
{ name: 'Lydian Dominant', intervals: '123–♯456–♭7', scaleIntervals: [0,2,4,6,7,9,10], desc: 'Lydian with a ♭7 — the jazz/fusion ♯4 chord sound. Herbie Hancock territory.' },
],
}
// Fallback
const SCALE_FALLBACK = SCALE_IDEAS.major
// Style variations for a progression
const STYLE_VARIATIONS = [
{
key: 'open',
label: 'Open & Spacious',
desc: 'Sus2 and add9 voicings — airy, gentle. Great for quiet intros and ambient sections.',
typeMap: { maj: 'sus2', min: 'sus2', dom7: 'sus4', maj7: 'add9', min7: 'sus2', add9: 'sus2', sus4: 'sus4', sus2: 'sus2', dim: 'dim', aug: 'aug', half_dim: 'half_dim', maj6: 'sus2', min6: 'sus2' },
color: 'text-blue-400',
border: 'border-blue-900/40',
},
{
key: 'jazz',
label: 'Jazz Upgrade',
desc: 'Triads → 7ths — instant sophistication. Works at any tempo, in any band context.',
typeMap: { maj: 'maj7', min: 'min7', dom7: 'dom7', add9: 'maj7', sus2: 'sus2', sus4: 'sus4', dim: 'dim7', aug: 'aug', half_dim: 'half_dim', maj6: 'maj6', min6: 'min6' },
color: 'text-amber-400',
border: 'border-amber-900/40',
},
{
key: 'blues',
label: 'Blues Stomp',
desc: 'Everything → dom7. Gritty, raw, powerful. All three chords want to slide and bend.',
typeMap: { maj: 'dom7', min: 'dom7', maj7: 'dom7', min7: 'dom7', add9: 'dom7', sus2: 'dom7', sus4: 'dom7', dim: 'dim7', aug: 'aug', half_dim: 'dom7', maj6: 'dom7', min6: 'dom7' },
color: 'text-red-400',
border: 'border-red-900/40',
},
{
key: 'modern',
label: 'Neo-Soul / Modern',
desc: "Add9 on majors, m7 on minors. D'Angelo, Thundercat, Childish Gambino territory.",
typeMap: { maj: 'add9', min: 'min7', dom7: 'dom7', maj7: 'add9', min7: 'min7', add9: 'add9', sus2: 'sus2', sus4: 'sus4', dim: 'dim', aug: 'aug', half_dim: 'half_dim', maj6: 'add9', min6: 'min7' },
color: 'text-purple-400',
border: 'border-purple-900/40',
},
]
// Transform a chord via a type map
function transformChord(chordStr, typeMap) {
const p = parseChord(chordStr)
if (!p) return chordStr
const newType = typeMap[p.type] ?? p.type
return NOTES[p.rootPc] + (CHORD_TYPES[newType]?.suffix ?? '')
}
// Get best voicings for a chord prefer open shapes, then low-fret barre
function getBestVoicings(chordStr, max = 4) {
const all = getGuitarVoicings(chordStr)
// Sort: open shapes first (label contains "Open"), then barre
const open = all.filter(v => v.label.includes('Open'))
const barre = all.filter(v => !v.label.includes('Open'))
return [...open, ...barre].slice(0, max)
}
// Per-chord voicing strip
function ChordStrip({ chordStr, keyInfo, onChordClick }) {
const voicings = getBestVoicings(chordStr, 4)
const rn = keyInfo?.root ? toRomanNumeral(chordStr, keyInfo.root, keyInfo.mode) : ''
return (
<div className="flex flex-col gap-2 p-3 bg-surface border border-border rounded-xl">
<div className="flex items-center gap-2">
<button onClick={() => onChordClick?.(chordStr)}
className="px-3 py-1 bg-accent/10 border border-accent/40 rounded-lg font-black text-lg text-accent hover:bg-accent/20 transition-colors">
{chordStr}
</button>
{rn && <span className="text-amber-400 text-sm font-semibold">{rn}</span>}
<span className="text-[11px] text-gray-600 ml-auto">click for all voicings</span>
</div>
{voicings.length > 0 ? (
<div className="flex flex-wrap gap-3">
{voicings.map((v, i) => (
<div key={i} className="flex flex-col items-center">
<ChordBox frets={v.frets} fingers={v.fingers} barre={v.barre} baseFret={v.baseFret} />
<p className="text-[10px] text-gray-600 text-center mt-1 max-w-[100px]">{v.label}</p>
</div>
))}
</div>
) : (
<p className="text-gray-600 text-xs">No voicings available.</p>
)}
</div>
)
}
// Style variation section
function StyleSection({ progression, onChordClick }) {
const [expanded, setExpanded] = useState(null)
return (
<div className="flex flex-col gap-2">
{STYLE_VARIATIONS.map(style => {
const isOpen = expanded === style.key
const transformed = progression.map(c => transformChord(c, style.typeMap))
return (
<div key={style.key} className={`border rounded-xl overflow-hidden transition-colors ${style.border} hover:border-opacity-70`}>
<button onClick={() => setExpanded(isOpen ? null : style.key)}
className="w-full flex items-center justify-between px-4 py-3 text-left">
<div className="flex flex-col gap-0.5">
<div className="flex items-center gap-2">
<span className={`font-bold text-sm ${style.color}`}>{style.label}</span>
<div className="flex gap-1">
{transformed.map((c, i) => (
<span key={i} className="text-xs font-bold text-gray-300">{c}{i < transformed.length - 1 ? ' →' : ''}</span>
))}
</div>
</div>
<span className="text-[11px] text-gray-500">{style.desc}</span>
</div>
<span className="text-gray-600 shrink-0 ml-3">{isOpen ? '▲' : '▼'}</span>
</button>
{isOpen && (
<div className="border-t border-border/50 px-4 py-4">
<div className="flex flex-wrap gap-4">
{transformed.map((c, i) => {
const voicings = getBestVoicings(c, 2)
return (
<div key={i} className="flex flex-col items-center gap-2">
<button onClick={() => onChordClick?.(c)}
className="px-2 py-0.5 bg-panel border border-border hover:border-accent/50 rounded-lg font-bold text-sm text-gray-200 hover:text-accent transition-all">
{c}
</button>
<div className="flex gap-2">
{voicings.map((v, vi) => (
<div key={vi} className="flex flex-col items-center">
<ChordBox frets={v.frets} fingers={v.fingers} barre={v.barre} baseFret={v.baseFret} />
<p className="text-[9px] text-gray-700 text-center mt-0.5 max-w-[90px]">{v.label}</p>
</div>
))}
</div>
</div>
)
})}
</div>
</div>
)}
</div>
)
})}
</div>
)
}
// Similar famous progressions
function SimilarSection({ progression, keyInfo, onChordClick }) {
const similar = findSimilarProgressions(progression, keyInfo)
if (!similar.length) return (
<p className="text-gray-600 text-sm text-center py-3">Play more and lock a key similar progressions will appear here.</p>
)
return (
<div className="flex flex-col gap-2">
{similar.slice(0, 3).map(prog => {
const chordsHere = keyInfo?.root ? progressionInKey(prog, keyInfo.root) : []
return (
<div key={prog.id} className="p-3 bg-surface border border-border rounded-xl">
<div className="flex items-center flex-wrap gap-2 mb-2">
<span className="font-bold text-white text-sm">{prog.name}</span>
<span className="text-[10px] font-mono text-gray-600">{prog.pattern}</span>
<span className="text-xs text-gray-600 ml-auto">{Math.round(prog.score * 100)}% match</span>
</div>
{chordsHere.length > 0 && (
<div className="flex flex-wrap gap-1.5 items-center mb-2">
{chordsHere.map((c, i) => (
<span key={i} className="flex items-center gap-1">
<button onClick={() => onChordClick?.(c)}
className={`px-2 py-0.5 rounded-lg font-bold text-xs border transition-all ${
i === 0 ? 'bg-accent border-accent text-white' : 'bg-panel border-border text-gray-300 hover:border-accent/50 hover:text-accent'
}`}>
{c}
</button>
{i < chordsHere.length - 1 && <span className="text-gray-700 text-xs"></span>}
</span>
))}
<span className="text-[10px] text-gray-600 ml-1">in {keyInfo?.root} {keyInfo?.mode}</span>
</div>
)}
<p className="text-[11px] text-gray-600">{prog.songs.slice(0, 3).join(' · ')}</p>
</div>
)
})}
</div>
)
}
// Main panel
export default function CurrentJamPanel({ keyInfo, chordHistory, detectedProgression, onChordClick }) {
const [open, setOpen] = useState(false)
const [view, setView] = useState('voicings') // voicings | scales | styles | similar
const { root, mode } = keyInfo ?? {}
// Working progression: detected loop or last 4 unique chords
const workingProgression = detectedProgression?.length
? detectedProgression
: [...new Set([...chordHistory].reverse())].reverse().slice(-4)
const scaleIdeas = SCALE_IDEAS[mode] ?? SCALE_FALLBACK
const rootPc = root ? NOTES.indexOf(root) : null
const hasSession = workingProgression.length > 0
return (
<div className="mb-3 bg-panel border border-border rounded-xl overflow-hidden">
<button onClick={() => setOpen(v => !v)}
className="w-full flex items-center justify-between px-4 py-2 text-sm text-gray-400 hover:text-gray-200 transition-all">
<div className="flex items-center gap-3">
<span>CURRENT JAM</span>
{root && (
<span className="text-[10px] px-2 py-0.5 bg-accent/10 border border-accent/30 rounded text-accent">
{root} {mode} {detectedProgression?.length ? `· ${workingProgression.join(' → ')}` : ''}
</span>
)}
</div>
<span>{open ? '▲' : '▼'}</span>
</button>
{open && (
<div className="border-t border-border p-4 flex flex-col gap-4">
{!hasSession ? (
<p className="text-gray-600 text-sm text-center py-6">Start listening and play some chords your jam will appear here.</p>
) : (
<>
{/* ── Progression summary ── */}
<div className="flex flex-wrap items-center gap-2 px-3 py-2 bg-surface border border-border rounded-xl">
{root ? (
<span className="text-accent font-bold text-sm">{root} {mode}</span>
) : (
<span className="text-gray-600 text-sm">Key detecting</span>
)}
{workingProgression.length > 0 && (
<>
<span className="text-gray-700">·</span>
{workingProgression.map((c, i) => (
<span key={i} className="flex items-center gap-1">
<span className="text-gray-300 font-bold text-sm">{c}</span>
{root && <span className="text-amber-400/60 text-[10px]">{toRomanNumeral(c, root, mode)}</span>}
{i < workingProgression.length - 1 && <span className="text-gray-700"></span>}
</span>
))}
</>
)}
</div>
{/* ── View tabs ── */}
<div className="flex gap-1 bg-surface border border-border rounded-xl p-1 overflow-x-auto">
{[
{ key: 'voicings', label: '🎸 Open Voicings' },
{ key: 'scales', label: '🎵 Scales to Solo' },
{ key: 'styles', label: '🎨 Style Options' },
{ key: 'similar', label: '🔗 Similar Progressions' },
].map(t => (
<button key={t.key} onClick={() => setView(t.key)}
className={`px-3 py-1.5 rounded-lg text-xs font-semibold transition-all whitespace-nowrap ${
view === t.key ? 'bg-accent text-white' : 'text-gray-400 hover:text-white'
}`}>
{t.label}
</button>
))}
</div>
{/* ── Voicings: per chord open shapes ── */}
{view === 'voicings' && (
<div className="flex flex-col gap-3">
<p className="text-xs text-gray-500">
Best open and barre voicings for each chord in your jam. Click a chord name to see all its voicings.
</p>
{workingProgression.map(chord => (
<ChordStrip key={chord} chordStr={chord} keyInfo={keyInfo} onChordClick={onChordClick} />
))}
</div>
)}
{/* ── Scales ── */}
{view === 'scales' && (
<div className="flex flex-col gap-3">
<p className="text-xs text-gray-500">
Scales and modes that fit {root ? `${root} ${mode}` : 'your current key'}.
Start with the pentatonic add the extra notes once you feel comfortable.
</p>
{scaleIdeas.map(idea => (
<div key={idea.name} className="p-3 bg-surface border border-border rounded-xl">
<div className="flex items-center gap-3 mb-2">
<span className="font-bold text-white text-sm">{idea.name}</span>
<span className="font-mono text-xs text-accent">{idea.intervals}</span>
</div>
{rootPc !== null && idea.scaleIntervals && (
<div className="mb-2 overflow-x-auto">
<RiffDiagram rootPc={rootPc} scaleIntervals={idea.scaleIntervals} />
<p className="text-[10px] text-gray-600 mt-1">
Purple = root · Grey = scale tone · Fret numbers above
</p>
</div>
)}
<p className="text-xs text-gray-400 leading-snug">{idea.desc}</p>
</div>
))}
<p className="text-[11px] text-gray-700 text-center">
Pro tip: always resolve to a chord tone at the end of a phrase 7 leading to root, or 3rd landing on the 1.
</p>
</div>
)}
{/* ── Style options ── */}
{view === 'styles' && (
<div className="flex flex-col gap-2">
<p className="text-xs text-gray-500">
Your progression re-voiced four ways. Expand any style to see the chord boxes.
</p>
<StyleSection progression={workingProgression} onChordClick={onChordClick} />
</div>
)}
{/* ── Similar progressions ── */}
{view === 'similar' && (
<SimilarSection progression={workingProgression} keyInfo={keyInfo} onChordClick={onChordClick} />
)}
</>
)}
</div>
)}
</div>
)
}
+646
View File
@@ -0,0 +1,646 @@
import { useRef } from 'react'
import { getScale, getChordTones, NOTES } from '../lib/theory'
// SVG Piano 2 octaves (C3B4)
const KEY_W = 30
const KEY_H = 80
const BLACK_W = 18
const BLACK_H = 50
const PIANO_W = 14 * KEY_W
const WHITE_OCT = [0, 2, 4, 5, 7, 9, 11] // pitch classes per octave
const BLACK_OCT = [
{ pc: 1, wi: 0 }, { pc: 3, wi: 1 }, { pc: 6, wi: 3 },
{ pc: 8, wi: 4 }, { pc: 10, wi: 5 },
]
const WHITE_LABELS = ['C3','D3','E3','F3','G3','A3','B3','C4','D4','E4','F4','G4','A4','B4']
function PianoSVG({ values, keyNotes, chordNotes, keyH = KEY_H, showPct = false, monoColor = false }) {
const max = Math.max(...values, 0.01)
const wKeys = []
const bKeys = []
for (let oct = 0; oct < 2; oct++) {
WHITE_OCT.forEach((pc, wi) => wKeys.push({ pc, wi: oct * 7 + wi }))
BLACK_OCT.forEach(({ pc, wi }) => bKeys.push({ pc, wi: oct * 7 + wi }))
}
const svgH = keyH + 6 + (showPct ? 16 : 0)
return (
<svg viewBox={`0 0 ${PIANO_W} ${svgH}`} width="100%" style={{ display: 'block' }}>
{/* White keys */}
{wKeys.map(({ pc, wi }) => {
const energy = values[pc] / max
const inChord = chordNotes?.has(pc)
const inKey = keyNotes?.has(pc)
const x = wi * KEY_W
const fillColor = inChord
? `rgba(167,139,250,${0.12 + energy * 0.88})`
: inKey
? monoColor ? `rgba(192,132,252,${0.1 + energy * 0.7})` : `rgba(251,191,36,${0.1 + energy * 0.7})`
: `rgba(180,180,190,${0.05 + energy * 0.2})`
const pct = showPct ? Math.round(values[pc] * 100) : 0
return (
<g key={`w${wi}`}>
<rect x={x+1} y={3} width={KEY_W-2} height={keyH}
rx={3} fill="rgb(20,20,26)" stroke="rgba(255,255,255,0.08)" strokeWidth={1} />
{energy > (inChord || inKey ? 0.12 : 0.35) && (
<rect
x={x+1} y={3 + keyH * (1 - Math.min(energy, 1) * 0.85)}
width={KEY_W-2} height={keyH * Math.min(energy, 1) * 0.85}
rx={2} fill={fillColor} />
)}
<text x={x + KEY_W/2} y={keyH - 4} textAnchor="middle" fontSize={8}
fill={inKey || inChord ? 'rgba(200,200,210,0.9)' : 'rgba(90,90,100,0.8)'}>
{WHITE_LABELS[wi]}
</text>
{showPct && pct > 0 && (
<text x={x + KEY_W/2} y={keyH + 14} textAnchor="middle" fontSize={8}
fill={inKey ? (monoColor ? 'rgb(192,132,252)' : 'rgb(251,191,36)') : 'rgba(100,100,110,0.8)'}>
{pct}%
</text>
)}
</g>
)
})}
{/* Black keys */}
{bKeys.map(({ pc, wi }, i) => {
const energy = values[pc] / max
const inChord = chordNotes?.has(pc)
const inKey = keyNotes?.has(pc)
const x = wi * KEY_W + KEY_W - BLACK_W / 2
const fillColor = inChord
? 'rgba(139,92,246,0.9)'
: inKey
? monoColor ? 'rgba(192,132,252,0.85)' : 'rgba(180,130,0,0.85)'
: 'rgba(70,70,80,0.75)'
const pct = showPct ? Math.round(values[pc] * 100) : 0
return (
<g key={`b${i}`}>
{/* Base */}
<rect x={x} y={3} width={BLACK_W} height={BLACK_H}
rx={2} fill="rgb(14,14,18)" stroke="rgba(255,255,255,0.06)" strokeWidth={1} />
{/* Partial fill from bottom — same mechanic as white keys */}
{energy > (inChord || inKey ? 0.05 : 0.35) && (
<rect
x={x} y={3 + BLACK_H * (1 - Math.min(energy, 1) * 0.9)}
width={BLACK_W} height={BLACK_H * Math.min(energy, 1) * 0.9}
rx={1} fill={fillColor} />
)}
{/* % label near top of key (inside) */}
{showPct && pct > 0 && (
<text x={x + BLACK_W/2} y={3 + 10} textAnchor="middle" fontSize={7}
fill={inKey || inChord ? 'rgba(220,220,230,0.9)' : 'rgba(110,110,120,0.7)'}>
{pct}%
</text>
)}
{/* Note name near bottom of key */}
<text x={x + BLACK_W/2} y={3 + BLACK_H - 5} textAnchor="middle" fontSize={7}
fill={inKey || inChord ? 'rgba(210,210,220,0.85)' : 'rgba(110,110,120,0.6)'}>
{NOTES[pc]}
</text>
</g>
)
})}
</svg>
)
}
// Mini fretboard guitar mode chroma view
const STRINGS = [
{ label: 'e', root: 4 },
{ label: 'B', root: 11 },
{ label: 'G', root: 7 },
{ label: 'D', root: 2 },
{ label: 'A', root: 9 },
{ label: 'E', root: 4 },
]
const MF_NUT_X = 22
const MF_OPEN_X = 10
const MF_FRET_W = 28
const MF_STR_H = 16
const MF_PAD_T = 16
const MF_PAD_B = 8
const MF_FRETS = 13 // frets 012
const MF_DOT_R = 6
const MF_W = MF_NUT_X + (MF_FRETS - 1) * MF_FRET_W + 10
const MF_H = MF_PAD_T + 5 * MF_STR_H + MF_PAD_B
const mfFretX = f => MF_NUT_X + (f - 0.5) * MF_FRET_W
const mfStringY = si => MF_PAD_T + si * MF_STR_H
function MiniFretboard({ values, keyNotes, chordNotes, monoColor = false }) {
const max = Math.max(...values, 0.01)
return (
<svg viewBox={`0 0 ${MF_W} ${MF_H}`} width="100%" style={{ display: 'block' }}>
{/* Board background */}
<rect x={MF_NUT_X} y={MF_PAD_T - 5}
width={MF_W - MF_NUT_X - 6} height={5 * MF_STR_H + 10}
fill="#1a120b" rx={2} />
{/* Fret position dots */}
{[3, 5, 7, 9].map(f => (
<circle key={f} cx={mfFretX(f)} cy={MF_PAD_T + 2.5 * MF_STR_H} r={3} fill="#3a2a1a" />
))}
<circle cx={mfFretX(12)} cy={MF_PAD_T + 1.5 * MF_STR_H} r={3} fill="#3a2a1a" />
<circle cx={mfFretX(12)} cy={MF_PAD_T + 3.5 * MF_STR_H} r={3} fill="#3a2a1a" />
{/* Fret lines */}
{Array.from({ length: MF_FRETS - 1 }, (_, i) => i + 1).map(f => (
<line key={f}
x1={MF_NUT_X + f * MF_FRET_W} y1={MF_PAD_T - 5}
x2={MF_NUT_X + f * MF_FRET_W} y2={MF_PAD_T + 5 * MF_STR_H + 5}
stroke="#4a3a2a" strokeWidth={1} />
))}
{/* Nut */}
<line x1={MF_NUT_X} y1={MF_PAD_T - 5} x2={MF_NUT_X} y2={MF_PAD_T + 5 * MF_STR_H + 5}
stroke="#c0b090" strokeWidth={3} />
{/* Strings */}
{STRINGS.map((_, si) => (
<line key={si}
x1={MF_OPEN_X - MF_DOT_R - 2} y1={mfStringY(si)}
x2={MF_W - 6} y2={mfStringY(si)}
stroke="#9ca3af"
strokeWidth={si < 2 ? 0.8 : si < 4 ? 1.2 : 1.8} />
))}
{/* Fret numbers */}
{[3, 5, 7, 9, 12].map(f => (
<text key={f} x={mfFretX(f)} y={MF_PAD_T - 5}
textAnchor="middle" fontSize={8} fill="#6b7280">{f}</text>
))}
{/* String labels */}
{STRINGS.map((s, si) => (
<text key={si} x={5} y={mfStringY(si) + 3.5}
textAnchor="middle" fontSize={9} fill="#6b7280">{s.label}</text>
))}
{/* Note dots — colored by energy */}
{STRINGS.flatMap((str, si) =>
Array.from({ length: MF_FRETS }, (_, fi) => {
const pc = (str.root + fi) % 12
const energy = values[pc] / max
const inChord = chordNotes?.has(pc)
const inKey = keyNotes?.has(pc)
if (!inChord && !inKey && energy < 0.35) return null
if ((inChord || inKey) && energy < 0.08) return null
const cx = fi === 0 ? MF_OPEN_X : mfFretX(fi)
const cy = mfStringY(si)
let fill, textFill
if (inChord) {
fill = `rgba(168,85,247,${0.3 + energy * 0.7})`
textFill = '#fff'
} else if (inKey) {
fill = monoColor ? `rgba(192,132,252,${0.2 + energy * 0.75})` : `rgba(245,158,11,${0.2 + energy * 0.75})`
textFill = monoColor ? '#fff' : 'rgba(0,0,0,0.85)'
} else {
fill = `rgba(100,100,120,${energy * 0.7})`
textFill = 'rgba(180,180,190,0.7)'
}
return (
<g key={`${si}-${fi}`}>
{energy > 0.3 && (inChord || inKey) && (
<circle cx={cx} cy={cy} r={MF_DOT_R + 4}
fill={inChord ? 'rgba(168,85,247,0.25)' : monoColor ? 'rgba(192,132,252,0.2)' : 'rgba(245,158,11,0.2)'}
style={{ filter: 'blur(4px)' }} />
)}
<circle cx={cx} cy={cy} r={MF_DOT_R} fill={fill} />
<text x={cx} y={cy + 3.5} textAnchor="middle" fontSize={7} fontWeight="600" fill={textFill}>
{NOTES[pc]}
</text>
</g>
)
})
)}
</svg>
)
}
// Oscilloscope strip
const OSC_W = 600
const OSC_H = 110
function Oscilloscope({ waveform }) {
const { wave, rms, detectedFreq, detectedNote } = waveform || {}
const silent = !rms || rms < 0.005
// Note scroll history last 5 distinct notes
const noteHistoryRef = useRef([]) // [{ note, freq, id }, ...] oldest first
const lastNoteRef = useRef(null)
const noteIdRef = useRef(0)
const lastDisplayRef = useRef(null) // last detected note shown in header never flickers
if (detectedNote && detectedNote !== lastNoteRef.current) {
lastNoteRef.current = detectedNote
lastDisplayRef.current = { note: detectedNote, freq: detectedFreq }
noteHistoryRef.current.push({ note: detectedNote, freq: detectedFreq, id: noteIdRef.current++ })
if (noteHistoryRef.current.length > 5) noteHistoryRef.current.shift()
} else if (detectedFreq && detectedNote) {
lastDisplayRef.current = { note: detectedNote, freq: detectedFreq }
}
// Ghost waveform holds the last clear-pitch shape, fades slowly
const ghostRef = useRef({ path: '', fill: '', opacity: 0 })
if (detectedFreq) {
ghostRef.current = { path: '', fill: '', opacity: 1 } // will be filled below
} else {
ghostRef.current = { ...ghostRef.current, opacity: ghostRef.current.opacity * 0.97 }
}
let path = '', sinePath = ''
if (wave?.length) {
const mid = OSC_H / 2
const waveAmp = Math.max(...wave.map(Math.abs), 0.001)
const gain = Math.min((OSC_H * 0.44) / waveAmp, OSC_H * 0.44)
const lo = Math.floor(wave.length / 4)
const hi = Math.floor(wave.length / 2)
let offset = lo
for (let i = lo; i < hi - 1; i++) {
if (wave[i] <= 0 && wave[i + 1] > 0) { offset = i; break }
}
const drawLen = Math.min(wave.length - offset, Math.floor(wave.length * 0.85))
const step = OSC_W / drawLen
path = Array.from({ length: drawLen }, (_, i) => {
const v = wave[offset + i]
return `${i === 0 ? 'M' : 'L'}${(i * step).toFixed(1)},${(mid - v * gain).toFixed(1)}`
}).join(' ')
// Capture ghost path when we have a clear pitch
if (detectedFreq) {
ghostRef.current.path = path
ghostRef.current.fill = path + ` L${OSC_W},${mid} L0,${mid} Z`
}
if (detectedFreq) {
const effectiveSR = 44100 / 8
const sineAmp = Math.min(waveAmp * gain * 0.55, OSC_H * 0.38)
sinePath = Array.from({ length: 300 }, (_, i) => {
const t = i / 299
const x = (t * OSC_W).toFixed(1)
const phase = ((offset + t * drawLen) / effectiveSR) * detectedFreq * Math.PI * 2
const y = (mid - Math.sin(phase) * sineAmp).toFixed(1)
return `${i === 0 ? 'M' : 'L'}${x},${y}`
}).join(' ')
}
}
const lineColor = detectedFreq
? 'rgba(168,85,247,0.9)'
: silent ? 'rgba(50,50,60,0.8)' : 'rgba(100,200,140,0.75)'
const ghost = ghostRef.current
const ghostOp = ghost.opacity
const noteHistory = noteHistoryRef.current
const lastDisplay = lastDisplayRef.current
return (
<div>
<div className="flex items-center justify-between mb-1">
<p className="text-xs text-gray-600 uppercase tracking-widest">Oscilloscope raw mic input</p>
<div className="flex items-center gap-3">
{lastDisplay && (
<>
<span className={`text-xs font-bold ${detectedFreq ? 'text-accent' : 'text-gray-500'}`}>{lastDisplay.note}</span>
<span className="text-xs text-gray-500 tabular-nums">{lastDisplay.freq.toFixed(1)} Hz</span>
<span className="text-xs text-gray-600 tabular-nums">{(1000 / lastDisplay.freq).toFixed(2)} ms / cycle</span>
</>
)}
{silent && <span className="text-xs text-gray-700">silence</span>}
<span className="text-xs text-gray-700 tabular-nums">rms {rms ? (rms * 100).toFixed(1) : '0.0'}%</span>
</div>
</div>
<svg viewBox={`0 0 ${OSC_W} ${OSC_H}`} width="100%" style={{ display: 'block' }}
className="rounded-lg bg-surface border border-border">
{/* Zero line */}
<line x1={0} y1={OSC_H / 2} x2={OSC_W} y2={OSC_H / 2}
stroke="rgba(255,255,255,0.05)" strokeWidth={0.5} />
{/* Ghost waveform — previous clear-pitch shape fading out */}
{ghost.path && ghostOp > 0.04 && !detectedFreq && (
<>
<path d={ghost.fill} fill={`rgba(168,85,247,${(ghostOp * 0.06).toFixed(3)})`} />
<path d={ghost.path} fill="none"
stroke={`rgba(150,120,200,${(ghostOp * 0.35).toFixed(3)})`}
strokeWidth={0.8} strokeLinejoin="round" strokeLinecap="round" />
</>
)}
{/* Fill body */}
{path && (
<path
d={`${path} L${OSC_W},${OSC_H / 2} L0,${OSC_H / 2} Z`}
fill={detectedFreq
? 'rgba(168,85,247,0.08)'
: silent ? 'none' : 'rgba(90,190,130,0.07)'}
/>
)}
{/* Waveform line */}
{path && <path d={path} fill="none" stroke={lineColor} strokeWidth={0.9}
strokeLinejoin="round" strokeLinecap="round" />}
{/* Sine overlay */}
{sinePath && <path d={sinePath} fill="none"
stroke="rgba(168,85,247,0.28)" strokeWidth={0.9}
strokeLinejoin="round" strokeDasharray="5 4" />}
{/* Scrolling note history — newest on right, slides left on each new note */}
{noteHistory.map((entry, i) => {
const age = noteHistory.length - 1 - i // 0 = newest
const x = OSC_W - 28 - age * 100
const op = (1 - age * 0.18).toFixed(2)
const isNew = age === 0
return (
<g key={entry.id}
style={{ transform: `translateX(${x}px)`, transition: 'transform 0.45s cubic-bezier(0.4,0,0.2,1)' }}>
<text x={0} y={OSC_H - 18} textAnchor="middle"
fontSize={isNew ? 13 : 11} fontWeight={isNew ? '700' : '400'}
fill={isNew ? `rgba(168,85,247,${op})` : `rgba(160,130,210,${op})`}>
{entry.note}
</text>
<text x={0} y={OSC_H - 7} textAnchor="middle" fontSize={7}
fill={`rgba(120,100,160,${(parseFloat(op) * 0.7).toFixed(2)})`}>
{entry.freq ? entry.freq.toFixed(0) : ''}Hz
</text>
</g>
)
})}
</svg>
</div>
)
}
// Frequency spectrum
const SPEC_H = 130
const SPEC_F_MIN = 40
const SPEC_F_MAX = 4000
const SPEC_LOG = Math.log(SPEC_F_MAX / SPEC_F_MIN)
// Map a frequency in Hz to an x pixel position (log scale)
function specX(f, w) {
if (f <= SPEC_F_MIN) return 0
if (f >= SPEC_F_MAX) return w
return w * Math.log(f / SPEC_F_MIN) / SPEC_LOG
}
const SPEC_GRID = [
{ label: 'E2', freq: 82.4 },
{ label: 'C3', freq: 130.8 },
{ label: 'E3', freq: 164.8 },
{ label: 'A3', freq: 220 },
{ label: 'C4', freq: 261.6 },
{ label: 'E4', freq: 329.6 },
{ label: 'A4', freq: 440 },
{ label: 'C5', freq: 523.3 },
{ label: 'C6', freq: 1046.5},
{ label: 'C7', freq: 2093 },
]
function SpectrumPanel({ spectrum, detectedFreq }) {
const W = OSC_W
const ghostRef = useRef(null)
const ghostFreqRef = useRef(null) // { freq, opacity }
// Ghost frequency lines lock on detection, decay slowly when gone
if (detectedFreq) {
ghostFreqRef.current = { freq: detectedFreq, opacity: 1 }
} else if (ghostFreqRef.current) {
ghostFreqRef.current = { freq: ghostFreqRef.current.freq, opacity: ghostFreqRef.current.opacity * 0.97 }
}
const ghostFreq = ghostFreqRef.current?.opacity > 0.04 ? ghostFreqRef.current.freq : null
const ghostOpacity = ghostFreqRef.current?.opacity ?? 0
// Ghost: rises instantly with signal, decays very slowly lingers as grey
if (spectrum?.length) {
if (!ghostRef.current) ghostRef.current = new Float32Array(spectrum.length)
const ghost = ghostRef.current
for (let i = 0; i < spectrum.length; i++) {
ghost[i] = spectrum[i] > ghost[i] ? spectrum[i] : ghost[i] * 0.988
}
}
let fillPath = '', strokePath = '', ghostFill = '', ghostStroke = ''
if (spectrum?.length) {
const n = spectrum.length
const pts = Array.from({ length: n }, (_, i) => {
const x = ((i / (n - 1)) * W).toFixed(1)
const y = (SPEC_H * (1 - spectrum[i])).toFixed(1)
return `${i === 0 ? 'M' : 'L'}${x},${y}`
}).join(' ')
strokePath = pts
fillPath = pts + ` L${W},${SPEC_H} L0,${SPEC_H} Z`
const ghost = ghostRef.current
if (ghost) {
const gpts = Array.from({ length: n }, (_, i) => {
const x = ((i / (n - 1)) * W).toFixed(1)
const y = (SPEC_H * (1 - ghost[i])).toFixed(1)
return `${i === 0 ? 'M' : 'L'}${x},${y}`
}).join(' ')
ghostStroke = gpts
ghostFill = gpts + ` L${W},${SPEC_H} L0,${SPEC_H} Z`
}
}
return (
<div>
<p className="text-xs text-gray-600 uppercase tracking-widest mb-1">
Frequency spectrum 40 Hz 4 kHz (log scale)
</p>
<svg viewBox={`0 0 ${W} ${SPEC_H}`} width="100%" style={{ display: 'block' }}
className="rounded-lg bg-surface border border-border">
{/* Note grid lines */}
{SPEC_GRID.map(({ label, freq }) => {
const x = specX(freq, W).toFixed(1)
return (
<g key={label}>
<line x1={x} y1={0} x2={x} y2={SPEC_H - 14}
stroke="rgba(255,255,255,0.06)" strokeWidth={1} />
<text x={x} y={SPEC_H - 3} textAnchor="middle" fontSize={7.5}
fill="rgba(80,80,95,0.9)">{label}</text>
</g>
)
})}
{/* Ghost — slow-decaying grey residue from previous peaks */}
{ghostFill && (
<>
<path d={ghostFill} fill="rgba(120,120,130,0.08)" />
<path d={ghostStroke} fill="none" stroke="rgba(130,130,145,0.30)" strokeWidth={0.7} />
</>
)}
{/* Live spectrum fill + stroke */}
{fillPath && (
<>
<path d={fillPath} fill="rgba(80,180,130,0.13)" />
<path d={strokePath} fill="none" stroke="rgba(90,200,145,0.55)" strokeWidth={0.8} />
</>
)}
{/* Fundamental + harmonics */}
{ghostFreq && [1, 2, 3, 4, 5].map(h => {
const hf = ghostFreq * h
if (hf > SPEC_F_MAX) return null
const xNum = specX(hf, W)
const x = xNum.toFixed(1)
const midi = Math.round(12 * Math.log2(hf / 440) + 69)
const note = NOTES[((midi % 12) + 12) % 12]
const oct = Math.floor(midi / 12) - 1
// Place label left of line near the right edge, right of line elsewhere
const labelX = xNum > W - 40 ? xNum - 3 : xNum + 3
const anchor = xNum > W - 40 ? 'end' : 'start'
if (h === 1) {
const op = (0.9 * ghostOpacity).toFixed(3)
const textOp = (ghostOpacity * 0.95).toFixed(3)
return (
<g key={h}>
<line x1={x} y1={0} x2={x} y2={SPEC_H - 14}
stroke={`rgba(168,85,247,${op})`} strokeWidth={1.2} />
<text x={labelX} y={10} textAnchor={anchor} fontSize={8} fontWeight="700"
fill={`rgba(168,85,247,${textOp})`}>{note}{oct}</text>
<text x={labelX} y={20} textAnchor={anchor} fontSize={7}
fill={`rgba(168,85,247,${(ghostOpacity * 0.55).toFixed(3)})`}>f</text>
</g>
)
}
const op = ((0.5 - (h - 2) * 0.1) * ghostOpacity).toFixed(3)
return (
<g key={h}>
<line x1={x} y1={0} x2={x} y2={SPEC_H - 14}
stroke={`rgba(168,85,247,${op})`} strokeWidth={0.7} strokeDasharray="3 4" />
<text x={labelX} y={10} textAnchor={anchor} fontSize={7.5}
fill={`rgba(168,85,247,${op})`}>{note}{oct}</text>
<text x={labelX} y={19} textAnchor={anchor} fontSize={7}
fill={`rgba(168,85,247,${(parseFloat(op) * 0.7).toFixed(3)})`}>{h}f</text>
</g>
)
})}
</svg>
</div>
)
}
// Main component
export default function DebugView({ chroma, chordCandidates, noteAnalysis, waveform, keyInfo, currentChord, instrument = 'guitar', monoColor = false }) {
const keyPCs = new Set(keyInfo ? getScale(keyInfo.root, keyInfo.mode).map(n => NOTES.indexOf(n)) : [])
const chordPCs = new Set(currentChord ? getChordTones(currentChord).map(n => NOTES.indexOf(n)) : [])
const chromaArr = chroma ? [...chroma] : new Array(12).fill(0)
const histFreq = noteAnalysis ? noteAnalysis.freq : new Array(12).fill(0)
const topKeys = noteAnalysis ? noteAnalysis.topKeys : []
const totalNotes = noteAnalysis?.total ?? 0
const sessionSecs = noteAnalysis?.sessionSecs ?? 0
const sessionLabel = sessionSecs >= 60
? `${Math.floor(sessionSecs / 60)}m ${sessionSecs % 60}s`
: `${sessionSecs}s`
const topScore = chordCandidates[0]?.score ?? 1
const topKeyScore = topKeys[0]?.score ?? 1
return (
<div className="flex flex-col gap-4">
{/* ── Live chroma visualization (instrument-synced) ── */}
<div>
<p className="text-xs text-gray-600 uppercase tracking-widest mb-2">Live chroma what the engine hears right now</p>
{instrument === 'guitar'
? <MiniFretboard values={chromaArr} keyNotes={keyPCs} chordNotes={chordPCs} monoColor={monoColor} />
: <PianoSVG values={chromaArr} keyNotes={keyPCs} chordNotes={chordPCs} keyH={90} monoColor={monoColor} />
}
</div>
{/* ── Bottom three columns ── */}
<div className="grid grid-cols-[2fr_1.5fr_1fr] gap-5">
{/* Col 1: Chord candidates */}
<div>
<p className="text-xs text-gray-600 uppercase tracking-widest mb-2">Chord candidates</p>
<div className="flex flex-col gap-1">
{chordCandidates.length === 0 && (
<p className="text-gray-700 text-xs">No signal detected</p>
)}
{chordCandidates.map((c, i) => (
<div
key={c.name}
className={`flex items-center gap-2 px-2 py-1.5 rounded-lg ${
i === 0 ? 'bg-accent/10 border border-accent/25' : 'border border-transparent'
}`}
>
<span className="text-xs text-gray-600 w-3 shrink-0">{i + 1}</span>
<span className={`text-sm font-bold w-14 shrink-0 ${i === 0 ? 'text-white' : 'text-gray-400'}`}>
{c.name}
</span>
<div className="flex-1 h-1.5 bg-gray-800 rounded-full overflow-hidden">
<div
className={`h-full rounded-full transition-all duration-300 ${i === 0 ? 'bg-accent' : 'bg-gray-600'}`}
style={{ width: `${(c.score / topScore) * 100}%` }}
/>
</div>
<span className="text-xs text-gray-500 w-8 text-right tabular-nums">{c.score.toFixed(2)}</span>
<div className="flex gap-1 w-14 justify-end">
{c.diatonic && <span className="text-[9px] px-1 rounded bg-green-900/50 text-green-400">key</span>}
{c.bassBonus > 0 && <span className="text-[9px] px-1 rounded bg-blue-900/50 text-blue-400">bass</span>}
</div>
</div>
))}
</div>
</div>
{/* Col 2: Note history piano with % labels */}
<div>
<div className="flex items-baseline justify-between mb-2">
<p className="text-xs text-gray-600 uppercase tracking-widest">Note history</p>
{totalNotes > 0 && (
<span className="text-[10px] text-gray-600 tabular-nums">
{totalNotes.toLocaleString()} notes · {sessionLabel}
</span>
)}
</div>
<PianoSVG values={histFreq} keyNotes={keyPCs} chordNotes={chordPCs} keyH={70} showPct={true} monoColor={monoColor} />
</div>
{/* Col 3: Key candidates */}
<div>
<p className="text-xs text-gray-600 uppercase tracking-widest mb-2">Key match scores</p>
<div className="flex flex-col gap-1.5">
{topKeys.length === 0 && (
<p className="text-gray-700 text-xs">Not enough history</p>
)}
{topKeys.map((k, i) => (
<div key={`${k.root}-${k.mode}`} className="flex items-center gap-2">
<span className={`text-xs w-16 shrink-0 ${i === 0 ? 'text-white font-semibold' : 'text-gray-500'}`}>
{k.root} {k.mode === 'major' ? 'maj' : 'min'}
</span>
<div className="flex-1 h-1 bg-gray-800 rounded-full overflow-hidden">
<div
className={`h-full rounded-full ${i === 0 ? 'bg-amber-400' : 'bg-gray-600'}`}
style={{ width: `${Math.max(0, (k.score / topKeyScore) * 100)}%` }}
/>
</div>
<span className="text-[10px] text-gray-600 tabular-nums w-8 text-right">{k.score.toFixed(2)}</span>
</div>
))}
</div>
</div>
</div>
{/* ── Oscilloscope + spectrum ── */}
<div className="flex flex-col gap-3">
<Oscilloscope waveform={waveform} />
<SpectrumPanel spectrum={waveform?.spectrum} detectedFreq={waveform?.detectedFreq} />
</div>
</div>
)
}

Some files were not shown because too many files have changed in this diff Show More