v1.0.11 · Release snapshot

Documentation comes from this release commit, without inheriting newer content. Commit: cc3dd17e61.

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 for the full package-graph.

Layers

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/*.

SubfolderImported viaResponsibility
core/entrySetup.ts@/core/entrySetupComposition 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/orientationCoordinated device orientation. Route-group layouts call useOrientation; the store resolves priority and issues one lockAsync per change. See routing.md.
core/memory/@core/memory/*ResourceScope / useResourceScope for deterministic screen-lifetime disposal.
core/audio/@core/audioOne process-wide piano sampler (PianoSamplerLike) via ensurePianoSampler — the iOS AVAudioEngine backend (NativePianoSampler, registered at boot from entrySetup.ts; see audio-engine.md). Android has no engine yet. useSoundFontSampler 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. @piano/types is the leaf, @piano/sdk is the root.

Feature anatomy

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

File responsibilities

FileResponsibility
types.tsDTO interfaces (snake_case wire format) + domain interfaces (camelCase app types).
api.tsPure async functions that return DTOs. No React. No mapping.
mappers.tsPure functions toX(dto: XDto): X. Easy to unit test.
queries.tsReact Query hooks; the only place that combines api + mappers. Centralises caching + invalidation.
store.tsClient-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; rules: the clean-architecture skill.

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).

Remote MIDI/BGM URLs are still indexed in src/core/sdk/catalog-asset-index.ts (refreshed on every projection) for HybridMidiRepository and backing resolution. Songs removed from the catalog but owned by the user are kept in @piano/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 (UserLibraryDocument in MMKV per userId), not inside the catalog cache. ILibraryStorage is cloud-ready — production uses HybridLibraryStorage (local-first; sync() is a stub until Firestore / API / iCloud lands). Login merges the guest partition into the account partition (onLibraryLogin).

Lock resolution uses LockContext (isVip + ownedSongIds) via getSongLockState 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). MIDI goes through JS bytes (write); a BGM recording is downloaded natively straight to its file (downloadToFile). Song-list cover art uses ImageCache in SongRow — 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 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. Features and UI never import the native SDK.

LayerAPIKnows Purchases?
Features / screensgetIapService() + domain types from @core/iapNo
iap-service-registry.tsBuilds RevenueCatIapService on first getIapService() callNo
revenuecat-iap-service.tsinit() once from entrySetup.ts; other methods await readinessYes — 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) only sets MMKV flags — no IAP calls on the splash critical path. Receipt restore for reinstalls runs idle after splash via schedulePostSplashReinstallRestore.
  • 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 (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 (<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 (consumed via useMagicJudgement):

  • Song sequencer / audio-driven pulse. PlayController owns a RhythmSequencer — the single song clock. Its Transport 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 forwards the module's ~30 ms clock pulse (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.
  • Shared clock channel. Anchor tick, run state, and tempo cross runtimes through createGameplayClockChannel — 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. The AUDIO clock is the master and the lane is disciplined toward it (see 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 (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 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 — extend the test, don't open-code variations of the clamp / pause logic.

See also .cursor/skills/piano-simulation-screen/SKILL.md 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/. They autolink on expo prebuild (same mechanism as expo-camera), live inside the host repo (not under packages/*), and are not published to npm.

ModulePlatformsPurpose
screen-gesture-deferiOSApp-wide bottom system gesture deferral (Home / app switcher) via preferredScreenEdgesDeferringSystemGestures = .bottom.
perf-hudiOSAlways-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 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 via perf-hud.ts.
piano-audio-engineiOS (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; the app's only piano engine — see audio-engine.md.
sdk-crash-guardsiOSGuards against known faults in third-party SDKs, installed from +load before main; native only, so it has no index.ts. 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). Its contract test runs in test:app:config.

Typical layout per module:

modules/<name>/
  expo-module.config.json   # autolinking — platforms + native class names
  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

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/ (e.g. withSplashBackground, withIosInAppPurchase) 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 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).

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); 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.

LayerFileRole
BootstrapAppProviders.tsxuseEffect — enable on mount, disable on unmount
Servicesystem-gesture-defer.tsPlatform branch; Android / web no-op today
NativeScreenGestureDeferController.swiftSwizzles the key-window root VC's preferredScreenEdgesDeferringSystemGestures getter

Do not toggle deferral from individual screens. Immersive piano surfaces instead call useKeepGameplayAwake 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 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 and 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 (generated by convert-charts) exposes a ChartAssetName union + chartAssets map, and src/core/sdk/song-assets.ts (gitignored, generated) indexes those modules per catalog id. Gameplay loads charts via loadGameplayChart; HybridMidiRepository only resolves remote MIDI for delisted owned snapshots.

FTUE tutorial charts are separate keys from catalog gameplay: src/assets/tutorial/charts/manifest.ts (generated by charts:convert-tutorial from the committed 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 maps those keys to chart modules and 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), any other is fetched. Twinkle Twinkle Little Star, which is public domain, is the whole tutorial on a public build and the stand-in for every slot the console leaves unusable. Each song carries its own coverAssetModule in tutorial-gameplay-song.ts (Twinkle's tutorialAssets.TwinkleTwinkleLittleStar from the tutorial manifest, a console song's catalog thumbnail) — TutorialGameplayScreen and TutorialResultScreen read the flag and pass tutorialSong.coverAssetModule on. Screen-2 practice training uses scripted mock notes that auto-fall from the spawn margin and pause at the hit line (same lane geometry as gameplay) plus a tutorial-owned lane stack (TutorialGameplayCanvas / TutorialPracticeGameplay — keyboard + hit line always visible) — no bundled MIDI, no PlayScreen. Practice keeps PlayScreenPrepareAssetGroup up until the SoundFont sampler and keyboard Skia snapshot bake are ready (isPlayPrepareReady / onSnapshotsReady), then skips the 3-2-1-GO pre-roll (skipCountdown) so coach copy and drills start as soon as prepare clears. Screen-4 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 training drills keep their colours locked at tier 1 (TUTORIAL_EFFECT_THEME_TIER on TutorialGameplayCanvas and in useTutorialPracticeSession), so a drill never flips tile / keyboard / effect palettes. The first-run tutorial flow lives in src/features/tutorial/.

// 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 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). 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, buildSongSegmentPlan). 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, 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> 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

See features/auth.md for the full contract.