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

# Architecture

The codebase has two halves separated by a hard boundary:

- **Host app** (`app/` + `src/`) — the Expo / React Native shell: routing, screens, providers, theming, query glue.
- **Piano packages** (`packages/@piano/*`) — pure TypeScript domain logic: MIDI parsing, SoundFont voice-plan, gameplay state machines, player data, catalog, progression. No React, no RN.

The host app reaches into the packages **only through `@piano/sdk`**. Everything else in `packages/*` is an implementation detail of the SDK. See [monorepo.md](/docs/monorepo.md) for the full package-graph.

## Layers

```mermaid
flowchart TB
  subgraph routes ["app/ — expo-router"]
    routeFiles["Route files<br/>(thin re-exports)"]
  end

  subgraph featureLayer ["src/features/* — business code"]
    screens[screens/]
    components[components/]
    queries[queries.ts]
    store[store.ts]
    api[api.ts]
    mappers[mappers.ts]
    types[types.ts]
  end

  subgraph foundation ["src/{core,components}/ — shared foundation"]
    sharedUi["components/<br/>Screen · Text · PrimaryButton · ImageCache"]
    coreEntry["core/entrySetup.ts<br/>(composition root)"]
    coreServices["core/services/<br/>apiClient · mmkv · queryClient · system-gesture-defer"]
    coreProviders["core/providers/<br/>AppProviders"]
    coreHooks["core/hooks/<br/>useScreenInsets · useMemoryWarning · useKeepGameplayAwake"]
    coreOrientation["core/orientation/<br/>useOrientation · orientation-store"]
    coreMemory["core/memory/<br/>ResourceScope"]
    coreAudio["core/audio/<br/>singleton native piano sampler"]
    coreTheme["core/theme/<br/>colors · spacing · fonts · breakpoints · themes"]
    coreUtils["core/utils/<br/>crashReporting · delay<br/>eventEmitter · stringHelper · ..."]
  end

  subgraph pianoPkgs ["packages/@piano/* — pure TS domain logic"]
    sdk["sdk<br/>createPianoSdk()"]
    rest["types · keyboard · core · midi · network ·<br/>analytics · ads · progression · player-data ·<br/>catalog · gameplay-{learn,magic,zen}"]
    sdk --> rest
  end

  routeFiles --> coreEntry
  routeFiles --> screens
  routeFiles --> coreProviders
  coreEntry --> coreServices
  screens --> components
  screens --> queries
  screens --> store
  screens --> sharedUi
  queries --> api
  queries --> mappers
  queries --> store
  api --> types
  mappers --> types
  store --> coreServices
  api --> coreServices
  sharedUi --> coreTheme
  sharedUi --> coreHooks
  coreProviders --> coreServices
  coreProviders --> coreMemory
  coreMemory --> coreServices
  coreMemory --> coreHooks
  screens -.gameplay only.-> sdk
```

## `src/core/` — the leaf foundation

`core/` is the catch-all home for every cross-cutting concern that isn't a feature and isn't a presentational component. Anything here can be imported by features, screens, components, or the root layout, but `core/` itself MUST NOT import from `features/*` or `app/*`.

```mermaid
flowchart LR
  subgraph core ["src/core/"]
    direction TB
    entry["entrySetup.ts<br/>(composition root)"]
    providers["providers/<br/>AppProviders"]
    services["services/<br/>apiClient · mmkv · queryClient"]
    hooks["hooks/<br/>useMemoryWarning · useScreenInsets"]
    orientation["orientation/<br/>useOrientation · orientation-store"]
    memory["memory/<br/>ResourceScope · useResourceScope"]
    audio["audio/<br/>singleton native piano sampler<br/>(ensurePianoSampler · usePianoSamplerStore)"]
    theme["theme/<br/>colors · spacing · fonts · breakpoints · themes"]
    utils["utils/<br/>crashReporting · delay<br/>eventEmitter · stringHelper · ..."]
  end

  entry -.imports.-> services
  providers -.imports.-> services
  providers -.imports.-> memory
  hooks -.imports.-> theme
```

