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

# Monorepo

Magic Piano is a Bun + Turborepo monorepo. The Expo app stays at the repo root; reusable piano logic lives in `packages/*` as `@piano/*` workspace packages plus the instrument-agnostic `@rhythm/engine` rhythm-game core, all built with `tsup` and orchestrated by `turbo`.

## Why a monorepo

- **The piano engines are reusable.** Audio, MIDI, gameplay, progression, catalog, ads, and analytics are domain logic that has nothing to do with React Native. Putting them under `packages/*` lets the same code ship to a future web build, a CLI, or a unit-test runner without dragging Expo with them.
- **The app stays thin.** `app/` and `src/` only contain UI, navigation, and React Query glue. All gameplay state machines live in `@piano/gameplay-{learn,magic,zen}`.
- **One install, one lockfile.** Bun's hoisted workspaces share a single `bun.lock` and `node_modules`, so React, RN, and Reanimated cannot be duplicated across packages — the #1 cause of "Invalid hook call" errors in RN monorepos.

## Repo layout

```text
magic_piano/
├── app/                       # expo-router routes (host)
├── src/                       # Expo app source (host)
├── packages/                  # Bun workspaces, all named @piano/*
│   ├── types/                 # leaf — domain types for game / midi / player
│   ├── keyboard/              # piano key model + layout math
│   ├── core/                  # cross-cutting engine primitives
│   ├── network/               # MIDI repository contracts
│   ├── analytics/             # adapter + dispatcher (+ visualizer/ browser tool)
│   ├── ads/                   # provider contract
│   ├── midi/                  # MIDI parser (midi-parser-js wrapper)
│   ├── progression/           # XP / level service
│   ├── player-data/           # PlayerDataManager (Zod-validated)
│   ├── user-library/          # Owned songs + subscription ledger (cloud-ready)
│   ├── catalog/               # SongCatalog (songs + moods)
│   ├── rhythm-engine/         # @rhythm/engine — instrument-agnostic rhythm core
│   ├── soundfont/             # @piano/soundfont — pure SF2 parse / ADSR / voice-plan (+ browser lab)
│   ├── gameplay-learn/        # legacy practice-mode engine (predates src/features/learn)
│   ├── gameplay-magic/        # magic-mode engine (thin shim re-exports from @rhythm/engine, slated for removal once Learn + Zen migrate)
│   ├── gameplay-zen/          # zen-mode engine
│   └── sdk/                   # public facade — createPianoSdk()
├── tools/                     # optional non-workspace tools (e.g. `piano-devtool-desktop` — the Piano DevTool Electron app, see [devtool.md](devtool.md))
├── modules/                   # local Expo modules (host-native bridges, autolinked on prebuild)
│   ├── screen-gesture-defer/  # iOS app-wide bottom-edge system gesture deferral
│   ├── perf-hud/              # iOS SwiftUI overlay — UI FPS / DRAW FPS / JANK / RAM / CPU (always-on)
│   └── sdk-crash-guards/      # iOS load-time guards against third-party SDK faults (no JS facade)
├── android/                   # Expo prebuild output
├── ios/                       # Expo prebuild output
├── package.json               # workspaces: ['packages/*']
├── turbo.json                 # build / typecheck / test / lint / dev pipeline
├── tsconfig.base.json         # shared compiler options for packages
├── tsup.config.base.ts        # shared bundler config for packages
├── bunfig.toml                # bun: hoisted linker, exact installs
└── metro.config.js            # watchFolders + nodeModulesPaths for packages
```

