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

# Magic Piano — Technical Docs

Living documentation for the Magic Piano React Native app. All diagrams use [Mermaid](https://mermaid.js.org/) and render natively in GitHub, Cursor, VS Code (with the Markdown Preview Mermaid extension), and most documentation sites.

## Stack at a glance

| Layer            | Tool                                                                     |
| ---------------- | ------------------------------------------------------------------------ |
| Runtime          | Expo SDK 56 + React Native 0.85                                          |
| Language         | TypeScript 6 (`strict`)                                                  |
| Routing          | `expo-router` (file-based)                                               |
| Client state     | `zustand` + `react-native-mmkv` persist                                  |
| Server state     | `@tanstack/react-query`                                                  |
| Styling          | `react-native-unistyles` (themed)                                        |
| Images           | `expo-image` via `<ImageCache>`                                          |
| Audio / gameplay | native `piano-audio-engine` module (iOS) + `@piano/*` workspace packages |
| Haptics          | `react-native-pulsar` behind a swappable `IHapticEngine` adapter         |
| Monorepo         | Bun workspaces + Turborepo (`packages/*`) + `tsup` per package           |
| Lint / format    | `biome`                                                                  |

## Repo layout

```mermaid
flowchart LR
  subgraph repo [magic_piano repo]
    direction TB
    appHost["app/ + src/<br/>Expo app (host)"]
    modules["modules/<br/>local Expo modules"]
    pkgs["packages/*<br/>@piano/* workspace packages"]
  end
  appHost --> modules
  appHost -->|imports facade| sdk["@piano/sdk"]
  sdk --> rest["@piano/{ads · analytics · catalog · core ·<br/>gameplay-{learn,magic,zen} · keyboard · midi ·<br/>network · player-data · progression · types}"]
```

The Expo app stays at the repo root (no `apps/mobile`). Bun resolves `@piano/*` via workspace symlinks, Metro picks them up via `watchFolders: [packages]`, and Turborepo orchestrates the 14 packages' `build` / `typecheck` / `test` / `lint` tasks. See [monorepo.md](/docs/monorepo.md).

## App source layout

```mermaid
flowchart LR
  app["app/<br/>expo-router routes<br/>(re-exports only)"] --> src["src/"]

  subgraph srcLayout ["src/"]
    direction TB
    features["features/*<br/>auth · catalog · onboarding · songs · tracks · home · piano"]
    components["components/<br/>Screen · Text · PrimaryButton · ImageCache"]
    core["core/<br/>services · providers · hooks · memory · theme"]
    assets["assets/<br/>fonts · images · samples"]
  end

  src --> features
  src --> components
  src --> core
  src --> assets

  features --> components
  features --> core
  components --> core
  features -.gameplay only.-> sdkPkg["@piano/sdk"]
```

### `src/core/` zoom-in

```mermaid
flowchart TB
  subgraph core ["src/core/"]
    direction LR
    entry["entrySetup.ts<br/>(boot-time side effects)"]
    providers["providers/<br/>AppProviders.tsx"]
    services["services/<br/>apiClient.ts<br/>mmkv.ts<br/>queryClient.ts<br/>system-gesture-defer.ts<br/>gameplay-keep-awake.ts<br/>haptics/"]
    hooks["hooks/<br/>useScreenInsets.ts<br/>useMemoryWarning.ts<br/>useKeepGameplayAwake.ts"]
    orientation["orientation/<br/>useOrientation.ts<br/>orientation-store.ts"]
    memory["memory/<br/>disposable.ts<br/>release-memory-pressure.ts"]
    audio["audio/<br/>pianoSamplerService.ts<br/>pianoSamplerStore.ts<br/>defaultSamplerFactory.ts"]
    theme["theme/<br/>colors · spacing · fonts<br/>breakpoints · themes"]
    utils["utils/<br/>crashReporting<br/>delay · eventEmitter<br/>stringHelper · hasValidStringProp<br/>gestureHandler"]
  end

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

`core/` is the leaf foundation: it can be imported by anything, but it MUST NOT import from `features/` or `app/`. It exists to give every cross-cutting concern (HTTP, storage, query cache, providers, hooks, theme, memory management, generic utilities) a single home.

The one **deliberate exception** is `core/entrySetup.ts` — the composition root. It runs once at app boot (imported as a side effect from the top of `app/_layout.tsx`) and is the single place allowed to wire `core/services/*` to feature stores (e.g. `useAuthStore`, `performSignOut`). Treat it as a bootstrap file, not as part of the leaf foundation.

### Haptics service (`core/services/haptics/`)

A port-and-adapter wrapper around `react-native-pulsar`. Consumers only ever depend on the semantic intent vocabulary (`Haptics.play("pianoKeyPress")`) — never on Pulsar preset names — so the library can be swapped (Expo Haptics, native `Vibration`, future libs) by writing one new file under `adapters/`. The active adapter is selected by the lazy factory in
[`app-lifecycle-app-container.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/infra/container/app-lifecycle-app-container.ts) and warmed
by the `haptics` lifecycle action. [`AppStartupPolicy`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/domain/policies/app-startup-policy.ts)
starts it after the splash and first FTUE screen on an onboarding launch, or after the intro under
the splash on a returning launch. It runs once per process; UI remounts do not rebind the engine.
Before initialization (and in unit tests), `Haptics` uses a silent no-op adapter. See
[App startup and lifecycle](/docs/features/app-lifecycle.md).

The Pulsar adapter applies two boot-time policies inside its constructor (see [src/core/services/haptics/adapters/pulsar.ts](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/services/haptics/adapters/pulsar.ts)): it disables the audio side of Core Haptics presets (`Settings.enableSound(false)`, development builds only, and already called by boot before the app-open chime loads: `silencePulsarSound`) so play / game surfaces stay haptic-only — the sampler and backing track own the audio mix — and it gates the engine on `Settings.getHapticsSupportLevel()` so devices without Core Haptics treat every `Haptics.play(...)` as a no-op. `setEnabled(true)` is coerced to off on unsupported hardware so a future settings toggle can't re-arm a silent device.

The intent vocabulary itself lives in [src/core/services/haptics/types.ts](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/services/haptics/types.ts), with the per-intent rationale for each Pulsar preset in `adapters/pulsar-intent-map.ts`. Two of them carry a rule worth knowing outside those files: **`pianoKeyPress`** (`wisp`, Pulsar's faintest single tap) fires on every key press on Learn and Free mode — a key plays nothing on release — and is rate-limited by [`throttle.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/services/haptics/throttle.ts); Game Mode's Perfect hit (the tutorial song's too) plays **`perfectTap`** (`push`, twice the wisp with the same soft fade, throttled the same way) and the tutorial drills' Perfect plays `noteHitPerfect` (`chirp`); the hold rumble is 0.325 (`HOLD_DEFAULT_AMPLITUDE` in `adapters/pulsar.ts`); and **`error`** (`buzz`, "unmistakable hard rejection") is Learn Mode's wrong-note buzz — deliberately above the key tick in weight and different in character, never throttled, so every judged miss lands (see `src/features/learn/hooks/learn-session-haptics.ts`, which picks the ONE intent a session transition earned so a miss that also costs a heart is felt once).

```ts
import { Haptics } from '@services/haptics';

Haptics.play('pianoKeyPress');     // UI / gameplay surfaces
Haptics.setEnabled(false);          // master toggle
// Prefer lifecycle-owned `Haptics.preload(HAPTIC_INTENTS)` — only
// call preload from a screen if you add intents after boot.
Haptics.preload(['noteHitPerfect', 'noteHitGood']);
```

Adding a new intent: append it to `HapticIntent` in [src/core/services/haptics/types.ts](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/services/haptics/types.ts) and add a row to `INTENT_PRESETS` in `adapters/pulsar-intent-map.ts`. The unit test guard at [src/core/services/haptics/**tests**/pulsar-intents.test.ts](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/services/haptics/__tests__/pulsar-intents.test.ts) fails loudly if either step is skipped.

