Working-tree content. Subject to change and not yet released. Commit: e3d4530507.
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/*.
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.ProfilereadsuseAuthStore. @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/, orapi.ts. @piano/<sub-package>directly (use@piano/sdkre-exports). The SDK is the only public surface.
core/,components/are leaves; they do not import fromfeatures/*or@piano/*.- Exception:
core/entrySetup.tsis the composition root and is allowed to import fromfeatures/*(auth store, monetization entitlement sync). Do not add new feature imports anywhere else incore/.
- Exception:
packages/@piano/*MUST NOT import fromapp/*,src/*,react, orreact-native. They are pure TypeScript libraries.- Workspace-internal dependencies between packages are governed by the graph in monorepo.md.
@piano/typesis the leaf,@piano/sdkis the root.
- Workspace-internal dependencies between packages are governed by the graph in monorepo.md.
Feature anatomy
Every feature follows the same shape so newcomers can navigate by muscle memory.
File responsibilities
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.tsowns server cache;store.tsowns client state. NouseEffect-fetch-into-useStateantipatterns. - DTO ↔ domain boundary keeps server changes from leaking into every component. A wire change updates
types.ts+mappers.tsonly. 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 inapp/_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()anduseTutorialStore.complete()go throughproceedWhenGroupPreloaded(next, …): immediate when the next module is ready (the normal case), otherwise at mostGROUP_PRELOAD_MAX_MS.LazyScreenFallback(dark backdrop, never a blank frame) covers whatever is left. - Offload on leave.
<GroupLifecycle group=…>callsoffloadGrouponce the rootStack.Protectedguard 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 rendersnullstill keeps its hooks — the decoded key art — alive). Owners register what to give back withonGroupOffload(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-runtimeand 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.
Boot rules:
src/bootstrap/start-app-bootstrap.ts, reached through the app lifecycle facade, callsgetIapService().init()once per process (Purchases.configure()+ listener + initial entitlement sync). Feature code never callsinit().- Splash identity (
resolveFirstLaunchIdentity) only sets MMKV flags — no IAP calls on the splash critical path. Receipt restore for reinstalls runs idle after splash viaschedulePostSplashReinstallRestore. - 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 domainIapEntitlementsin the adapter, then handed to the composition-root handler wired inentrySetup.ts(entitlements store + ad-gate cache). - Attribution (AppsFlyer) goes through
@core/attribution(getAttributionService(), port + adapter + noop/fake like@core/iap); ads go through@core/ads - Meta app events (Facebook SDK,
react-native-fbsdk-next) go through@core/meta-events(getMetaAppEvents(), port + one adapter + noop/fake + registry;sim→ noop): the ad path'sAdImpressionand the ATT answer. Install / app activation are logged by the SDK itself. (getAdsService()); subscriptions go through@core/iaponly.
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.
PlayControllerowns aRhythmSequencer— the single song clock. ItsTransportis 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 fromsampler.createClockPump():NativeClockPumpforwards 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 gameplaysetIntervaland no releasesetTimeout— 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).
useRhythmEnginesubscribes its anchorsteptocontroller.sequencer.onPulse; the step callscontroller.tickFrame()— which advances theRhythmEngine(groups, pedal, game end) from the transport tick — then runssweepMissedGroupsover the cursor before publishing the just-stepped tick into the shared clock channel and the newheadIdxSv. 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 inChartJson(plus an optionaltempo_map), and are converted beats → seconds → linear song ticks at one constantticksPerSecond. The runtime clock, tile scroll, and judgement windows therefore never see a tempo change. Seetimeline/tempo-map.ts. - Shared clock channel. Anchor tick, run state, and tempo cross runtimes through
createGameplayClockChannel— fixed-typeSynchronizablenumber cells fromreact-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 serializingsetBlocking, and only when it changes. Serializing the whole snapshot object per pulse cost 10–24 ms on iPad. ASharedValuewritten 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 usegetDirty()— never blocking, at worst one publish behind, which the extrapolation window already absorbs. - UI thread / frame cadence (60–120 Hz). A single
useFrameCallbackworklet inside the same hook does one non-blocking snapshot read and callsresolveDisplayTick. 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→JSVisualClockChannel(lock-free fixed-typeSynchronizablecells). 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 ReanimatedsetActiveviasetFrameActive, driven byGameStateMachine.stateChanged→isPlaying()— not ReactsetState. The judgement cursor lives incursorRefonly; 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)intocreatePressMailboxbefore the hop (four fixed-typeSynchronizableslots + a seqlock; the keyboard finds it throughjudgementTickSvwithpressMailboxOf, like the game-state block).registerTapacks the press first thing; the anchor step holds the auto-pause and the miss sweep while a posted, unacked press is at mostIN_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 reachesregisterTapstops holding after the age cap. - Pause / resume. Manual and auto-pause flip the engine state machine;
syncIsRunningpublishesisRunning: 0, freezestickSv(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 everypause()andresume()(PlayController.setDisplayTickSource/realignTo), and the hook seeds the lane on start / resume. HUD play/pause leaves subscribe viasubscribeManualTransportseparately.
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).
tickSvis 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
tickSvfrom the JS thread — callcontroller.tickFrame()through the anchor loop and let the worklet extrapolate. - Never schedule gameplay audio with
setTimeout/setInterval— add aSequencerTrackto the controller'sRhythmSequencerand pass exact audio times (playNote(…, atTime),releaseVoice(voice, atTime)). - Never include
tickSvin a hook dep array; it's a stable Reanimated handle. - New tick-driven UI must read from
tickSvviauseDerivedValue/useAnimatedStyle, not subscribe via a re-render. - The pure helper
computeInterpolatedTickis unit-tested inpackages/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.
Typical layout per module:
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) withrecycleItems. 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-itemonLayout(e.g.useListOnScreenIds) work as they are. - Recycled cells must not keep the previous item's state. Anything a cell reads once at
mount (
useStateinitialisers, 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). GiveImageCachearecyclingKey. - Legend List v3 specifics:
- import
LegendListfrom@legendapp/list/react-native, orAnimatedLegendListfrom@legendapp/list/reanimated(v3 has no root export, andcreateAnimatedComponentdoes not work); - recycling is opt-in (
recycleItems), andgetItemTypeseparates cell kinds; getFixedItemSizeskips measuring when rows have a known height; there is no listgap, so put the gap in the cell;maintainVisibleContentPositionanchors on size changes by default;- a Reanimated offset comes from
sharedValues={{ scrollOffset }}, not a workletonScroll; renderItemmust be an inline callback, not a component that calls hooks.
- import
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.
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/.
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 includesanalyzeTrackand 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.