| Subfolder            | Imported via        | Responsibility                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| -------------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `core/entrySetup.ts` | `@/core/entrySetup` | Composition root. Runs once at boot, wires axios hooks (`getAuthToken`, `onUnauthorized`), RevenueCat `getIapService().init()`, the IAP entitlements sync handler (`setIapEntitlementsSyncHandler`), and side-effect imports (gesture handler). The **only** file in `core/` allowed to import from `features/*`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `core/services/`     | `@services/*`       | Side-effect free transport layer: axios `apiClient`, MMKV adapter, React Query client, platform glue (`system-gesture-defer.ts` — app-wide iOS bottom-edge gesture deferral; `gameplay-keep-awake.ts` — keep-awake tag for immersive surfaces).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `core/providers/`    | `@core/providers/*` | `AppProviders` — the root provider tree (gesture handler · safe area · QueryClient · app-wide iOS gesture deferral).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `core/hooks/`        | `@hooks/*`          | Hooks not owned by a single feature (`useScreenInsets`, `useMemoryWarning`, `useKeepGameplayAwake`).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `core/orientation/`  | `@core/orientation` | Coordinated device orientation. Route-group layouts call `useOrientation`; the store resolves priority and issues one `lockAsync` per change. See [routing.md](/docs/routing.md#screen-orientation).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `core/memory/`       | `@core/memory/*`    | `ResourceScope` / `useResourceScope` for deterministic screen-lifetime disposal.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `core/audio/`        | `@core/audio`       | One process-wide piano sampler (`PianoSamplerLike`) via `ensurePianoSampler` — the iOS AVAudioEngine backend ([`NativePianoSampler`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/audio/engine/native/native-piano-sampler.ts), registered at boot from `entrySetup.ts`; see [audio-engine.md](/docs/audio-engine.md)). Android has no engine yet. [`useSoundFontSampler`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/keyboard/hooks/useSoundFontSampler.ts) subscribes through `usePianoSamplerStore` — screens do **not** dispose the sampler on unmount. Also the persisted shared mixer, the output route / speaker profile, and song previews. The service file stays type-only so it loads under `bun:test`. |
| `core/theme/`        | `@core/theme/*`     | Unistyles tokens consumed by `unistyles.ts` and every styled component.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `core/utils/`        | `@/core/utils/*`    | Generic, framework-agnostic helpers: Firebase Crashlytics + Sentry reporting fan-out (`crashReporting.ts`), date formatting, delay, app event emitter, string helpers, type guards. No feature knowledge.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |

## Dependency direction rules

- `app/*` may import from `@features/*/screens/*`, `@core/providers/*`, and `@/core/entrySetup` (side-effect import) only.
- `features/<x>` may import from:
  - its own folder
  - `@services`, `@hooks`, `@core/*`, `@components`
  - **another feature's `store.ts`** (read-only client state), e.g. `Profile` reads `useAuthStore`.
  - `@piano/sdk` (and only `@piano/sdk`) — for gameplay features that need engines, catalog, progression, etc.
- `features/<x>` MUST NOT import:
  - `app/*`
  - another feature's `screens/`, `components/`, or `api.ts`.
  - `@piano/<sub-package>` directly (use `@piano/sdk` re-exports). The SDK is the only public surface.
- `core/`, `components/` are leaves; they do not import from `features/*` or `@piano/*`.
  - **Exception:** `core/entrySetup.ts` is the composition root and _is_ allowed to import from `features/*` (auth store, monetization entitlement sync). Do not add new feature imports anywhere else in `core/`.
- `packages/@piano/*` MUST NOT import from `app/*`, `src/*`, `react`, or `react-native`. They are pure TypeScript libraries.
  - Workspace-internal dependencies between packages are governed by the graph in [monorepo.md](/docs/monorepo.md). `@piano/types` is the leaf, `@piano/sdk` is the root.

```mermaid
flowchart LR
  app --> screensFeatureA[features.A.screens]
  app --> screensFeatureB[features.B.screens]
  screensFeatureA --> sharedComponents[components]
  screensFeatureA --> aQueries[features.A.queries]
  screensFeatureA --> bStore[features.B.store]
  aQueries --> aApi[features.A.api]
  aQueries --> aStore[features.A.store]
  aApi --> apiClient[core.services.apiClient]
  aStore --> mmkv[core.services.mmkv]
  sharedComponents --> theme[core.theme]
  sharedComponents --> hooks[core.hooks]
```

## Feature anatomy

Every feature follows the same shape so newcomers can navigate by muscle memory.

```mermaid
flowchart LR
  subgraph featureFolder [features/&lt;name&gt;]
    typesNode["types.ts<br/>DTO + domain types"]
    mappersNode["mappers.ts<br/>DTO -> domain"]
    apiNode["api.ts<br/>fetch/mock fns"]
    queriesNode["queries.ts<br/>react-query hooks"]
    storeNode["store.ts<br/>zustand"]
    screensNode["screens/"]
    componentsNode["components/"]
  end
  apiNode --> typesNode
  mappersNode --> typesNode
  queriesNode --> apiNode
  queriesNode --> mappersNode
  queriesNode --> storeNode
  screensNode --> queriesNode
  screensNode --> storeNode
  screensNode --> componentsNode
```

### File responsibilities

| File          | Responsibility                                                                                            |
| ------------- | --------------------------------------------------------------------------------------------------------- |
| `types.ts`    | DTO interfaces (snake_case wire format) + domain interfaces (camelCase app types).                        |
| `api.ts`      | Pure async functions that return DTOs. No React. No mapping.                                              |
| `mappers.ts`  | Pure functions `toX(dto: XDto): X`. Easy to unit test.                                                    |
| `queries.ts`  | React Query hooks; the only place that combines `api` + `mappers`. Centralises caching + invalidation.    |
| `store.ts`    | Client-only state (UI flags, filters, persisted session). Never duplicates server state.                  |
| `screens/`    | Composition of components + hooks; rendered by route files. Defaults to `export const <Name>Screen = ...` |
| `components/` | Feature-local presentational components. Not exported to other features.                                  |

## Why this split

- **Routing is decoupled from screens.** Move a screen between routes by editing one re-export line. No prop drilling through layouts.
- **Server vs client state is explicit.** `queries.ts` owns server cache; `store.ts` owns client state. No `useEffect`-fetch-into-`useState` antipatterns.
- **DTO ↔ domain boundary** keeps server changes from leaking into every component. A wire change updates `types.ts` + `mappers.ts` only.
- **`core/` keeps the rest of the codebase honest.** Centralising apiClient/mmkv/queryClient/providers/theme means the dependency arrow always points _into_ core, never out — so refactors there can't accidentally pull in a feature.
- **Features are deletable.** Removing a feature is `rm -rf src/features/<x>` + delete its route files.

## Song catalog (app-level layers)

The song catalog is the first slice of the **app-level layered architecture**: top-level `src/domain` (entities, `I*` ports, pure policies, use cases, `CatalogFacade`), `src/data` (DTOs, mappers, caches, repositories, service layer) and `src/infra` (RN-bound adapters + the composition root) — shared by all features, not split per feature. The bundled `songs.json` is the default; Remote Config / a CDN override it when they publish a newer `version`, and MIDI beyond the first N pre-built songs downloads on demand. Full description, test fakes and publishing: [features/catalog.md](/docs/features/catalog.md); rules: the [clean-architecture skill](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/.cursor/skills/clean-architecture/SKILL.md).

The **monetization slice** is the second: the ads A/B arm (`mon_pkg`), the ad decisions (interstitial, FSN, App Open, Learn by stage, No Ads popup, banner), rewarded unlocks and the No Ads / VIP paywall products, behind `MonetizationFacade`. It reads the app's counters and song library through repositories and plays ads through the existing ads layer. `startMonetization()` builds it at app start and hands it the decisions wired so far; each feature asks it through a source hook ([ad-trigger-logic.md](/docs/ad-trigger-logic.md#monetization-slice-mon_pkg)).

Remote MIDI/BGM URLs are still indexed in [`src/core/sdk/catalog-asset-index.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/sdk/catalog-asset-index.ts) (refreshed on every projection) for [`HybridMidiRepository`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/sdk/adapters/hybrid-midi-repository.ts) and backing resolution. Songs removed from the catalog but owned by the user are kept in [`@piano/user-library`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/user-library/) with a frozen snapshot and merged back into the song list (`delisted: true`).

### User library (purchases)

Owned songs and subscription state live in [`@piano/user-library`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/user-library/) (`UserLibraryDocument` in MMKV per `userId`), not inside the catalog cache. [`ILibraryStorage`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/user-library/src/storage.ts) is cloud-ready — production uses [`HybridLibraryStorage`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/services/library/mmkv-library-storage.ts) (local-first; `sync()` is a stub until Firestore / API / iCloud lands). Login merges the guest partition into the account partition ([`onLibraryLogin`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/services/library/instance.ts)).

Lock resolution uses [`LockContext`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/user-library/src/lock-context.ts) (`isVip` + `ownedSongIds`) via [`getSongLockState`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/catalog/src/lock-rules.ts) **before** live config flags. `PlayerData.listUserSongIds` is dual-written during migration and will be deprecated once cloud sync ships.

### Media persistence

Remote MIDI, BGM, and preview bytes are stored under `FileSystem.cacheDirectory/media/` with an MMKV index ([`ExpoMediaStore`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/services/media-store/expo-media-store.ts)). MIDI goes through JS bytes (`write`); a BGM recording is downloaded natively straight to its file (`downloadToFile`). Song-list cover art uses [`ImageCache`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/components/ImageCache.tsx) in [`SongRow`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/songs/components/SongRow.tsx) — covers load on demand as rows render (expo-image disk + memory cache).

## App boot — who wires what

The UI hook `src/bootstrap/useBootstrapEntrySDK.ts` only forwards `start` to the app-lifecycle
store. `AppLifecycleFacade` and `StartAppLifecycle` own process initialization and lifecycle
transitions through injected ports; `AppStartupPolicy` is the single place that chooses startup
phases. Device bindings live in `infra/adapters` and `app-lifecycle-app-container.ts`.

A launch with onboarding incomplete keeps gameplay warmups, catalog sync, MIDI queue construction
and version prefetch behind **splash hidden + first FTUE screen committed**, then two frame
boundaries and idle. Returning launches initialize those services after the intro without waiting
for an onboarding event. The launch context is read from restored flags once per process; nothing
persists whether services have started. Foreground transitions refresh RC/recheck entitlements,
while repeated events and React remounts do not reinitialize SDKs. See
[App startup and lifecycle](/docs/features/app-lifecycle.md) for the task matrix and tests.

`src/bootstrap/entrySetup.ts` remains a pre-React side-effect import for platform registration,
error/performance reporting, audio factory/mixer binding, screen tracking and native splash cover.
It no longer starts catalog sync or constructs the MIDI queue at module evaluation.

### Boot performance

Cold start is measured, not just gated. `src/bootstrap/start-app-bootstrap.ts` runs essential boot
services (`crash`, `remote_config`, `iap`, `att`, `appsflyer`, plus returning-launch `haptics`) as a **guarded step**
(`boot-step.ts`: never throws, per-step timeout except ATT), so one failing service cannot skip
the rest or `fn_loading_end`. `boot-telemetry.ts` wraps each step in a Firebase Performance trace
(`boot_<step>`, plus `boot_total`), leaves Crashlytics breadcrumbs (`boot:<step>:<status>:<ms>`),
and builds the `boot_timing` analytics event (`boot-timeline.pure.ts`).

Firebase Performance is only reached through the `PerformanceService` port in
`src/core/perf/` (interface + registry + Firebase/no-op adapters + `FakePerformanceService`),
mirroring `src/core/iap`. Only `adapters/firebase-performance-service.ts` imports
`@react-native-firebase/perf` (a source-contract test enforces it). It maps 1:1 onto a future
`IPerformanceService` in `src/domain/ports` + an `src/infra` adapter. Collection has a Remote
Config kill switch, `perf_enabled` (default `true`; applies on the next launch). Pre-JS time
(process launch → JS entry) comes from Firebase Performance's automatic `_app_start` trace and
the `js_entry_ms` param.

The backend is installed in `src/bootstrap/perf-setup.ts` (called from `entrySetup.ts`; until then
`getPerformanceService()` is the no-op). It is Firebase Performance unless
`EXPO_PUBLIC_PERF_FIREBASE=0`. Swapping or adding a backend = one adapter under
`src/core/perf/adapters/` and one line there.

### Error reporting (Sentry, alongside Crashlytics)

`src/core/error-reporting/` mirrors `core/perf`: the `ErrorReportingService` port, a registry
(no-op until installed), a fake, and `adapters/sentry-error-reporting-service.ts` as the only
`@sentry/react-native` importer (enforced by its test). `src/bootstrap/error-reporting-setup.ts`
installs it first thing in `entrySetup.ts`; with an empty `EXPO_PUBLIC_SENTRY_DSN` it stays the
no-op, and it is disabled in `__DEV__`. `crashReporting.ts` fans every report, breadcrumb and
user id out to both Crashlytics and Sentry, so `AppErrorBoundary`, `CrashErrorReporter` and boot
telemetry need no changes. The root layout is wrapped through `wrapRoot`. Tracing is sampled at
30% with auto UI/stall tracing off (gameplay hot path). Metro uses `getSentryExpoConfig` for
debug IDs.

## Lazy modules — splash, onboarding, tutorial, app; preload next, offload on leave

Laziness is per **module**, not per screen. Four modules — `splash`, `onboarding`, `tutorial`,
`app` — are each one `import()` of a barrel under `src/core/navigation/modules/`, evaluated whole
(`memoLoader` in `src/core/navigation/groups.ts`: once, however many routes and preloads ask).
A route file renders its screen with `lazyRoute(appScreens.songs)`; that is a pick from the
already-loaded module, so no screen has a load of its own.

- **Preload next.** Each group layout mounts `<PreloadGroup next=…>`: onboarding loads the
  tutorial, the tutorial loads the app, the app layout holds the launch splash on its module
  (`warmupName="app-group"`) when the app is the first thing shown. The splash module is started
  at module load in `app/_layout.tsx` (`preloadGroup("splash")`) and renders nothing while it
  loads, because the native splash is still up. Preload evaluates modules; it never mounts them.
- **Hand-off.** `useOnboardingStore.complete()` and `useTutorialStore.complete()` go through
  `proceedWhenGroupPreloaded(next, …)`: immediate when the next module is ready (the normal
  case), otherwise at most `GROUP_PRELOAD_MAX_MS`. `LazyScreenFallback` (dark backdrop, never a
  blank frame) covers whatever is left.
- **Offload on leave.** `<GroupLifecycle group=…>` calls `offloadGroup` once the root
  `Stack.Protected` guard drops the group; `<OffloadGroupWhen group="splash" done=…>` does the
  same once the splash has hidden, and the root layout unmounts the launch splash itself at that
  point (a component that renders `null` still keeps its hooks — the decoded key art — alive). Owners register what to give back with
  `onGroupOffload(group, release)` (references only, Skia frees the images).
- **Limits.** Metro's release runtime has no module eviction and Hermes bytecode is mmap'd, so a
  left module frees its runtime resources (caches, mounted trees), not its evaluated module
  scope. Module eviction would need a patched `metro-runtime` and a build-time exclusive-module
  manifest; it is not implemented.
- **Cost of the unit.** The app module evaluates every app screen together, gameplay included,
  in one go (during the tutorial, or under the splash on a returning launch) — measure that
  stall before adding more to a barrel.

## IAP / RevenueCat — adapter-only third-party boundary

`react-native-purchases` is owned **exclusively** by [`src/core/iap/adapters/revenuecat-iap-service.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/iap/adapters/revenuecat-iap-service.ts). Features and UI never import the native SDK.

| Layer                                                                                                                                                                   | API                                                               | Knows Purchases?    |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | ------------------- |
| Features / screens                                                                                                                                                      | `getIapService()` + domain types from `@core/iap`                 | No                  |
| [`iap-service-registry.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/iap/iap-service-registry.ts)              | Builds `RevenueCatIapService` on first `getIapService()` call     | No                  |
| [`revenuecat-iap-service.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/iap/adapters/revenuecat-iap-service.ts) | `init()` once from `entrySetup.ts`; other methods await readiness | **Yes — only here** |

Boot rules:

- `src/bootstrap/start-app-bootstrap.ts`, reached through the app lifecycle facade, calls `getIapService().init()` once per process (`Purchases.configure()` + listener + initial entitlement sync). Feature code never calls `init()`.
- Splash identity ([`resolveFirstLaunchIdentity`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/auth/fresh-install.ts)) only sets MMKV flags — no IAP calls on the splash critical path. Receipt restore for reinstalls runs idle after splash via [`schedulePostSplashReinstallRestore`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/auth/fresh-install.ts).
- Offerings are deduped in-flight and cached for five minutes so paywall hooks and purchase flows do not each hit the network.
- Mid-session entitlement pushes (`CustomerInfoUpdateListener`) are mapped to domain `IapEntitlements` in the adapter, then handed to the composition-root handler wired in `entrySetup.ts` (entitlements store + ad-gate cache).
- Attribution (AppsFlyer) goes through `@core/attribution` (`getAttributionService()`, port + adapter + noop/fake like `@core/iap`); ads go through `@core/ads`
- Meta app events (Facebook SDK, `react-native-fbsdk-next`) go through `@core/meta-events` (`getMetaAppEvents()`, port + one adapter + noop/fake + registry; `sim` → noop): the ad path's `AdImpression` and the ATT answer. Install / app activation are logged by the SDK itself.
  (`getAdsService()`); subscriptions go through `@core/iap` only.

## Gameplay clock — two-clock tick model

Falling tiles use a **Shared Tile Buffer + Sliding Cursor** (flat `SharedTileLayout[]` + `tileCursorSv` advanced on the UI thread from `tickSv`) so the atlas pool only binds the active window — see [features/piano.md](/docs/features/piano.md) (`<TileFalling>` section). Render cost stays one lane `translateY`; judgement uses a separate `@rhythm/engine` `RhythmCursor` / `headIdxSv`.

The PlayScreen rendering stack (`<TileFalling>`, `<GameplayHeaderBackground>`, every overlay slot pool) reads its time from a single `tickSv: SharedValue<number>` that advances on the UI thread. Driving that SharedValue cleanly while still letting the JS-owned `RhythmEngine` + the native sampler schedule notes requires a **two-clock split** owned by `@rhythm/engine`'s [`useRhythmEngine`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/rhythm-engine/src/react/use-rhythm-engine.ts) (consumed via [`useMagicJudgement`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/piano/hooks/useMagicJudgement.ts)):

```mermaid
flowchart LR
  subgraph AudioThread [Audio render thread]
    Pump["sampler.createClockPump()<br/>NativeClockPump (iOS)<br/>pulse every 30ms"]
  end

  subgraph JSThread [JS thread - pulse cadence ~50 Hz]
    Runner[useMagicGameplay → PlayController]
    Seq["RhythmSequencer.pulse()<br/>lookahead: rhythm / melody-autoplay notes<br/>at exact engine-clock times"]
    Anchor["onPulse → step<br/>controller.tickFrame() + sweepMissedGroups<br/>publishes clock snapshot, writes headIdxSv"]
    Runner --> Seq
    Seq --> Anchor
  end

  Pump -->|pulse| Seq

  Clock[("GameplayClockChannel<br/>fixed-type Synchronizable cells + seqlock<br/>anchorTick, isRunning, ticksPerSecond,<br/>seed, holdAtTick")]
  Visual[("VisualClockChannel<br/>lane tick + multiplier (UI → JS)")]

  subgraph UIThread [UI thread - frame cadence 60-120 Hz]
    Frame["useFrameCallback worklet<br/>resolveDisplayTick(getDirty())"]
    Tick[tickSv]
    Frame --> Tick
  end

  Anchor -->|"setBlocking (write-on-event)"| Clock
  Clock -->|"getDirty (read-on-frame)"| Frame
  Frame -->|"setDirty (every frame)"| Visual
  Visual -->|"getDirty (judgement)"| Anchor
  Tick --> Renderers["TileFalling translateY,<br/>GameplayHeaderBackground progress,<br/>derived particle positions"]
```

- **Song sequencer / audio-driven pulse.** `PlayController` owns a [`RhythmSequencer`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/rhythm-engine/src/sequencer/rhythm-sequencer.ts) — the single song clock. Its [`Transport`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/rhythm-engine/src/sequencer/transport.ts) is the only mapping between song ticks and the sampler's audio clock (`sampler.getCurrentTime()` — the render-timeline clock of the iOS native engine). The pump comes from `sampler.createClockPump()`: [`NativeClockPump`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/audio/engine/native/native-clock-pump.ts) forwards the module's \~30 ms clock pulse ([audio-engine.md](/docs/audio-engine.md)); each pulse the sequencer hands the sampler every note due inside a 150 ms lookahead horizon with its **exact** start and release audio time (`NoteScheduleTrack`). There is **no gameplay `setInterval`** and no release `setTimeout` — pulse jitter never reaches the speaker. Pause cancels voices scheduled but not yet sounding and rewinds the lane so resume re-schedules them.
- **JS thread / pulse cadence (\~50 Hz).** `useRhythmEngine` subscribes its anchor `step` to `controller.sequencer.onPulse`; the step calls `controller.tickFrame()` — which advances the `RhythmEngine` (groups, pedal, game end) from the transport tick — then runs `sweepMissedGroups` over the cursor before publishing the just-stepped tick into the shared clock channel and the new `headIdxSv`. Audio scheduling stays on the JS thread; the native module lands each timestamped note on its exact render sample.
- **Tempo map (compile time).** Multi-tempo MIDI is linearized by the MIDI compiler (`chartJsonToChart` / `midiToChart`): notes stay in musical beats in `ChartJson` (plus an optional `tempo_map`), and are converted beats → seconds → **linear** song ticks at one constant `ticksPerSecond`. The runtime clock, tile scroll, and judgement windows therefore never see a tempo change. See [`timeline/tempo-map.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/rhythm-engine/src/timeline/tempo-map.ts).
- **Shared clock channel.** Anchor tick, run state, and tempo cross runtimes through [`createGameplayClockChannel`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/rhythm-engine/src/sync/gameplay-clock-channel.ts) — fixed-type `Synchronizable` number cells from `react-native-worklets` (C++ memory both runtimes address directly) guarded by a seqlock, so a read still sees one publish; only the tempo curve (an object) goes through the serializing `setBlocking`, and only when it changes. Serializing the whole snapshot object per pulse cost 10–24 ms on iPad. A `SharedValue` written on the RN runtime only reaches the UI runtime on the next Reanimated batch (up to one frame of staleness on the note-timing path); a Synchronizable write is visible immediately. The anchor loop is the sole writer and short-circuits when nothing changed, so a paused song never churns the channel. Reads use `getDirty()` — never blocking, at worst one publish behind, which the extrapolation window already absorbs.
- **UI thread / frame cadence (60–120 Hz).** A single `useFrameCallback` worklet inside the same hook does one non-blocking snapshot read and calls [`resolveDisplayTick`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/rhythm-engine/src/sync/gameplay-clock.ts). The AUDIO clock is the master and the lane is disciplined toward it (see [features/piano.md — Gameplay clock](/docs/features/piano.md#gameplay-clock)): it integrates frame deltas along the tempo curve, so it is smooth between the 20 ms anchors, and its speed is nudged to close the low-passed offset to the extrapolated audio tick; it never moves backward and audio is never moved for it while playing. The worklet mirrors the tick it showed into a UI→JS [`VisualClockChannel`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/rhythm-engine/src/sync/visual-clock-channel.ts) (lock-free fixed-type `Synchronizable` cells). Taps and releases are judged at the lane tick stamped on the UI thread (within a few ms of audio); the anchor step's own judgements — miss sweep, hold completion, auto-pause — run on the audio tick, so a UI hitch never delays them. The worklet is gated with Reanimated `setActive` via `setFrameActive`, driven by `GameStateMachine.stateChanged` → `isPlaying()` — **not** React `setState`. The judgement cursor lives in `cursorRef` only; arming never mirrors it into React state.
- **Press mailbox (wait-mode pause vs. an on-time tap).** A key press is stamped on the UI thread and then crosses to JS (`scheduleOnRN`) — one to two frames plus JS queue time — while the wait-mode auto-pause is decided on the audio pulse (every 16–20 ms) and could run first, freezing the song for a tap already on its way (the tap then had to resume it). The touch-down worklet therefore also posts `(note, tick)` into [`createPressMailbox`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/rhythm-engine/src/driver/press-mailbox.ts) before the hop (four fixed-type `Synchronizable` slots + a seqlock; the keyboard finds it through `judgementTickSv` with `pressMailboxOf`, like the game-state block). `registerTap` acks the press first thing; the anchor step holds the auto-pause **and the miss sweep** while a posted, unacked press is at most `IN_FLIGHT_PRESS_MAX_MS` (100 ms) old. Pitch is not compared — a wrong key delays the pause by one hop until it is acked; a press that never reaches `registerTap` stops holding after the age cap.
- **Pause / resume.** Manual and auto-pause flip the engine state machine; `syncIsRunning` publishes `isRunning: 0`, freezes `tickSv` (and writes the frozen tick to the lane mirror) and deactivates the frame callback with zero PlayScreenBody commits. The controller re-aligns the song clock onto the lane tick at every `pause()` and `resume()` (`PlayController.setDisplayTickSource` / `realignTo`), and the hook seeds the lane on start / resume. HUD play/pause leaves subscribe via `subscribeManualTransport` separately.

Why this is faster than the previous single-clock rAF loop:

- JS wake-ups follow the audio pump (\~50 Hz) instead of the 60–120 Hz frame rate, and carry no audio-timing responsibility (notes are pre-scheduled).
- `tickSv` is updated entirely from the UI thread; no per-frame JS→UI bridge writes.
- The UI worklet would run every frame regardless (Reanimated already wakes the UI runtime for any SharedValue subscriber), so the interpolation cost is essentially free CPU.

Rules for code in this area:

- **Never** mutate `tickSv` from the JS thread — call `controller.tickFrame()` through the anchor loop and let the worklet extrapolate.
- **Never** schedule gameplay audio with `setTimeout` / `setInterval` — add a `SequencerTrack` to the controller's `RhythmSequencer` and pass exact audio times (`playNote(…, atTime)`, `releaseVoice(voice, atTime)`).
- **Never** include `tickSv` in a hook dep array; it's a stable Reanimated handle.
- New tick-driven UI must read from `tickSv` via `useDerivedValue` / `useAnimatedStyle`, not subscribe via a re-render.
- The pure helper `computeInterpolatedTick` is unit-tested in [`packages/rhythm-engine/tests/tick-driver-utils.test.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/rhythm-engine/tests/tick-driver-utils.test.ts) — extend the test, don't open-code variations of the clamp / pause logic.

See also [.cursor/skills/piano-simulation-screen/SKILL.md](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/.cursor/skills/piano-simulation-screen/SKILL.md#performance-conventions-dont-break-these) for the rendering-side conventions that depend on this contract.

## Local Expo modules (`modules/`)

Platform APIs that neither React Native nor Expo expose are bridged through **local Expo modules** under [`modules/`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/). They autolink on `expo prebuild` (same mechanism as `expo-camera`), live inside the host repo (not under `packages/*`), and are **not** published to npm.

| Module                                                                                                                                           | Platforms                                    | Purpose                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| ------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`screen-gesture-defer`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/screen-gesture-defer/) | iOS                                          | App-wide bottom system gesture deferral (Home / app switcher) via `preferredScreenEdgesDeferringSystemGestures = .bottom`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| [`perf-hud`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/perf-hud/)                         | iOS                                          | Always-on draggable SwiftUI overlay (outside the RN tree): UI FPS (main-thread `CADisplayLink` ticks), DRAW FPS / JANK (frames the busiest `CAMetalLayer` — the Skia gameplay canvas — actually presented per second, and late (> 1.5× refresh) or dropped presents; [`PerfHudPresentTracker.swift`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/perf-hud/ios/PerfHudPresentTracker.swift) swizzles `-[CAMetalLayer nextDrawable]` while the HUD is shown; the simulator counts rendered drawables instead), JS FPS (Hermes `requestAnimationFrame` → sync JSI `reportJsFps`, clamped 0…60), RAM, CPU %. Bootstrapped from [`AppProviders`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/providers/AppProviders.tsx) via [`perf-hud.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/services/perf-hud.ts). |
| [`piano-audio-engine`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/piano-audio-engine/)     | iOS (Nitro HybridObject, not an Expo module) | AVAudioEngine piano backend: a TinySoundFont sampler node (`AVAudioSourceNode`, per-voice envelope / tone / velocity curve) → group inserts → EQ → Reverb2 / delay sends → limiter, sample-accurate note scheduling on the render clock, a \~30 ms clock pulse (callback + shared-memory mailbox), and diagnostics (DSP load, xruns, peak / RMS). Wrapped by [`NativePianoSampler`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/audio/engine/native/native-piano-sampler.ts); the app's only piano engine — see [audio-engine.md](/docs/audio-engine.md). Stays on Nitro 0.37.2; that release has no SwiftPM manifest, so this module is not part of the SwiftPM prep.                                                                                                                                                                                                                                     |
| [`sdk-crash-guards`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/sdk-crash-guards/)         | iOS                                          | Guards against known faults in third-party SDKs, installed from `+load` before `main`; native only, so it has no `index.ts`. [`GULMutableDictionaryNilKeyGuard.m`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/sdk-crash-guards/ios/GULMutableDictionaryNilKeyGuard.m) drops writes with a nil key to GoogleUtilities' `GULMutableDictionary`. Such a write throws on the dictionary's private queue, where no caller can catch it. On 2026-09-29 a Firebase Analytics server response caused one and aborted every iOS app about 10 s after launch ([firebase-ios-sdk#16728](https://github.com/firebase/firebase-ios-sdk/issues/16728)). Its contract test runs in `test:app:config`. It deliberately has no `Package.swift`: a static SwiftPM target dead-strips `+load` unless the app force-loads the object file. CocoaPods static linkage keeps the swizzle.                                                    |

Typical layout per module:

```text
modules/<name>/
  expo-module.config.json   # autolinking — platforms + native class names
  Package.swift             # SwiftPM prep; CocoaPods ignores it. Not every module has one.
  index.ts                  # typed JS facade (Platform.OS guards)
  ios/
    <Name>Module.podspec    # required — without this, autolinking search finds the module but resolve skips it
    *.swift
  android/                  # optional Kotlin + build.gradle
```

`tracking-authorization`, `screen-gesture-defer`, `perf-hud`, and `fullscreen-native-ad` each ship a `Package.swift` whose library product matches the pod name. `fullscreen-native-ad` depends on Google's SwiftPM package at 13.10.0, the same `Google-Mobile-Ads-SDK` pin as `react-native-google-mobile-ads` 17.4.0. Prebuild still uses CocoaPods; these manifests are not linked until SwiftPM autolinking is turned on. `@react-native-masked-view/masked-view` stays: `TextOutline`, `ResultStarBadge`, `ComingSoon`, and `SongListEdgeFade` still render through it, and `expo-router` lists it as a peer.

Adding or changing native code requires a **dev-client rebuild** (`expo prebuild` + `expo run:ios` / EAS). It does **not** hot-reload through Metro and does **not** work in Expo Go.

Config plugins in [`plugins/`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/plugins/) (e.g. [`withSplashBackground`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/plugins/withSplashBackground.ts), [`withIosInAppPurchase`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/plugins/withIosInAppPurchase.ts)) are the alternative when the change is a one-time project-file mutation rather than a runtime JS ↔ native API. `withIosInAppPurchase` links `StoreKit.framework` and enables Xcode's **In-App Purchase** capability (`com.apple.InAppPurchase`) on every prebuild — IAP is not an entitlements-plist key, so a hand-added Signing & Capabilities entry would be wiped when `ios/` is regenerated. [`withAlternateAppIcons`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/plugins/withAlternateAppIcons.ts) does the same for the App Store icon test: it adds the alternate `AppIcon-<name>` sets from `assets/app-icons/` to the asset catalog and compiles them into the app target, with no runtime code ([ci-cd.md](/docs/ci-cd.md#3-app-icon-test-product-page-optimization)).

## Lists

- **A list that can outgrow a screen, or holds heavy cards → Legend List v3
  (`@legendapp/list`) with `recycleItems`.** A row that scrolls off is re-bound to the next
  item instead of being unmounted and mounted again. The Song List is the reference
  ([songs.md](/docs/features/songs.md#the-list-legend-list-v3)); leaderboards and mission lists should
  start on it too.
- **A small, fixed list (≲ 10 items: plans, suggestions, settings rows, tabs) → `ScrollView` +
  `.map`.** Recycling buys nothing there, and entering animations or per-item `onLayout`
  (e.g. `useListOnScreenIds`) work as they are.
- **Recycled cells must not keep the previous item's state.** Anything a cell reads once at
  mount (`useState` initialisers, shared values, refs) is re-derived when the item's key
  changes — reset it in an effect keyed on the id, or keep the value together with the key it
  belongs to (`SongCardReveal`, `SongTitleMarquee`). Give `ImageCache` a `recyclingKey`.
- **Legend List v3 specifics:**
  - import `LegendList` from `@legendapp/list/react-native`, or `AnimatedLegendList` from
    `@legendapp/list/reanimated` (v3 has no root export, and `createAnimatedComponent` does not
    work);
  - recycling is opt-in (`recycleItems`), and `getItemType` separates cell kinds;
  - `getFixedItemSize` skips measuring when rows have a known height; there is no list `gap`,
    so put the gap in the cell;
  - `maintainVisibleContentPosition` anchors on size changes by default;
  - a Reanimated offset comes from `sharedValues={{ scrollOffset }}`, not a worklet `onScroll`;
  - `renderItem` must be an inline callback, not a component that calls hooks.

## System gesture deferral (app-wide)

On iOS, an accidental upward swipe from the bottom edge normally fires the Home / multitasking gesture immediately. Magic Piano enables bottom-edge deferral **once for the whole app** at bootstrap so the **first** bottom-edge swipe is handled by the app and the system gesture needs a **second** deliberate swipe — not only on play / learn / keyboard routes.

```mermaid
sequenceDiagram
  participant Providers as AppProviders
  participant Service as setGameplayGestureDeferralEnabled
  participant Native as modules/screen-gesture-defer
  participant UIKit as Root UIViewController

  Providers->>Service: mount → enabled = true
  Service->>Native: setBottomEdgeGestureDeferred(true)
  Native->>UIKit: preferredScreenEdgesDeferringSystemGestures = .bottom
  Providers->>Service: unmount → enabled = false
  Service->>Native: setBottomEdgeGestureDeferred(false)
  Native->>UIKit: restore default edges + setNeedsUpdateOfScreenEdgesDeferringSystemGestures()
```

| Layer     | File                                                                                                                                                                                                 | Role                                                                                   |
| --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| Bootstrap | [`AppProviders.tsx`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/providers/AppProviders.tsx)                                                   | `useEffect` — enable on mount, disable on unmount                                      |
| Service   | [`system-gesture-defer.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/services/system-gesture-defer.ts)                                      | Platform branch; Android / web no-op today                                             |
| Native    | [`ScreenGestureDeferController.swift`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/screen-gesture-defer/ios/ScreenGestureDeferController.swift) | Swizzles the key-window root VC's `preferredScreenEdgesDeferringSystemGestures` getter |

Do **not** toggle deferral from individual screens. Immersive piano surfaces instead call [`useKeepGameplayAwake`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/hooks/useKeepGameplayAwake.ts) so the screen does not auto-lock mid-session.

**Android:** out of scope for now. `View.setSystemGestureExclusionRects` does not cover the reserved bottom Home/Recents strip; hiding the gesture-nav bar would need `react-native-edge-to-edge` or custom Kotlin. The service is written so a future Android branch can be added without touching callers.

**Note:** `autoHideHomeIndicator: true` on the `play` / `play-result` routes in [`app/(app)/_layout.tsx`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/app/\(app\)/_layout.tsx) is **not** a supported `@react-navigation/native-stack` option — it is silently ignored. Home-indicator hiding is separate from edge deferral and is not implemented today.

## Per-song asset declaration

There is no `.config.json` artifact. Production catalog songs are synced at build time via `bun run catalog:sync-sheet` into [`src/assets/config/songs.json`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/assets/config/songs.json) and [`src/assets/charts/`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/assets/charts/) (sheet MIDI is downloaded in memory and converted to offline `ChartJson` — raw `.mid` is not stored under assets). [`src/assets/charts/manifest.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/assets/charts/manifest.ts) (generated by `convert-charts`) exposes a `ChartAssetName` union + `chartAssets` map, and [`src/core/sdk/song-assets.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/sdk/song-assets.ts) (gitignored, generated) indexes those modules per catalog id. Gameplay loads charts via [`loadGameplayChart`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/sdk/gameplay-chart.ts); [`HybridMidiRepository`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/sdk/adapters/hybrid-midi-repository.ts) only resolves remote MIDI for delisted owned snapshots.

FTUE tutorial charts are **separate keys** from catalog gameplay: [`src/assets/tutorial/charts/manifest.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/assets/tutorial/charts/manifest.ts) (generated by `charts:convert-tutorial` from the committed [`twinkletwinklelittlestar_tutorial.mid`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/assets/tutorial/twinkletwinklelittlestar_tutorial.mid) source, which stays on disk for the converter and tests but is not bundled — `scripts/assets-manifest/config.ts` gives the tutorial folder `excludeExtensions: ["mid"]`) bundles offline `ChartJson` for the gameplay `fileName` stem `twinkletwinklelittlestar_tutorial`; [`tutorial-song-assets.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/tutorial/tutorial-song-assets.ts) maps those keys to chart modules and [`gameplay-chart.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/sdk/gameplay-chart.ts) falls back to them when catalog lookup misses. The excerpts the console's `tutorial_song` names for the Instant songs (`APT_RoseBrunoMars_tutorial`, `DanceMonkey_TonesAndI_tutorial`, `FurElise_Beethoven_tutorial`, `NoBatidao_ZXKAI_tutorial`, `NoBatidao_ZXKAI_tutorial_new`) are committed next to them under their CDN file names and converted the same way; a console entry whose URL ends in one of those file names plays the bundled chart without a download ([`bundledTutorialExcerpt`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/tutorial/tutorial-gameplay-song.ts)), any other is fetched. Twinkle Twinkle Little Star is the stand-in for every slot the console leaves unusable. Each song carries its own `coverAssetModule` in [`tutorial-gameplay-song.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/tutorial/tutorial-gameplay-song.ts) (Twinkle's `tutorialAssets.TwinkleTwinkleLittleStar` from the tutorial manifest, a console song's catalog thumbnail) — `TutorialGameplayScreen` passes `tutorialSong.coverAssetModule` on. First-run song gameplay runs on Game Mode's own gameplay: `TutorialSongSurface` → `TutorialSongGameplayPhase` mounts `PlayScreenGameplayGroup` (`PlayGameCanvas` + `MultiplierAwarePianoKeyboard`) under `GameplayThemeTierProvider`, driven by `useTutorialSongSession` (bundled offline chart via `loadGameplayChart`, countdown, judgement — still no `(app)` routes). Score, the x2–x5 badge (`useGameplayHudBridge`), per-lane points and every tier effect follow the streak as in Game Mode; the tutorial adds only its hand guide on top. The first-run tutorial flow lives in [`src/features/tutorial/`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/tutorial/).

```ts
// src/features/tutorial/tutorial-song-assets.ts — maps fileName → bundled ChartJson
getTutorialSongAsset("twinkletwinklelittlestar_tutorial") // → tutorialChartAssets.twinkletwinklelittlestar_tutorial
```

Everything else — BPM, duration, `ticksPerSecond`, time-signature, midi end-tick, melody / rhythm split — is derived offline when running catalog sync / `charts:convert-tutorial` (`parseMidi` → `serializeChart`). Production MIDIs name their tracks `melody`, `rhythm`, and `segment` (plus optional `pedal` / `sustain`); [`splitMelodyAndRhythmFromParsed`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/rhythm-engine/src/chart/track-roles.ts) picks the named stems (excluding the segment marker and pedal track from playback) and falls back to the legacy heuristic for older files. Sustain windows prefer MIDI CC64 when present; otherwise a named pedal track maps each note's on→off duration to a pedal-down window (pitch ignored) ([`extractPedalSpans`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/rhythm-engine/src/chart/pedal.ts)). The `segment` marker track is parsed into `chart.segments` for tooling/visualizer use, but **free-tier part gating** in PlayScreen reads the bundled catalog instead: sheet **Section 1/2/3** MIDI converted to section charts under `src/assets/charts/` or legacy time-based `segments` in `songs.json` ([`catalog-segmentation.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/catalog/catalog-segmentation.ts), [`buildSongSegmentPlan`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/piano/parse-song-segment-plan.ts)). To ship a new song, update the Google Sheet and run `catalog:sync-sheet`; add tutorial MIDI under `src/assets/tutorial/`, register the `fileName` in [`tutorial-gameplay-song.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/tutorial/tutorial-gameplay-song.ts), then `bun run charts:convert-tutorial` (and `assets:sync` if you added bitmaps).

The gameplay screen no longer draws a night-sky backdrop: `NightSkyBackground`, `MultiplierAwareNightSky` and their `star-background` / `smoke-background` bitmaps were removed as dead code (see the note in `PlayScreen.game-canvas.test.ts`). `NIGHT_SKY_BACKGROUND_ENABLED` in `night-sky-background-enabled.ts` is the only leftover flag.

The previous "purple-smoke being sucked in" backdrop, [`<EnergyGradientBackground>`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/piano/components/EnergyGradientBackground.tsx) and its multiplier-aware wrapper, is **parked behind a comment in `PlayScreen`** for one-step re-enable — the imports, the `useEnergyShared` SV plumbing, and the JSX block are all commented in place. Nothing in either component has been deleted.

> **Authoring tool — out of band.** The MIDI visualizer (`bun run midi:viz`) is a developer tool that still includes `analyzeTrack` and a song-config builder, but its output is **not consumed by the host app**; the runtime path described above ignores any pre-computed JSON. The analyzer subpath export (`@piano/midi/analyzer`) is build-time-only and does not ship with the runtime bundle.

## Concrete example — sign-in dependency chain

```mermaid
flowchart LR
  signInRoute["app/(auth)/sign-in.tsx"] --> signInScreen["SignInScreen"]
  signInScreen --> authForm["AuthForm"]
  signInScreen --> useSignInMutation
  useSignInMutation --> signInRequest["signInRequest()"]
  useSignInMutation --> toSession
  useSignInMutation --> useAuthStore
  signInRequest --> apiClient["core/services/apiClient"]
  toSession --> sessionDto[SessionDto]
  useAuthStore --> mmkvStorage["core/services/mmkv"]
  authForm --> primaryButton[PrimaryButton]
```

See [features/auth.md](/docs/features/auth.md) for the full contract.

***

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