### System gesture deferral (`core/services/system-gesture-defer.ts`)

[`AppProviders`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/providers/AppProviders.tsx) enables app-wide iOS bottom-edge deferral via [`setGameplayGestureDeferralEnabled`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/services/system-gesture-defer.ts) → local Expo module [`modules/screen-gesture-defer`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/screen-gesture-defer/) (`preferredScreenEdgesDeferringSystemGestures = .bottom`). A mistouch on the bottom edge does not immediately trigger Home / app switcher anywhere in the app. Android / web are no-ops today.

Immersive piano routes (`play`, `learn`, `keyboard`) separately call [`useKeepGameplayAwake`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/hooks/useKeepGameplayAwake.ts) so the device does not auto-lock mid-session.

Requires a dev-client rebuild after native module changes — see [architecture.md § Local Expo modules](/docs/architecture.md#local-expo-modules-modules) and [architecture.md § System gesture deferral](/docs/architecture.md#system-gesture-deferral-app-wide).

## Documentation map

| Doc                                                                                                                                                      | Purpose                                                                                                                                                  |
| -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [architecture.md](/docs/architecture.md)                                                                                                      | Feature anatomy, dependency rules, the why behind the folder structure                                                                                   |
| [monorepo.md](/docs/monorepo.md)                                                                                                              | `packages/*` topology, `@piano/*` dependency graph, turbo + tsup setup                                                                                   |
| [adding-a-package.md](/docs/adding-a-package.md)                                                                                              | Step-by-step recipe to add a new `@piano/*` workspace                                                                                                    |
| [routing.md](/docs/routing.md)                                                                                                                | Expo Router groups, redirect/guard flow                                                                                                                  |
| [state-management.md](/docs/state-management.md)                                                                                              | Zustand stores + MMKV persistence patterns                                                                                                               |
| [data-fetching.md](/docs/data-fetching.md)                                                                                                    | TanStack Query, apiClient, mappers, optimistic updates                                                                                                   |
| [styling-theming.md](/docs/styling-theming.md)                                                                                                | Unistyles setup, themes, breakpoints                                                                                                                     |
| [button-press.md](/docs/button-press.md)                                                                                                      | The app's button press: spring squish, sparkles, when to opt out                                                                                         |
| [images.md](/docs/images.md)                                                                                                                  | `<ImageCache>` wrapper, expo-image extras, memory-pressure cleanup                                                                                       |
| [adding-a-feature.md](/docs/adding-a-feature.md)                                                                                              | Step-by-step recipe to add a new feature                                                                                                                 |
| [features/catalog.md](/docs/features/catalog.md)                                                                                              | Remote song catalog + media sync                                                                                                                         |
| [features/songs.md](/docs/features/songs.md)                                                                                                  | Song list UI, previews, lock / paywall surfaces                                                                                                          |
| [features/song-reward.md](/docs/features/song-reward.md)                                                                                      | Reward song after a finished song (A/B), daily count, popup                                                                                              |
| [features/onboarding.md](/docs/features/onboarding.md)                                                                                        | Onboarding feature contract                                                                                                                              |
| [features/auth.md](/docs/features/auth.md)                                                                                                    | Auth feature contract                                                                                                                                    |
| [features/tracks.md](/docs/features/tracks.md)                                                                                                | Tracks feature (`Track` model + UI store; query layer removed)                                                                                           |
| [features/piano.md](/docs/features/piano.md)                                                                                                  | Piano gameplay glue (consumes `@piano/sdk`)                                                                                                              |
| [features/cross-promo.md](/docs/features/cross-promo.md)                                                                                      | Cross promotion: OneLink intake, `xp_uid`, Song List routing, `map_user_id`, Universal Links                                                             |
| [adaptive-tempo.md](/docs/adaptive-tempo.md)                                                                                                  | Adaptive tempo — hidden per-play slow-down: spec, contract, as-built wiring, RC key `adaptive_tempo`, findings, how to play it                           |
| [audio-engine.md](/docs/audio-engine.md)                                                                                                      | Piano audio engine — `@piano/audio-engine` contracts, iOS AVAudioEngine module, shared mixer, speaker output profile, DevTool tuning, device QA          |
| [performance-monitoring.md](/docs/performance-monitoring.md)                                                                                  | Per-screen / per-song performance (Sentry native frames, hangs, Firebase) behind `PerformanceMonitor`; nothing runs during gameplay                      |
| [ci-cd.md](/docs/ci-cd.md)                                                                                                                    | Fastlane + GitLab CI setup: TestFlight, Play Internal                                                                                                    |
| [runtime-provider.md](/docs/runtime-provider.md)                                                                                              | Prebuilt Debug simulator app: CI publish to the GitLab registry, `bun runtime:start`                                                                     |
| [runtime-provider-guide.html](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/docs/runtime-provider-guide.html) | Same, as an illustrated HTML guide (React Flow diagram + macOS token setup) — open in a browser                                                          |
| [ad-trigger-logic.md](/docs/ad-trigger-logic.md)                                                                                              | When ads fire — interstitial frequency cap, placements, play-time accumulator, App Open                                                                  |
| [remote-config-enable-iap.md](/docs/remote-config-enable-iap.md)                                                                              | Remote Config `enableIAP` — what it switches (single-song deals), what must not read it (No Ads package, paywalls), every reader                         |
| [remote-config-removed-keys.md](/docs/remote-config-removed-keys.md)                                                                          | Remote Config keys the app no longer reads (`timing_config`, `keyboard_blocking`, `show_devtools`, `learn_volume_tuner`) — safe to delete in the console |
| [admob-integration.md](/docs/admob-integration.md)                                                                                            | Google AdMob ads — SDK wiring, High → All unit tiers, ATT/IDFA/personalisation, analytics mapping, Ad Inspector, Phase 2 mediation adapters              |
| [security.md](/docs/security.md)                                                                                                              | rnsec scan workflow, accepted risks (`.rnsec.jsonc`), hardening helpers                                                                                  |

## Agent guardrails

Cursor, Claude Code and Codex share [AGENTS.md](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/AGENTS.md), canonical rules in [`.agents/rules/`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/.agents/rules/) and skills in [`.agents/skills/`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/.agents/skills/). Run `bun run agents:sync` to create the agent symlinks and `bun run agents:check` to validate them. Cursor applies `.mdc` metadata through `.cursor/rules`; Claude Code and Codex read the always-on and matching path-scoped rules linked in the index.

| Topic                                                   | Rule / skill                                                                                                                                                                          |
| ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **SUPREME** — branchless gameplay shaders (WGSL / SkSL) | [branchless-shaders.mdc](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/.cursor/rules/branchless-shaders.mdc)                               |
| Gameplay perf (no setState per hit)                     | [gameplay-hot-path.mdc](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/.cursor/rules/gameplay-hot-path.mdc)                                 |
| Metro + workspace singleton dedupe                      | [monorepo-metro.mdc](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/.cursor/rules/monorepo-metro.mdc)                                       |
| Firebase Remote Config                                  | [firebase-remote-config.mdc](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/.cursor/rules/firebase-remote-config.mdc)                       |
| Skia gameplay stack                                     | [piano-simulation-screen skill](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/.cursor/skills/piano-simulation-screen/SKILL.md)             |
| Reanimated threading                                    | [reanimated-worklets-threading skill](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/.cursor/skills/reanimated-worklets-threading/SKILL.md) |

## Rozenite DevTools

[Rozenite](https://www.rozenite.dev/) extends React Native DevTools with require profiling, file system browsing, MMKV storage, TanStack Query, navigation, and Zustand inspectors, plus the local WebGPU / Song Data / Catalog / Assets panels below. Metro integration is gated by `WITH_ROZENITE=true` (never set in production builds); `@rozenite/*` and `rozenite-*` packages live in root `devDependencies` and are only `require`d from `metro.config.js` when that flag is set.

```bash
bun run start   # WITH_ROZENITE=true expo start --dev-client
```

Then open React Native DevTools from the Expo CLI — panels appear for Metro Require Profiler, File System, Storage, TanStack Query, Navigation Inspector, and Zustand, followed by the local panels. Plugin hooks live in [`src/core/devtools/RozeniteDevTools.tsx`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/devtools/RozeniteDevTools.tsx) (dev-only lazy mount from `AppProviders`); Zustand store registration is in [`src/core/devtools/zustand-stores.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/devtools/zustand-stores.ts). Hot-path gameplay stores (`useJudgementStore`, per-hit score/streak) are **not** registered — Rozenite would serialize and bridge every update over CDP and stall the JS thread during play. Require Profiler and the local Assets panel additionally need `enhanceMetroConfig` in [`metro.config.js`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/metro.config.js).

**On-screen route debug overlay** (no DevTools needed): every `__DEV__` build shows a `ROUTE /…` pill top-left over every route, FTUE included. Tap it for the root `Stack.Protected` guard inputs (`onboarding.hasCompleted`, `needsTutorial`, `tutorialExitHref`), the live navigator tree (focused path marked ▶, so push vs replace is visible) and the focus history with timings. Set `EXPO_PUBLIC_ROUTE_DEBUG=0` to hide it. Code: [`src/core/devtools/route-debug/`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/devtools/route-debug/), mounted last in [`app/_layout.tsx`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/app/_layout.tsx).

### WebGPU panel (local plugin)

A local, dev-only **WebGPU** panel inspects the sprite engine in one place: every distinct atlas **texture** (pixels, size, GPU bytes, which plane slots and layers sample it), the **named sprites** on each texture (frame rect, consumer layer, pool, live instance count) and every **plane** (regions, draw batches, GPU memory). Unlike the npm plugins above, its panel is hand-authored static HTML in [`packages/rozenite-piano-devtools/panels/`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/rozenite-piano-devtools/panels/) (copied to `dist/` by that package's `build` script), listed via `include` in [`metro.config.js`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/metro.config.js). The device side lives in [`src/core/devtools/webgpu-planes/`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/devtools/webgpu-planes) (snapshot + texture grouping) and [`src/core/devtools/note-atlas/`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/devtools/note-atlas): a `__DEV__`-only `registry.ts` that the atlas bake sites ([`gameplay-atlas-sheet-context.tsx`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/components/gameplay-atlas-sheet-context.tsx), [`AtlasPianoKeyboard.tsx`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/components/AtlasPianoKeyboard.tsx)) register their named sheets into on mount.

### Song Data panel (local plugin)

A local, dev-only **Song Data** panel inspects every bundled offline chart (`getAllSongAssets()` → `ChartJson`) in one sortable, filterable table: total tracks, per-track melody / rhythm / pedal timelines (note counts, hold vs single, pitch and velocity ranges, first/last beat), segment ("part") counts, BPM, time signature, duration, and the baked `stats` — plus a catalog-wide summary bar (total notes, which song has the most, songs carrying a pedal track / parts / audio). Selecting a row renders a **canvas piano roll** for that song — melody (green) and rhythm (purple) notes on a pitch × time grid with bar/second axis labels, a sustain-pedal strip, and a **velocity line chart** under the roll (0–127, shared time axis; peaks show dynamics ups/downs; chord onsets span min–max) — at an intrinsic beats×zoom width (horizontal scroll; does not stretch to the panel). Drag the bar between the song table and the roll to expand the chart upward (double-click resets); drag the roll itself to pan. Hovering a note, pedal span, or velocity sample shows a tooltip (pitch / timing / velocity, or ↑↓ delta vs the previous sample). The selected song's summary JSON is expandable below. **Copy JSON** grabs the entire catalog. Panel HTML is [`packages/rozenite-piano-devtools/panels/song-data.html`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/rozenite-piano-devtools/panels/song-data.html); the device side lives in [`src/core/devtools/song-data/`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/devtools/song-data): a React-free, unit-tested `analyze-song-data.ts` (the single source of truth — catalog aggregate plus the per-song `buildSongChartView` note / velocity payload) and `useSongDataDevTools.ts`, which ships the aggregate on connect and the note-level piano-roll payload on demand (one song at a time). Besides the bundled charts it lists every song the app has **downloaded**: `cached-song-charts.ts` reads each MIDI whose disk copy is current from the catalog (`CatalogFacade.inspect()` → `getMidi`, cache only — never the network; full songs by file name, parts as `<fileName>-section-N`) and parses it with `parseMidi` → `serializeChart`, the build's own path. A MIDI saved to disk re-pushes the summary (`observeMidi`, debounced), so a fresh download shows up without a refresh.

### Play Result panel (local plugin)

A local, dev-only **Play Result** panel opens the gameplay result screen without finishing a song: pick **session** / **section** / **fullSongUnlocked**, optionally a catalog **song id**, then **Open mock result on device**. The device hook writes `useSessionResultStore.setSnapshot(...)` and **`router.push("/(app)/play-result")`** so the Song list tab stays on the stack (game-over uses `replace` because it swaps out `play`, not `(tabs)`). Panel HTML is [`packages/rozenite-piano-devtools/panels/play-result.html`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/rozenite-piano-devtools/panels/play-result.html); device code lives in [`src/core/devtools/play-result/`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/devtools/play-result/).

### Startup Perf panel (local plugin)

A local, dev-only **Startup Perf** panel shows what the startup budget service measured for this cold start, each figure against a mobile-game budget (Android vitals: cold start ≥ 5 s is excessive; 60 fps frame; stalls past 200 ms read as frozen): JS bundle load, boot services and steps, the whole splash, **cold start → first FTUE screen (`fn_intro_1`)**, longest frame gap, worst-second JS fps and jank %. The service is a port + classes in [`src/core/perf/startup/`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/perf/startup/) — `StartupBudgetService` (port), `DevStartupBudgetService` (measures, judges, notifies `StartupReporter`s and subscribers), `NoopStartupBudgetService` (default; release and tests), `ConsoleStartupReporter` (`console.warn` `[perf:startup]` on every blown budget). `src/bootstrap/startup-budget-setup.ts` installs the dev one under `__DEV__` only; the budgets live in `startup-budget.pure.ts`. Boot, splash and the FTUE funnel (`setFtueEventListener`) report to `getStartupBudgetService()`. Panel HTML is [`packages/rozenite-piano-devtools/panels/startup-perf.html`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/rozenite-piano-devtools/panels/startup-perf.html); device code lives in [`src/core/devtools/startup-perf/`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/devtools/startup-perf/).

A local, dev-only **IAP** panel shows the RevenueCat offerings and their packages (id, product id, price, free trial) plus the customer's entitlements and purchases, read through `getIapService()` (read-only, on request). Panel HTML is [`packages/rozenite-piano-devtools/panels/iap.html`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/rozenite-piano-devtools/panels/iap.html); device code lives in [`src/core/devtools/iap/`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/devtools/iap/).

### Catalog panel (local plugin)

A local, dev-only **Catalog** panel shows what the catalog slice holds and how fresh it is, from `CatalogFacade.inspect()` (read-only; never downloads). Cards: the **active** catalog (origin tag `bundled` / `remote-config` / `cdn`, version = publish time, sha, `minAppVersion`), the **bundled** build, the remote catalog **on disk**, and **Sync / TTL** (last checked, launch TTL and foreground gap with time to expiry, `stale`/`fresh`, ETags). The table lists every song with its entry origin, `vs bundled` (same / changed / new), MIDI origin (`bundled` / `cached` / `stale` = disk copy of an older URL / `remote` = not downloaded / `none`), parts, bytes on disk and save time; a row expands to each MIDI slot's URL. **Force check** runs `refresh({ trigger: "manual" })`. The device pushes a fresh payload on connect, on **Reload**, when the catalog changes, and \~300 ms after a MIDI is saved to disk (`CatalogFacade.observeMidi`, debounced), so a song downloaded during play flips from `remote` to `cached` without a manual reload. Panel HTML is [`packages/rozenite-piano-devtools/panels/catalog.html`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/rozenite-piano-devtools/panels/catalog.html); the device side is [`src/core/devtools/catalog/`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/devtools/catalog) (`catalog-panel-payload.ts` is pure and unit-tested, `useCatalogDevTools.ts` is the hook).

### Assets panel (local plugin)

A local, dev-only **Assets** panel scans every binary asset under `src/` (images, audio, video, MIDI, soundfonts, fonts, JSON under an `assets/` folder) and shows a thumbnail (images, video poster; audio / video play in the detail pane), file size, and whether the file is **used**. Cards total the count and bytes per status (click one to filter) and per kind; assets are grouped by folder with grid / list views, sorting (path, size, status, modified), a kind filter, and **Copy unused** for a deletion checklist. Statuses: **used** (a source file references it by relative path, tsconfig alias or — as a last resort — bare file name, it is registered in a generated `manifest.ts` _and_ that manifest key is mentioned elsewhere, _or_ code reaches the manifest registry as a whole — `Object.keys/values/entries(registry)`, spreading, aliasing, or a manifest helper such as `profileAvatars` that enumerates it — in which case every key counts as used and the reference names the consumer; plain `registry[name]` indexing does not count), **registered** (listed in a manifest but its key is never mentioned and the registry is never reached as a whole — unused unless looked up by a computed string), **unused** (no reference in `src/`, `app/`, `packages/`; test files do not count). `@2x`/`@3x` variants share their base file's verdict. Selecting an asset shows its dimensions, modified time and every referencing `file:line`.

Unlike the other panels this one has **no device side**: the scan is static analysis on the Metro host. [`packages/rozenite-piano-devtools/metro.js`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/rozenite-piano-devtools/metro.js) (wired through `enhanceMetroConfig` in [`metro.config.js`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/metro.config.js)) serves `/__piano_assets/scan` and `/__piano_assets/file`; the scanner is [`scanner/scan-assets.js`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/rozenite-piano-devtools/scanner/scan-assets.js) (unit-tested in `__tests__/`), the panel is [`panels/assets.html`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/rozenite-piano-devtools/panels/assets.html). Dynamic paths (``require(`./${name}.png`)``) cannot be seen — treat "unused" as "check, then delete".

## Internal tools

Some workspace packages are **not** part of the mobile app — they are browser-based dev tools used by PO, design, and engineering to iterate on assets and effects. They live in `packages/*` for monorepo convenience but are never bundled into the React Native build.

| Tool                                                                                                                                            | Purpose                                                                                                | Run                                                                     |
| ----------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------- |
| [`@piano/soundfont`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/soundfont/README.md) lab | Browser Phosphor lab for shared SF2 / ADSR / voice-plan logic (pure TS package + Web Audio adapter)    | `bun run soundfont:lab` · `bun run soundfont:lab:build`                 |
| `@piano/midi` visualizer                                                                                                                        | MIDI visualizer + Hit Timing (BPM scale / device Timing Zone + tile-fall sim)                          | `bun run midi:viz`                                                      |
| [Piano DevTool](/docs/devtool.md)                                                                                                    | Electron / web app: analytics stream + MIDI/SF2 sync to the app (`EXPO_PUBLIC_ENABLE_DESKTOP_TOOLS=1`) | `bun run devtool:dev` · `bun run devtool:web` · `bun run analytics:viz` |

## High-level user journey

The root `app/_layout.tsx` wraps each group in `<Stack.Protected guard={...}>` and reads `hasCompleted` + `session` from Zustand. Whichever guard is satisfied is the stack the user sees — there is no boot redirect file.

```mermaid
flowchart LR
  start([App launch]) --> root["app/_layout.tsx<br/>ProtectedRoutes"]
  root -->|!hasCompleted| onb["(onboarding)/<br/>3-slide carousel"]
  root -->|hasCompleted &amp;&amp; !session| signIn["(auth)/sign-in"]
  root -->|hasCompleted &amp;&amp; session| tabs["(app)/(tabs)<br/>landscape · SideTabBar"]
  onb -->|complete + skip| signIn
  signIn -->|signIn ok| tabs
  signIn --> signUp["(auth)/sign-up"]
  signUp -->|signUp ok| tabs
  tabs --> home[Home]
  tabs --> profile[Profile]
  profile -->|signOut| signIn
```

## Path aliases & package imports

App-internal imports use TypeScript path aliases:

| Alias           | Maps to               | Use for                                        |
| --------------- | --------------------- | ---------------------------------------------- |
| `@/*`           | `src/*`               | Catch-all when no specific alias fits          |
| `@core/*`       | `src/core/*`          | Anything in providers / memory / hooks / theme |
| `@services/*`   | `src/core/services/*` | `apiClient`, `mmkv`, `queryClient`             |
| `@hooks/*`      | `src/core/hooks/*`    | `useScreenInsets`, `useMemoryWarning`          |
| `@features/*`   | `src/features/*`      | Feature-internal imports                       |
| `@components/*` | `src/components/*`    | Shared UI primitives                           |
| `@assets/*`     | `src/assets/*`        | Static assets (fonts, images, audio samples)   |

Bundled bitmaps/SFX/soundfonts under `src/assets/{icons,shared,gamplay,paywall,songs,sfx,bottom-tab,soundfonts,tutorial,onboarding}/` expose typed keys via **generated** `manifest.ts` files. Catalog song lookup maps live in [`src/core/sdk/song-assets.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/docs/src/core/sdk/song-assets.ts) (gitignored, generated by `catalog:sync-sheet`, indexing `chartAssets` from `@assets/charts/manifest`); preview clips + [`src/assets/previews/index.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/docs/src/assets/previews/index.ts) are gitignored and materialized by `catalog:sync-sheet` / `ensure-catalog-generated.ts`. Chart JSON / BGM / preview binaries under `src/assets/{charts,audio,previews}/` are also gitignored (`.gitkeep` placeholders tracked). Sheet MIDI is converted to chart JSON at sync time and is **not** stored under `src/assets/midi/`. After adding or removing binaries in asset folders, run `bun run assets:sync` (also runs on `postinstall` and before `typecheck`). Generated asset manifests are gitignored — invalid keys are caught by TypeScript (`IconName`, `ChartAssetName`, …).

Prefer the module-specific alias over `@/*` whenever one exists.

Workspace packages are imported by their **package name** (no path alias):

```ts
import { createPianoSdk } from '@piano/sdk';
import type { Song } from '@piano/types';
```

Bun resolves these via the workspace symlinks under `node_modules/@piano/*` → `packages/<name>`. Don't add path aliases for workspace packages — package-name resolution is what `bunx turbo run build` and Metro both rely on.

## Conventions in 60 seconds

- `app/` only contains route files that import a screen from `@features/*/screens/` and re-export it as `default`. No business logic in route files.

- A feature folder is self-contained:

  ```
  features/<name>/
    api.ts        # fetch/mock fns -> DTOs
    mappers.ts    # DTO -> domain
    types.ts      # DTO + domain types
    queries.ts    # react-query hooks (server state)
    store.ts      # zustand (client state)
    screens/      # rendered by route files
    components/   # local-only UI
  ```

- Features can import from `@services`, `@hooks`, `@core/*`, `@components`. Features may import another feature's `store.ts` only (e.g. `Profile` reads `useAuthStore`); avoid importing other features' `screens/` or `components/`.

- `core/`, `components/` are leaves — they never import from `features/*`.

## Documentation website

Run `bun run docs:dev` for the Rspress website, or `bun run docs:build` for static output. Devs maintain the existing Markdown; the site documents the current version, and `CHANGELOG.md` is its one page of release history. Setup and release workflow: [Documentation website](/docs/docs-site.md).

***

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