Documentation comes from this release commit, without inheriting newer content. Commit: 63ea8c2b3d.
Feature — Catalog
Bundled song list + monetisation flags. Synced from a published Google Sheet CSV at build time into src/assets/ (the default), optionally overridden at run time by Remote Config / a CDN, and merged with owned delisted songs from @piano/user-library.
Runtime: bundled default, providers override
The catalog is a layered slice shared by the whole app (src/domain, src/data, src/infra — see Layers), not a feature folder. At run time:
- Bundled is the default.
LocalCatalogServiceservessongs.json(version = the build's sync time in unix seconds).getCached()is synchronous and never empty, so the first frame paints with zero requests. - Providers override it.
RemoteConfigCatalogService(Firebase RC keysong_catalog, inline JSON) andCdnCatalogService(config.json+ immutablecatalog.<N>.json, setEXPO_PUBLIC_CATALOG_URL) are asked on launch / foreground / pull / push.CatalogResolverpicks the highestversion(tie → higher provider priority), skips snapshots whoseminAppVersionis above the app, and never lets an empty catalog win. A provider is a new class implementingICatalogProviderplus one line increateCatalogModule. - Persisted, offline-safe. The winning remote snapshot is cached in MMKV (
catalog.v1.*, blob then pointer). Restart paints it before any request; a newer app build whose bundle beats it drops it. Offline is a state (sync: "offline"), not an error. - The UI reads one store.
useCatalogStore(a plain zustandcreate(...)const insrc/features/catalog/catalog-runtime.ts, built fromcatalogStateCreatorinstore.ts) subscribes once toCatalogFacade;useCatalogSongsQuery/useCatalogSongByFileNameQuerykeep their signatures but read that store.
MIDI: N pre-built, the rest downloaded
MidiBundlePolicy is the single rule for which songs ship pre-built MIDI. The build and the app use the same class. By default it ships the songs the sheet marks Instant in its Note column (any case); a sheet that marks none falls back to the first DEFAULT_BUNDLED_MIDI_COUNT (5) by catalog order. A bundled song ships its new versions too (charts/<fileName>-v-<name>.json, see Song versions), so an assigned version plays offline from the first launch.
A number or all ignores the Note column. A song that was bundled under the first-5 rule and is not marked Instant becomes download-on-play.
Learn Mode follows the same rule. The songs MidiBundlePolicy selects ship a pre-built learn chart (their Learn Mode MIDI, downloaded in memory and converted straight to learnmode/charts/<key>_learnmode.json — the raw .mid is never stored, like gameplay MIDI). Every other song keeps learnMidiUrl / learnAudioUrl in songs.json (and in the remote catalog), the Song-list Learn CTA is lit by that link (hasLearnMode reads the catalog asset index), and tapping Learn runs useLearnChart → ensureLearnChart(songId) (src/infra/container/ensure-learn-chart.ts): facade.getMidi({ song, part: null, learn: true }) (same bundled → disk cache → download path, cache key <fileName>-learn), then the chart is built from the bytes with the production builder (src/features/learn/chart-build/, shared with scripts/convert-learn-charts.ts), validated and registered in @core/sdk/runtime-learn-chart for getLearnChart. The Learn screen shows a loading state meanwhile and "unavailable" if the download or the build fails. Learn Mode Audio has no consumer in the app today (the Learn backing is the chart's rhythm track), so the URL is only carried by the catalog.
Song preview plays the song's Game MIDI and nothing else: the gameplay chart synthesised through the piano sampler, never a recording (the Learn Mode audio may not be used as a preview, for copyright). It plays the song's busiest 15 s: the stretch with the most melody notes starting inside it, the earliest on a tie, opening on a melody note so it never starts on silence; the backing notes of that stretch play with it (findBusiestPreviewStartMs). A player assigned a version by song_versions previews that version (read on every tap, on every screen), fetched and falling back to the song's own exactly as Game Mode does (setPreviewVersionLookup + ensurePlayableSongChart, wired in src/bootstrap/entrySetup.ts). It follows the same path: every playable song shows the preview button (hasSongPreview also accepts a song whose catalog MIDI URL is known), and SongPreviewService calls ensureChart (bootstrap wires it to ensureSongChart) when the chart is not bundled; a failed download plays nothing and ends the preview like any other.
Audio files follow the same path. SongAudioRepository.ensure() resolves bundled → disk cache → download for a song's recording (bgmUrl for Game Mode, learnAudioUrl for Learn Mode; bundled: SongAsset.audioAssetModule, learnmode/audio/<key>.mp3), returning a plain file URI the audio engine streams — never bytes — with one download per file however many ask, and download: "background" for a caller that must not wait. A download goes straight to the file through the native downloader (MediaStore.downloadToFile: into <key>.audio.part, renamed once the status is 2xx), so a recording's several MiB never pass through JS as bytes or base64 — the MIDI path (fetchAndCache / write) still does, for files of a few KB. CatalogFacade.getBacking(song, purpose, options) is the one question Game Mode and Learn Mode ask: the recording if there is one, otherwise the song's MIDI (rhythm), otherwise none. They hand the answer to the engine's sequencer; see audio-engine.md.
At run time MidiRepository.ensure() resolves bundled → disk cache (same URL revision, size-verified) → download and returns a typed result (bundled | ready | unavailable). Gameplay calls ensureSongChart(fileName) (src/infra/container/ensure-song-chart.ts) before building the chart; downloaded bytes go through the existing runtime-midi registry, so loadGameplayChart is unchanged. Songs keep their midiUrl in songs.json, so they still list as playable.
Background MIDI download queue
So a song opens without waiting on the network, the app warms the disk with every MIDI the catalog serves that it does not ship — each song's full-song MIDI, then its Learn MIDI, in sortOrder (the order of the song list). createMidiDownloadProcessor (src/infra/container/midi-download-processor.ts, rules in src/domain/policies/midi-download-policy.ts) is wired by startMidiDownloadQueue (src/bootstrap/) from entrySetup.ts, on the idle queue.
- One song at a time, with a gap. A MIDI is fetched through
facade.prefetchMidi([ref])(the normal bundled → disk → download path, single-flight per key, so a song the player opens while it is on the wire joins that request). The next one startsMIDI_DOWNLOAD_GAP_MS(3 s) later. What the device already has (shipped, or cached at the current URL) is skipped with no gap and no request. The first song waitsMIDI_DOWNLOAD_START_DELAY_MS(5 s) after the idle queue so it never competes with boot. - Never while the player is busy.
isBlocked= gameplay (isGameplayActive,/play), anything holding the live audio surface (Learn, the tutorial's song and practice, the keyboard) or a fullscreen ad. The flags are poll-only, so a held-back queue looks again every 5 s and carries on the moment the player is free; a download already on the wire is allowed to finish. In the background it stops (AppStatebackground→pause) and a return to the foreground resumes it. - Failure. A failed MIDI waits 10 s, 30 s, 90 s (in a row) before the next try, and one that failed is tried only after every MIDI not yet tried. Three failures in a row mean offline: the queue rests until the catalog changes (
observe) or the app returns from the background, which also forgets what it gave up on (3 tries per MIDI). Section MIDIs are not fetched.
Test it with createHarness + a hand-moved scheduler (src/infra/__tests__/midi-download-processor.test.ts); coverage: bun run test:coverage src/domain src/infra.
Song versions (A/B test)
A song can have new versions of its full-song MIDI (sheet Link MIDI Piano_<name> → Song.midiVersions), and Remote Config's song_versions says which one a Game Mode play loads: a JSON object of song id → version name, {} by default.
- Resolution (
resolveSongVersion,src/domain/policies/song-version-policy.ts): a song plays the assigned version only when its catalog row has that version; an unknown song or name plays the song's own MIDI. Section parts, Learn Mode and the tutorial's own song (useTutorialSongSession, which plays itstutorial_songMIDI) never take a version. - Loading (
CatalogFacade.getPlayableMidi(song, version)→GetSongMidi.playable): the version's MIDI goes bundled → disk cache → download like any other, under its own key (midiVersionKey→<fileName>-v-<name>). A version that cannot be had (offline, a dead link) falls back to the song's own MIDI; the song is never blocked.ensurePlayableSongChart(fileName, version)(src/infra/container/ensure-song-chart.ts) is whatuseMagicGameplaycalls, and it reports which chart loaded. - When it is read: once per Game Mode screen, as it opens (
PlayScreen), so a Remote Config fetch mid-song never swaps the chart. The bootstrap downloads every assigned version in the background once Remote Config is hydrated (prefetchSongVersions), so the first play rarely waits. - Analytics: every song event carries
song_version—default, or the version name of the chart that loaded (analytics-events.md). - Previews play the assigned version too: its busiest 15 s, with the same fetch and fallback (see Song preview above).
- Progress, high scores and unlocks stay keyed by the song id: a version is the same song.
- Dev builds:
EXPO_PUBLIC_RC_SONG_VERSIONS='{"no-batidao":"short"}'in.env.localwins over the console (dev-overrides.ts).
Publishing a remote catalog (PO workflow)
When the song sheet changes and phones should get it without an app release:
- Open the Piano DevTool (
bun run devtool:dev) → Catalog tab. - Click Read sheet & convert. The DevTool reads the Song Config sheet and converts it with the same code as the build-time sync (
scripts/catalog-sync/remote-catalog.ts). It shows the song count, how many are playable, which songs are new versus the app bundle, any skipped rows, and the payload size. Optionally set a minimum app version (older builds ignore the catalog). - Click Copy JSON (or Download .json).
- Firebase console → Remote Config → parameter
song_catalog(String) → paste → Publish changes.
Phones pick it up on the next launch / foreground check. version is the export time in unix seconds, the same unit the app derives for its bundle, so an export made after a build overrides it and an older one never does. Remote Config allows 1,000,000 characters across all parameter values; today's catalog is ~14 KB and the tab warns when the payload passes half of that (switch to the CDN provider then).
The same conversion is available from the CLI (CI, or a CDN instead of Remote Config):
Layers
domain and data are pure TypeScript (no RN/Expo/app imports, no hidden fetch/Date.now/MMKV); src/__tests__/architecture.test.ts enforces it.
Inspecting at runtime (DevTools)
CatalogFacade.inspect() → InspectCatalog use case: ICatalogRepository.inspect() (active / bundled / on-disk summaries, SyncPolicy.describe TTL window, each entry's origin and change vs the bundled catalog) plus IMidiRepository.inspect(ref) per MIDI slot (bundled / cached / stale / remote / none). MidiCache records savedAt per disk copy (older entries read as savedAt: null). It feeds the Rozenite Catalog panel (docs/README.md); nothing in the app's runtime path calls it. The panel stays current through CatalogFacade.observeMidi(listener) → ObserveMidi → IMidiRepository.subscribe, which fires after a downloaded MIDI is written to disk (a cache hit, a bundled MIDI or a failed write fires nothing; a throwing listener is reported, never fails the download).
Testing in isolation
Every edge is an interface, so the real policies, repositories and use cases run against fakes from src/testing/support.ts: FakeCdn (ETag/304, online switch, request log), FakeRemoteConfig, MemoryKeyValueStore, InMemoryBlobStore, FakeClock, FakeBundledCatalog / FakeBundledCharts. createHarness({ bundledMidiCount, providers, kv, blobs, clock }) builds the full module (call it again with the same kv/blobs to simulate a restart). A store test builds createCatalogStore({ facade, project }) over a two-method fake facade (features/catalog/__tests__/store.test.ts).
Sheet columns
Order | Song Name | Artist | Genre | Difficulty | isPremium | Ads Unlock | isIAP | isPublicDomain | Thumbnail | Link MIDI Piano | Link MIDI Piano_<name>… | Section 1 | Section 2 | Section 3 | Link BGM | Song ID | Note
- Link MIDI Piano — full-song MIDI downloaded in memory and converted to
src/assets/charts/{fileName}.json(raw.midis not stored under assets). - Link MIDI Piano_<name> — a new version of that MIDI, one column per version (
Link MIDI Piano_short; the name is lower-case letters and digits, any header case). Empty orTBU= the song has no such version. It lands in the song'smidiVersions({ short: <url> }); nothing plays it until Remote Config assigns it (Song versions). - Note —
Instantships the song's chart in the app (see MIDI: N pre-built); anything else is a free-text note. - Section 1/2/3 — per-part MIDI →
src/assets/charts/{fileName}-section-{N}.json(max 3). - Link BGM — backing track at
src/assets/audio/{fileName}.{ext}. - Preview audio — short clip at
src/assets/previews/{fileName}-preview.{ext}when present. - Song ID — stable catalog id (falls back to slug-from-name when empty).
- Difficulty — integer
1..6on the sheet and insongs.json(see Difficulty scale). - Rows with no MIDI still appear in the songs list as subscription/IAP placeholders; gameplay navigation gates on
isPlayable.
Difficulty scale
Six-level rating synced with the Google Sheet Difficulty column and @piano/catalog Difficulty enum:
Sheet / bundled catalog. New rows and catalog:sync-sheet output use this scale. UI maps to slug chips (tutorial, easy, …) via difficultyToSlug().
Legacy data (pre–6-level builds). Older persisted values used a 3-tier scale (1 = Easy, 2 = Medium, 3 = Hard). Those are not the same as today’s 1 = Tutorial:
- User library (
@piano/user-library):schemaVersion1 documents are upgraded to v2 on read — MMKV is rewritten locally; Firestore receives v2 on the next library sync. See packages/user-library/README.md. - Gameplay UI:
difficulty === 1(Tutorial) is not shown as a chip on play/result/FTUE surfaces — it is a sheet/catalog marker only (shouldShowGameplayDifficultyTagin@components/DifficultyTag.utils). - Songs list filter: the header difficulty dropdown offers
allpluseasy…impossibleonly (no Tutorial filter). - Bundled
songs.json: refreshed bycatalog:sync-sheet/postinstall; existing bundles in the wild are replaced on the next app ship that includes a new sync. - Google Sheet: content must use the new
1..6column values (old1= Easy rows should become2, etc.).
Sync workflow
Also runs on postinstall after build:packages (always re-downloads sheet assets — no skip cache). Script entry: scripts/sync-catalog-from-sheet.ts.
One tab, both modes. The Song Config tab (SONG_CONFIG_SHEET_GID in song-config.ts) feeds gameplay and Learn Mode, and the one script builds both:
<key> is learnAssetKey(songId) (learn-chart-stem.ts): the id lowercased with accents and non-alphanumerics dropped (fur-elise → furelise) — the same key the app uses to gate the Learn CTA and load the chart/backing. The sheet is the only source of Learn Mode MIDI: the sync converts each one in memory and writes only learnmode/charts/<key>_learnmode.json (gitignored), a song has Learn Mode exactly when its row carries a Learn Mode MIDI link, and the sync deletes the chart of a song whose link came off (orphan cleanup) — CI also wipes every learn chart before it syncs, since the self-hosted runner keeps gitignored files between runs. A raw learnmode/*_learnmode.mid left by an older sync is removed on the next run. Backings are generated the same way: learnmode/audio/* is gitignored (only .gitkeep is tracked), a song has a backing exactly when its row carries a Learn Mode Audio link and the bundle policy ships it, and the sync deletes any backing the sheet no longer plans (CI wipes the folder first). After downloading, the script rebuilds the tutorial + learn chart manifests and the learn audio manifest (also on the offline fallback), and fails if a learn MIDI does not pass the learn schema. bun run charts:convert-learn only regenerates the learn manifest.ts / stems.ts from the JSON already on disk (CI jobs that restore the catalog snapshot run it). Learn logic: scripts/catalog-sync/learn-assets.ts.
Files
Data flow
On cold start, React Query serves initialData from bundled songs.json immediately. There is no runtime sheet fetch or MMKV catalog refresh. Pull-to-refresh re-reads the same bundled source.
Segmentation. Gameplay reads CatalogSong.sectionMidiUrls. For bundled multi-part songs (section MIDIs on disk but no URLs in songs.json), toCatalogSong injects placeholder section URLs so part-count logic in catalog-segmentation.ts stays accurate. When a sync drops section files, segment-progress-reconcile.ts clears stale unlock progress on the next app version that ships the new bundle.
Media resolution
Production gameplay loads bundled chart JSON (and optional BGM/preview). Sheet MIDI is converted at sync time — it is not packaged as .mid. HybridMidiRepository has an empty bundled set and only resolves remote MIDI URLs for owned delisted snapshots.
Query keys
Hooks
Offline bootstrap
src/assets/config/songs.json is gitignored and regenerated whenever the sheet CSV is read (catalog:sync-sheet / postinstall). Offline charts + BGM/preview bytes live beside it under src/assets/charts/, src/assets/audio/, and src/assets/previews/.
Dev-synced songs (Piano DevTool)
When EXPO_PUBLIC_ENABLE_DESKTOP_TOOLS=1, catalog-merge.ts folds songs pushed from the Piano DevTool into the catalog queries: an add becomes a synthetic free entry (isPublicDomain so store filtering keeps it), an override keeps the bundled song's id and monetisation and only swaps the chart (getGameplayChart prefers the dev MIDI). dev-songs.ts maps a synced DevSong to a catalog row and dev-sync-snapshot.ts builds the rich catalog_snapshot (artist, difficulty, Learn Mode, playable, in-app vs dev source) plus bundled-chart answers the desktop requests. With the flag off none of this runs.