[`modules/`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/) holds **local Expo modules** — host-native bridges autolinked on `expo prebuild` (Swift/Kotlin + `expo-module.config.json`). They are not Bun workspace packages: no `package.json`, no `tsup` build, not imported as `@piano/*`. The app imports them via relative paths from `src/` (e.g. [`system-gesture-defer.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/services/system-gesture-defer.ts) → [`modules/screen-gesture-defer`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/screen-gesture-defer/), [`perf-hud.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/services/perf-hud.ts) → [`modules/perf-hud`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/perf-hud/)). See [architecture.md § Local Expo modules](/docs/architecture.md#local-expo-modules-modules).

## Workspace dependency graph

`@piano/types` is the leaf; `@piano/sdk` is the facade. Every other package sits between them.

```mermaid
flowchart BT
  types["@piano/types"]
  ads["@piano/ads"]
  keyboard["@piano/keyboard"]
  core["@piano/core"]
  network["@piano/network"]
  analytics["@piano/analytics"]
  audioEngine["@piano/audio-engine"]
  midi["@piano/midi"] --> types
  progression["@piano/progression"]
  playerData["@piano/player-data"] --> core
  catalog["@piano/catalog"] --> playerData
  catalog --> userLibrary["@piano/user-library"]
  userLibrary --> core
  gameplayLearn["@piano/gameplay-learn"] --> types
  gameplayLearn --> core
  gameplayLearn --> progression
  gameplayMagic["@piano/gameplay-magic"] --> types
  gameplayMagic --> core
  gameplayMagic --> progression
  gameplayZen["@piano/gameplay-zen"] --> types
  gameplayZen --> core
  gameplayZen --> progression
  sdk["@piano/sdk"] --> types
  sdk --> ads
  sdk --> analytics
  sdk --> catalog
  sdk --> core
  sdk --> gameplayLearn
  sdk --> gameplayMagic
  sdk --> gameplayZen
  sdk --> keyboard
  sdk --> midi
  sdk --> network
  sdk --> playerData
  sdk --> progression
```

Topological build order (what `turbo run build` walks):

| Layer | Packages                                                                                                            |
| ----- | ------------------------------------------------------------------------------------------------------------------- |
| L0    | `types`, `ads`, `keyboard`, `network`, `analytics`, `progression`, `audio-engine`                                   |
| L1    | `midi`, `rhythm-engine`                                                                                             |
| L2    | `core` (re-exports from `rhythm-engine`)                                                                            |
| L3    | `player-data`, `user-library`, `gameplay-learn`, `gameplay-magic` (re-exports from `rhythm-engine`), `gameplay-zen` |
| L4    | `catalog`                                                                                                           |
| L5    | `sdk`                                                                                                               |

> **Deprecation track:** `@piano/midi`, `@piano/gameplay-magic` (the `judgement` module), and parts of `@piano/core` (`event-bus`, `state-machine`, `tick-clock`) are now **thin re-exports from `@rhythm/engine`**. They stay for backward compatibility with `@piano/gameplay-learn` and `@piano/gameplay-zen` until those packages migrate; track full removal in the rhythm-engine package README.

## Package responsibilities

| Package                 | Contains                                                                                                                                                                                                                                                                               | External deps                                                              |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| `@piano/types`          | Domain types for game / midi / player                                                                                                                                                                                                                                                  | —                                                                          |
| `@piano/keyboard`       | Piano key model, octave math, layout helpers                                                                                                                                                                                                                                           | —                                                                          |
| `@piano/midi`           | MIDI byte → event parser                                                                                                                                                                                                                                                               | `midi-parser-js`                                                           |
| `@piano/core`           | Cross-cutting engine primitives (event buses, clocks, base classes)                                                                                                                                                                                                                    | —                                                                          |
| `@piano/network`        | `IMidiRepository` contract for fetching songs                                                                                                                                                                                                                                          | —                                                                          |
| `@piano/analytics`      | Valibot schema-driven typed `track()` + `IAnalyticsAdapter` fan-out ([docs](/docs/analytics-events.md)); browser visualizer under `visualizer/` (`bun run analytics:viz`)                                                                                                   | `valibot`                                                                  |
| `@piano/ads`            | `IAdsProvider` contract                                                                                                                                                                                                                                                                | —                                                                          |
| `@piano/progression`    | XP table + `LevelService`                                                                                                                                                                                                                                                              | `valibot`                                                                  |
| `@piano/player-data`    | `PlayerDataManager` (XP, unlocks) + `IPlayerDataStorage`                                                                                                                                                                                                                               | `valibot`                                                                  |
| `@piano/user-library`   | `UserLibraryManager` (owned songs, snapshots) + `ILibraryStorage`                                                                                                                                                                                                                      | `valibot`, `@piano/core`                                                   |
| `@piano/catalog`        | `SongCatalog` (songs + moods)                                                                                                                                                                                                                                                          | `valibot`                                                                  |
| `@rhythm/engine`        | Instrument-agnostic rhythm core: chart parser, bitmask cursor, judgement, scoring, `PlayController`, optional React bindings. Single source of truth for tile/highlight/judgement on the UI thread.                                                                                    | `react-native-reanimated` (peer, optional via `./react`), `midi-parser-js` |
| `@piano/audio-engine`   | Platform-agnostic piano audio contracts (`PianoAudioEngine`, instrument / clock / effects / settings / diagnostics / preset) + shared pure helpers (velocity curves, `resolveAudioBackend`). Imported directly by `src/core/audio/engine/` ([docs](/docs/audio-engine.md)). | —                                                                          |
| `@piano/soundfont`      | Pure SF2 parse, region merge, ADSR convert, sample voice-plan (no AudioContext). Used by app adapters + browser lab (`bun run soundfont:lab` / `soundfont:lab:build`).                                                                                                                 | —                                                                          |
| `@piano/gameplay-learn` | Learn-mode engine + scoring                                                                                                                                                                                                                                                            | —                                                                          |
| `@piano/gameplay-magic` | Magic-mode shim (`judgement` re-exports from `@rhythm/engine`; `judgement-queue` + `engine` retained for legacy consumers, removal scheduled after Learn + Zen migrate)                                                                                                                | —                                                                          |
| `@piano/gameplay-zen`   | Zen-mode engine + scoring                                                                                                                                                                                                                                                              | —                                                                          |
| `@piano/sdk`            | `createPianoSdk(config)` — single entry point for the Expo app                                                                                                                                                                                                                         | re-exports everything                                                      |

The Expo app **only imports `@piano/sdk`** (and re-exported types from it). Reaching past the SDK into a sub-package directly works but defeats the facade — keep that for tests or scripts.

## Per-package layout

Every package is identical:

```text
packages/<name>/
├── src/
│   └── index.ts        # the only entry point
├── tests/              # bun test
├── dist/               # tsup output (gitignored)
├── package.json        # name = "@piano/<name>"
├── tsconfig.json       # extends ../../tsconfig.base.json
├── tsup.config.ts      # imports baseConfig from ../../tsup.config.base.ts
└── README.md
```

`package.json` is uniform too:

```json
{
  "name": "@piano/<name>",
  "version": "0.0.0",
  "type": "module",
  "main": "./src/index.ts",
  "module": "./src/index.ts",
  "types": "./src/index.ts",
  "exports": {
    ".": {
      "types": "./src/index.ts",
      "default": "./src/index.ts"
    }
  },
  "files": ["src"],
  "scripts": {
    "build": "tsup",
    "test": "bun test",
    "typecheck": "tsc --noEmit",
    "clean": "rm -rf dist .turbo"
  }
}
```

Workspace deps use `"@piano/<dep>": "workspace:*"`. Runtime/peer deps go under `dependencies`. Build tooling (`tsup`, `typescript`, `@types/bun`) goes under `devDependencies`.

## Shared configs

### `tsconfig.base.json`

Strict, ES2022, declaration emit + sourcemaps + incremental builds. Extended by every package's `tsconfig.json`:

```json
{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    "outDir": "./dist",
    "rootDir": "./src"
  },
  "include": ["src/**/*"],
  "exclude": ["dist", "node_modules", "tests"]
}
```

The Expo app's `tsconfig.json` does **not** extend this file — it extends `expo/tsconfig.base` because Expo needs different `jsx`, `lib`, and `types` settings. The two tsconfigs intentionally diverge: packages target plain ES2022, the app targets RN.

### `tsup.config.base.ts`

Dual ESM + CJS output, declaration files, sourcemaps, no code splitting (each package ships a single `index.{js,cjs,d.ts}`). Extended by every package's `tsup.config.ts`:

```ts
import { defineConfig } from 'tsup';
import { baseConfig } from '../../tsup.config.base';

export default defineConfig(baseConfig);
```

If a package needs entry-point overrides (multiple subpath exports, side-effects flag, externals), it can spread `baseConfig` and add its own keys.

### `bunfig.toml`

```toml
[install]
exact = true       # pin every install to an exact version
linker = "hoisted" # hoist deps to root node_modules (required for Metro)
```

The `hoisted` linker is what lets Metro resolve a single copy of `react` / `react-native` / `react-native-reanimated` across the app and packages. Don't switch to `isolated` — RN cannot tolerate duplicate copies of those modules.

The `[test]` table also sets `pathIgnorePatterns = ["build/**", "ios/**", "android/**", "node_modules/**"]`. `bun test` keeps a directory fd open for every folder it walks while discovering tests; a local simulator build under `build/ios-sim` (\~15k folders) plus `ios/Pods` (\~10k) made each shard hold \~30k fds, and the nine `//#test:app:*` shards that Turbo runs together exhausted the system file table (`ENFILE` / `SystemFdQuotaExceeded`, shards failing at random). Keep native build output out of the test walk.

### `turbo.json`

```json
{
  "tasks": {
    "build":     { "dependsOn": ["^build"], "outputs": ["dist/**"] },
    "test":      { "dependsOn": ["^build"], "outputs": [] },
    "typecheck": { "dependsOn": ["^build"], "outputs": [] },
    "dev":       { "cache": false, "dependsOn": ["^build"], "outputs": [], "persistent": true },
    "clean":     { "cache": false, "outputs": [] }
  }
}
```

`^build` means "build dependencies first" — turbo walks the workspace graph in topological order. So `bunx turbo run typecheck` rebuilds dependent `dist/` outputs before typechecking each package, which guarantees `@piano/sdk` typechecks against fresh declaration files of `@piano/types` etc.

## How the Expo app consumes packages

```mermaid
sequenceDiagram
  participant Dev as Developer
  participant Bun as bun install
  participant FS as node_modules/@piano
  participant Metro as Metro bundler
  participant App as src/features/piano

  Dev->>Bun: bun install
  Bun->>FS: symlink each packages/<name> -> node_modules/@piano/<name>
  Dev->>Metro: bun run start
  Metro->>FS: resolve "@piano/sdk"
  FS-->>Metro: packages/sdk/src/index.ts (TypeScript source — no build step)
  Metro-->>App: bundled module
```

Three pieces make this work:

1. **Bun workspaces** (`package.json` `workspaces: ["packages/*"]`) symlink each `@piano/*` into `node_modules/@piano/`.
2. **Metro `watchFolders`** (`metro.config.js`) point at `packages/`, so editing a file in `packages/midi/src/parser.ts` triggers Fast Refresh in the running app.
3. **`disableHierarchicalLookup: true`** (`metro.config.js`) prevents Metro from walking up into nested `node_modules`, which is what would otherwise pull in a duplicate `react`.
4. **`DEDUPE_SINGLETONS` resolver** forces `react-native-reanimated` and `react-native-worklets` to always resolve from the root `node_modules` — a nested copy in `packages/*/node_modules` causes frame-callback id collisions and release crashes. Agent rule: [`.cursor/rules/monorepo-metro.mdc`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/.cursor/rules/monorepo-metro.mdc). After editing `metro.config.js`, run `expo start --clear`.

The Reanimated and Unistyles babel plugins both live in the root `babel.config.js`, and `autoProcessPaths` is `['app', 'packages']` — so worklets and styled components inside `packages/*` get the same codegen the app sources do.

## Common commands

| Command                                     | Effect                                                          |
| ------------------------------------------- | --------------------------------------------------------------- |
| `bun install`                               | Install root + all workspaces, refresh symlinks                 |
| `bun run start`                             | Start Metro for the Expo app (consumes packages by symlink)     |
| `bun run ios` / `bun run android`           | Build + launch the native app                                   |
| `bun run typecheck`                         | Typecheck the Expo app only (`tsc --noEmit` at root)            |
| `bun run typecheck:all`                     | Typecheck every workspace package via `turbo run typecheck`     |
| `bun run build:packages`                    | Build all `@piano/*` (`turbo run build`, topologically ordered) |
| `bun run lint:all`                          | Run each workspace's `lint` script                              |
| `bunx turbo run build --filter=@piano/midi` | Build a single package and its dependencies                     |
| `bunx turbo run dev --filter=@piano/midi`   | Watch-mode `tsup --watch` for one package                       |
| `bun run clean` (per package)               | `rm -rf dist .turbo` inside that package                        |

## Adding / removing a package

See [adding-a-package.md](/docs/adding-a-package.md) for the full recipe. TL;DR:

1. Copy an existing leaf package (`packages/types/` is a good template).
2. Rename it in `package.json` (`@piano/<new-name>`).
3. Add `"@piano/<dep>": "workspace:*"` for any workspace deps.
4. Run `bun install` from the repo root — the symlink appears under `node_modules/@piano/`.
5. Add it to `@piano/sdk`'s `dependencies` and `src/index.ts` re-export if it should be part of the public surface.

## Things to watch for

- **Don't ship `react`/`react-native` from a package.** RN packages only — the engines under `@piano/*` are pure TS and must stay that way. If you need RN, write a thin adapter in `src/features/<x>/` instead.
- **Peer deps for the host app.** When a package eventually does want a peer (e.g. `expo-asset` for sample loading), declare it as `peerDependencies` in the package and ensure the same exact version is in the root `package.json`.
- **`workspace:*` pins are protocol-only.** `bun install` rewrites them to actual versions in the published artifact, but inside this repo they always resolve to the live source.
- **`turbo run build` caches per package.** If you bypass turbo and run `tsup` directly in one package, turbo will still see clean inputs next time and skip — that's intentional. To force a rebuild, `bun run clean` in that package or `bunx turbo run build --force`.

***

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