> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# 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](#layers)), not a feature folder. At run time:

1. **Bundled is the default.** `LocalCatalogService` serves `songs.json` (version = the build's sync time in unix seconds). `getCached()` is synchronous and never empty, so the first frame paints with zero requests.
2. **Providers override it.** `RemoteConfigCatalogService` (Firebase RC key `song_catalog`, inline JSON) and `CdnCatalogService` (`config.json` + immutable `catalog.<N>.json`, set `EXPO_PUBLIC_CATALOG_URL`) are asked on launch / foreground / pull / push — `push` is every Remote Config fetch that lands (`onRemoteConfigFetched`, forced past the launch / foreground TTL; over a song it waits for the next foreground, which is then forced). `CatalogResolver` picks the highest `version` (tie → higher provider priority), skips snapshots whose `minAppVersion` is above the app, and never lets an empty catalog win. Only the CDN sets `minAppVersion` (in its `config.json`); the Remote Config `song_catalog` is **never matched against the app build version** — a `minAppVersion` left in its value is ignored, and which builds get it is a Remote Config condition in the console. A provider is a new class implementing `ICatalogProvider` plus one line in `createCatalogModule`.
3. **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.
4. **The UI reads one store.** `useCatalogStore` (a plain zustand `create(...)` const in `src/features/catalog/catalog-runtime.ts`, built from `catalogStateCreator` in `store.ts`) subscribes once to `CatalogFacade`; `useCatalogSongsQuery` / `useCatalogSongByFileNameQuery` keep 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](#song-versions-ab-test)), so an assigned version plays offline from the first launch.

```bash
bun run catalog:sync-sheet                                # default: the Instant songs (else the first 5), also in CI / postinstall
CATALOG_BUNDLED_MIDI_COUNT=all bun run catalog:sync-sheet # override: every song bundled ("0" = none, "12" = first 12)
```

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`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/audio/song-preview/preview-notes.ts)). 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](/docs/audio-engine.md#audio-files-and-the-song-backing).

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 starts `MIDI_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 waits `MIDI_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 (`AppState` `background` → `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.

```json
{ "no-batidao": "short" }
```

- **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 its `tutorial_song` MIDI) 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 what `useMagicGameplay` calls, 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](/docs/analytics-events.md#song-sessions-across-game-mode-and-learn-mode)).
- **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.local` wins over the console ([`dev-overrides.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/config/dev-overrides.ts)).

### Publishing a remote catalog (PO workflow)

When the song sheet changes and phones should get it **without an app release**:

1. Open the **Piano DevTool** (`bun run devtool:dev`) → **Monetization** tab.
2. Click **Fetch sheet**. 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`); skipped rows show as warnings. Optionally set a minimum app version under **Source & backup** (older builds ignore the catalog).
3. Pick the variant (Friendly is the default Remote Config value; each A/B condition has its own variant), adjust its song order and access switches if needed, then **Copy song_catalog** (or **Save song_catalog**).
4. Firebase console → **Remote Config** → parameter `song_catalog` (String), in that variant's condition → paste → **Publish changes**. The same variant's `mon_pkg` and `fs_logic` are copied from the same section.

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 per variant, so four variants stay well below it (switch to the CDN provider if it grows).

The same conversion is available from the CLI (CI, or a CDN instead of Remote Config):

```bash
bun run catalog:publish-remote [outDir] [--csv sheet.csv] [--min-app 1.5.0]
# writes remote-config.json (the RC value), catalog.<version>.json and config.json (upload config.json LAST)
```

### Layers

```
features/catalog/store.ts ─▶ domain/facades/CatalogFacade ─▶ use-cases ─▶ ports (I*)
                                                                 ▲
data/{repositories,services,cache,mappers,dto} ──implements──────┘
infra/adapters (MMKV, fetch, MediaStore, Firebase) + infra/container (the only `new`s)
```

`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](/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`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/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`).

```bash
bun test src/domain src/data src/infra src/__tests__ src/features/catalog scripts/catalog-sync
```

## 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`

- **isPublicDomain** — the app no longer reads it (04/12/2026). **Content team:** keep the column in the song sheet and in the console `song_catalog` while app versions 1.0.11–1.0.13 are in use; they require it.
- **Link MIDI Piano** — full-song MIDI downloaded in memory and converted to `src/assets/charts/{fileName}.json` (raw `.mid` is 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 or `TBU` = the song has no such version. It lands in the song's `midiVersions` (`{ short: <url> }`); nothing plays it until Remote Config assigns it ([Song versions](#song-versions-ab-test)).
- **Note** — `Instant` ships the song's chart in the app (see [MIDI: N pre-built](#midi-n-pre-built-the-rest-downloaded)); 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..6` on the sheet and in `songs.json` (see [Difficulty scale](#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:

| Value | Label      |
| ----- | ---------- |
| 1     | Tutorial   |
| 2     | Easy       |
| 3     | Medium     |
| 4     | Hard       |
| 5     | Extreme    |
| 6     | Impossible |

**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:

| Legacy stored value | Meaning then | Migrated to (new scale) |
| ------------------- | ------------ | ----------------------- |
| 1                   | Easy         | 2 (Easy)                |
| 2                   | Medium       | 3 (Medium)              |
| 3                   | Hard         | 4 (Hard)                |

- **User library** (`@piano/user-library`): `schemaVersion` **1** 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](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/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 (`shouldShowGameplayDifficultyTag` in `@components/DifficultyTag.utils`).
- **Songs list filter**: the header difficulty dropdown offers `all` plus `easy` … `impossible` only (no Tutorial filter).
- **Bundled `songs.json`**: refreshed by `catalog: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..6` column values (old `1` = Easy rows should become `2`, etc.).

## Sync workflow

```bash
bun run catalog:sync-sheet   # manual refresh after sheet edits
```

Also runs on `postinstall` after `build:packages` (always re-downloads sheet assets — no skip cache). Script entry: [`scripts/sync-catalog-from-sheet.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/scripts/sync-catalog-from-sheet.ts).

**One tab, both modes.** The Song Config tab (`SONG_CONFIG_SHEET_GID` in [`song-config.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/config/song-config.ts)) feeds gameplay and Learn Mode, and the one script builds both:

