Documentation comes from this release commit, without inheriting newer content. Commit: 371ee4692c.
Magic Piano — Technical Docs
Living documentation for the Magic Piano React Native app. All diagrams use Mermaid and render natively in GitHub, Cursor, VS Code (with the Markdown Preview Mermaid extension), and most documentation sites.
Stack at a glance
Repo layout
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.
App source layout
src/core/ zoom-in
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 and warmed
by the haptics lifecycle action. AppStartupPolicy
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.
The Pulsar adapter applies two boot-time policies inside its constructor (see src/core/services/haptics/adapters/pulsar.ts): it disables the audio side of Core Haptics presets (Settings.enableSound(false)) 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, 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; 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).
Adding a new intent: append it to HapticIntent in 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 fails loudly if either step is skipped.
System gesture deferral (core/services/system-gesture-defer.ts)
AppProviders enables app-wide iOS bottom-edge deferral via setGameplayGestureDeferralEnabled → local Expo module 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 so the device does not auto-lock mid-session.
Requires a dev-client rebuild after native module changes — see architecture.md § Local Expo modules and architecture.md § System gesture deferral.
Documentation map
Agent guardrails
Cursor, Claude Code and Codex share AGENTS.md, canonical rules in .agents/rules/ and skills in .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.
Rozenite DevTools
Rozenite 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 required from metro.config.js when that flag is set.
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 (dev-only lazy mount from AppProviders); Zustand store registration is in 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.
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/ (copied to dist/ by that package's build script), listed via include in metro.config.js. The device side lives in src/core/devtools/webgpu-planes/ (snapshot + texture grouping) and src/core/devtools/note-atlas/: a __DEV__-only registry.ts that the atlas bake sites (gameplay-atlas-sheet-context.tsx, 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; the device side lives in 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; device code lives in 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/ — StartupBudgetService (port), DevStartupBudgetService (measures, judges, notifies StartupReporters 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; device code lives in 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; device code lives in 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; the device side is 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 (wired through enhanceMetroConfig in metro.config.js) serves /__piano_assets/scan and /__piano_assets/file; the scanner is scanner/scan-assets.js (unit-tested in __tests__/), the panel is 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.
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.
Path aliases & package imports
App-internal imports use TypeScript path aliases:
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 (gitignored, generated by catalog:sync-sheet, indexing chartAssets from @assets/charts/manifest); preview clips + 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):
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 asdefault. No business logic in route files. -
A feature folder is self-contained:
-
Features can import from
@services,@hooks,@core/*,@components. Features may import another feature'sstore.tsonly (e.g.ProfilereadsuseAuthStore); avoid importing other features'screens/orcomponents/. -
core/,components/are leaves — they never import fromfeatures/*.