| Column                                                                                                          | Mode     | Lands in                                                                          |
| --------------------------------------------------------------------------------------------------------------- | -------- | --------------------------------------------------------------------------------- |
| `Song Name`, `Artist`, `Genre`, `Difficulty`, `isPremium`, `Ads Unlock`, `isIAP`, `isPublicDomain`, `Thumbnail` | catalog  | `config/songs.json`                                                               |
| `Link MIDI Piano`                                                                                               | gameplay | `charts/<fileName>.json` (converted in memory)                                    |
| `Learn Mode MIDI`                                                                                               | learn    | converted in memory → `learnmode/charts/<key>_learnmode.json` (no `.mid` written) |
| `Learn Mode Audio`                                                                                              | learn    | `learnmode/audio/<key>.mp3` → `learnAudioAssets`                                  |

`<key>` is `learnAssetKey(songId)` ([`learn-chart-stem.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/sdk/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`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/scripts/catalog-sync/learn-assets.ts).

## Files

```text
scripts/
  sync-catalog-from-sheet.ts
  catalog-sync/               # download, manifest, generators
    learn-assets.ts           # Learn Mode MIDI/backing plan + audio manifest
src/assets/
  config/songs.json           # bundled catalog metadata (generated)
  catalog/
    .gitkeep                  # tracked placeholder
    sync-manifest.json        # last sync checksums (gitignored, generated)
  charts/
    .gitkeep                  # tracked placeholder
    *.json                    # gitignored — MIDI→JSON at catalog:sync-sheet / CI
    manifest.ts               # gitignored Metro map (generated by convert-charts)
  audio/
    .gitkeep                  # tracked placeholder
    *                         # gitignored BGM binaries (ogg/mp3/…)
  previews/
    .gitkeep                  # tracked placeholder
    index.ts                  # gitignored Metro map (generated)
    *                         # gitignored preview clips (mp3/…)
  songs/                      # bitmap assets only (manifest via assets:sync)
  learnmode/
    charts/                   # gitignored learn chart JSON (Learn MIDI converted at sync time) + manifest.ts / stems.ts (convert-learn-charts)
    audio/                    # gitignored Learn Mode backings (sheet `Learn Mode Audio`) + .gitkeep
src/core/sdk/
  song-assets.ts              # gitignored catalog id → chartAssets / audio map (generated; indexes `@assets/charts/manifest`)
src/features/catalog/
  api.ts                      # parseSongConfigCsv() — used by sync script + tests
  sheet-mappers.ts            # CSV row → Song (+ sectionMidiUrls)
  bundled-file-name.ts        # optional bundled fileName lookup via songs.json
  mappers.ts                  # Song → CatalogSong, cover URL helpers
  catalog-merge.ts            # mergeDelistedOwned + buildDisplayCatalog
  catalog-media-sync.ts       # legacy MediaStore eviction (owned delisted snapshots)
  owned-snapshot.ts           # CatalogSong → library snapshot shape
  cache.ts                    # legacy MMKV snapshot helpers
  queries.ts                  # useCatalogSongsQuery (bundled), useCatalogSongByFileNameQuery
  types.ts                    # CatalogSong (+ delisted flag)
  __tests__/
```

## Data flow

```mermaid
flowchart LR
  sheet[(Google Sheet CSV)] --> sync["sync-catalog-from-sheet.ts"]
  sync --> assets["src/assets/config + charts + audio + previews"]
  assets --> hydrate["readCatalogInitialData"]
  hydrate --> list[SongsScreen instant paint]
  assets --> query["fetchAndFinalizeCatalog"]
  query --> merge["buildDisplayCatalog"]
  merge --> lib["UserLibraryManager"]
  lib --> display["CatalogSong[]"]
  display --> list
  display --> songs["features/songs"]
  display --> piano["features/piano"]
```

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`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/catalog/catalog-segmentation.ts) stays accurate. When a sync drops section files, [`segment-progress-reconcile.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/catalog/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`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/sdk/adapters/hybrid-midi-repository.ts) has an empty bundled set and only resolves remote MIDI URLs for owned delisted snapshots.

```mermaid
flowchart LR
  play[Play] --> chart["loadGameplayChart → ChartJson"]
  chart --> engine[chartJsonToChart]
  preview[Owned delisted MIDI] --> hybrid[HybridMidiRepository]
  hybrid --> remote["remote URL fallback"]
  remote --> cache["MediaStore.fetchAndCache"]
```

## Query keys

```ts
export const catalogKeys = {
  all: ["catalog"] as const,
  list: () => [...catalogKeys.all, "list"] as const,
  byFileName: (fileName: string) => [...catalogKeys.all, "by-fileName", fileName] as const,
};
```

## Hooks

| Hook                                      | Returns               | Notes                                 |
| ----------------------------------------- | --------------------- | ------------------------------------- |
| `useCatalogSongsQuery()`                  | `CatalogSong[]`       | Bundled `songs.json` + delisted merge |
| `useCatalogSongByFileNameQuery(fileName)` | `CatalogSong \| null` | Lookup for gameplay routes            |

## Offline bootstrap

[`src/assets/config/songs.json`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/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](/docs/devtool.md) into the catalog queries: an **add** becomes a synthetic free entry (free), 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.

***

<small>Source: [`docs/features/catalog.md`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/docs/features/catalog.md)</small>
