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

# Piano DevTool

One Electron app (also runnable as a plain web server) that replaces the old analytics bridge and
adds MIDI / soundfont sync to the phone. The MIDI visualizer and soundfont lab stay standalone
(`bun run midi:viz`, `bun run soundfont:lab`). Source: [`tools/piano-devtool-desktop`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/tools/piano-devtool-desktop/README.md).
Wire protocol: `@piano/network/devtool-protocol` (shared by the tool and the app).

| Tab            | What it does                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Devices        | **Connect a phone** (QR / LAN) for analytics + library sync; connected phones and sync state; the first sync-capable phone is **auto-selected for Library**; switch with **Use for library** when several are online; **Clear dev data**.                                                                                                                                                                                                                                                                                                                          |
| Analytics      | Live event stream per device, `@piano/analytics` contract validation, contract coverage, saved sessions; **Classic visualizer** sub-tab (no duplicate connect UI — use **Devices**).                                                                                                                                                                                                                                                                                                                                                                               |
| Library & Sync | **Manifest sync** bar (revision, **Push to devices**); upload MIDI / SF2 (SF2 **On relay** list under the drop zone); **App song list** from the phone; **Gameplay** / **Learn**; **add** / **override**.                                                                                                                                                                                                                                                                                                                                                          |
| Monetization   | Per A/B variant (Friendly, Balanced, Aggressive A, Aggressive B, plus experiments): the **ad rules** (`mon_pkg`, `fs_logic`) and the **song list** (order, access switches) from the Song Config sheet, a player preview, **Apply rules to device**, and the Remote Config values to paste. See [Monetization tab](#monetization-tab-songs-and-ad-rules-per-variant).                                                                                                                                                                                              |
| Sound          | Realtime sampler + mixer tuning on a connected phone, a looping test phrase, live meters, and named presets saved on this computer. See [Sound tab](#sound-tab-realtime-audio-tuning).                                                                                                                                                                                                                                                                                                                                                                             |
| Adaptive tempo | Live tracking + tuning of the hidden per-play tempo multiplier: ON/OFF and why (Remote Config, dev override), the live `m`, stats and per-bar decisions of the current / last play, the policy numbers in force, a log of flag / threshold-tuning / play / decision changes (exportable as a `.log` file) and a **play report** for a music specialist (Markdown + per-bar CSV); tuning can be exported / imported as JSON (also accepts a Remote Config `adaptive_tempo` object) and copied as Remote Config JSON. See [Adaptive tempo tab](#adaptive-tempo-tab). |
| Haptics        | Realtime gameplay-haptic tuning on a connected phone: **Light / Medium / Strong** tone bundles, a per-event (Perfect tap, hold complete, miss) **tone** (exact strength + sharpness) or **preset pattern** choice with _Play on phone_, the hold rumble, and the **rush limiter** (target rate, burst, min gap, softest gain) with a synthetic **Rush test** and live requested / played / dropped stats; export / import JSON. See [Haptics tab](#haptics-tab).                                                                                                   |

## Run

```bash
bun run devtool:dev     # Electron + Vite HMR (shell UI hot-reloads)
bun run devtool:web     # production UI build + browser → http://localhost:7799 (no HMR)
bun run devtool:start   # production build in Electron (no HMR)
bun run devtool:dist    # DMG → tools/piano-devtool-desktop/release/
```

Use **`devtool:dev`** while editing the DevTool UI. `devtool:web` / `devtool:start` run `electron-vite build` first — that is intentional for QA/production-like runs, not day-to-day UI work.

`analytics:bridge` and `analytics:desktop:*` remain as aliases. The tool is **not** a Bun workspace;
root scripts install it on demand via [`scripts/ensure-devtool-deps.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/scripts/ensure-devtool-deps.ts)
(the Electron binary is skipped for typecheck/tests and downloaded on first `devtool:dev|start|dist`, which also compiles the `macos-alias` addon the DMG maker needs, since deps install with `--ignore-scripts`). `bun run typecheck` and `bun run test` cover it
(`typecheck:tools`, `//#test:app:tools`).

## Architecture

```mermaid
flowchart LR
  PO[PO uploads .mid / .sf2] --> UI[DevTool UI]
  UI -->|HTTP /api| Lib[(Library: sha256 files + manifest.json)]
  Lib -->|manifest_changed over WS| Phone[App sync client]
  Phone -->|GET /api/files/sha256| Lib
  Phone -->|sync_ack, sync_progress, catalog_snapshot, bundled_chart| UI
  Phone -->|analytics events| UI
```

- **One port** (default `7799`, `PIANO_DEVTOOL_PORT`): static UI, `/api/*` and the WebSocket hub.
- **Control plane = WebSocket JSON, data plane = HTTP.** The WS only carries small messages; files are
  downloaded over HTTP from content-addressed URLs (`sha256`), so a re-push of unchanged files costs nothing.
- **Manifest** `{ revision, songs[], soundfonts[] }` is the desired state. `DevSong` carries
  `{ id, fileName, mode: "add" | "override", meta, midi: { sha256, bytes } }`; `DevSoundFont` carries
  `{ id, name, sha256, bytes, activateOnSync }`. The app diffs it against what it has installed.
- **Hello handshake.** `{ type: "hello", role: "app", protocolVersion, device }`. A hello without
  `protocolVersion` is an analytics-only client. The relay keeps a sync socket and an events socket per
  device so one phone shows up as one device row.
- **Protocol v14** (`DEVTOOL_PROTOCOL_VERSION`; v14 adds the Haptics tab's `haptics_state` / `request_haptics_state` / `set_haptics` / `play_haptic` / `haptic_rush_test`, see [Haptics tab](#haptics-tab); v13 swapped the adaptive-tempo thresholds for the pause-driven tap-windowed model; v12 adds the Timing tab's `timing_state` / `request_timing_state` / `set_timing`, see [Timing tab](#timing-tab); v8 adds `adaptive_tempo_state`, v9 `set_adaptive_tempo` + live signals, v10 `timingZone`, v11 the song / per-bar log / decision context, see [Adaptive tempo tab](#adaptive-tempo-tab)): v2 added the `audio_*` messages below; v3 reshaped their sound to the
  instrument-sampler prototype's model (v4 adds `levels`, v5 adds `limiters`, v6 the master limiter's ceiling / look-ahead / release, v7 `autoPlay`, below; [`sound-model.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/network/src/devtool-protocol/sound-model.ts)). An older
  app never answers (or fails validation on) them and the Sound tab shows no state for it.
- **Security.** Internal QA only: loopback, this machine's own addresses, and private LAN peers
  (RFC1918 / link-local) may connect with no proxy headers; proxied or public-internet clients get
  401\. Caps: MIDI 5 MB, SF2 300 MB.
- **Data** lives in Electron `userData/devtool` (web mode: `~/.piano-devtool`, `PIANO_DEVTOOL_DATA`).

## App side (`src/core/devtool-sync/`)

Enabled only by `EXPO_PUBLIC_ENABLE_DESKTOP_TOOLS=1` (also `true`) — one flag for the analytics WS bridge and MIDI/SF2 sync.
It is **not** gated on `__DEV__`, so a PO can use a release-config internal build. The committed `.env`
turns it on; CI sets it per ref (`0` on `dev`, `main`, `release/ios*` and `v*` tags, the `.env` value on other
branches: [ci-cd.md](/docs/ci-cd.md)). With the flag off, the DevTool graph (sync client, analytics bridge, Settings section) is not bundled:
its entry points `require` it behind a literal `process.env.EXPO_PUBLIC_ENABLE_DESKTOP_TOOLS` test that
release builds fold away. A config test (`config/__tests__/devtool-flag.test.ts`) checks that
no CI workflow or EAS profile defaults it to on and that the store refs stay strictly off.

`EXPO_PUBLIC_FORCE_AUTO_PLAY=1` makes every session start in auto play (`usePianoUiStore.autoPlayMode`, via
`src/features/piano/forced-auto-play.ts`). It only takes effect together with `EXPO_PUBLIC_ENABLE_DESKTOP_TOOLS=1`, and the
Sound tab can still switch auto play off for the run. For a premium user with no ads, pair it with
`EXPO_PUBLIC_APP_VARIANT=sim` (stub IAP that is always premium).

| File                                         | Role                                                                                                                                                    |
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `sync-client.ts`                             | WS state machine: connect, hello, receive `manifest_changed`, install, ack, progress, answer catalog / bundled-chart requests, retry.                   |
| `installer.ts`                               | Download to `<sha>.part`, size check, sha256 check (≤ 32 MB), atomic rename, 3 retries, keep the previous version on failure, sweep unreferenced files. |
| `store.ts`                                   | Persisted installed manifest, active soundfont id, last sync time; live connection / phase / progress / error.                                          |
| `commit-outcome.ts`                          | Persist the outcome and keep the soundfont choice coherent (activate-on-sync, fall back when removed).                                                  |
| `dev-midi.ts`, `dev-library.ts`              | In-memory registry of installed dev MIDI; installed songs / soundfonts for the catalog.                                                                 |
| `dev-soundfonts.ts`, `use-dev-soundfonts.ts` | Installed soundfonts as picker choices (`<root><sha>.sf2` URIs).                                                                                        |
| `status-summary.ts`                          | View model for the Settings "DEV SYNC" section.                                                                                                         |
| `runtime.ts`                                 | `startDevToolSync`, `retryDevToolSync`, `clearDevToolData`.                                                                                             |

Boot wiring lives in `src/bootstrap/devtool-sync.ts` (idle-scheduled from `useBootstrapEntrySDK`): it loads
dev MIDI from disk first (a song pushed yesterday plays today without the desktop), then starts the client.
`core/*` may not import `features/*`, so everything that needs the catalog or sampler settings is composed here.

### Songs

- **Chart precedence** (`getGameplayChart`): dev MIDI registry → bundled `ChartJson` → runtime MIDI.
- **add**: a synthetic catalog entry (free) merged
  by `catalog-merge.ts` into the catalog queries.
- **override**: keeps the catalog id and monetisation, so progress and unlocks are preserved; only the chart changes.
- The preview of an overridden song still uses the bundled chart.

### Soundfonts

`SoundFontSource = number | { id, uri }` flows through the whole SF2 pipeline (sampler, shared bank, PCM
cache, loader, native decoder). A `{ uri }` source skips `Asset.fromModule` and decodes the synced file
directly; the PCM cache treats dev fonts as the same only when the content-hashed `uri` matches.
`sampler-settings-store` holds `devSoundFont` (overrides the bundled `soundFont` while set). The Sound
sheet's `SoundFontChoiceRow` lists synced fonts as extra chips; `bootstrap/dev-soundfont-sync.ts` applies
the persisted / `activateOnSync` choice after each sync and falls back to the bundled font if it was removed.

## Monetization tab (songs and ad rules per variant)

One tab for the PO's A/B setup. A **variant** is one Remote Config condition: a set of ad rules
and its own song list. Flow, top to bottom:

1. **Songs from the sheet.** **Fetch sheet** imports the Song Config sheet with the same CSV
   conversion as the build-time sync. The sheet keeps its own format: every variant starts from
   it, and songs a variant has not changed follow it on each fetch. **Source & backup** holds the
   sheet link, the minimum app version, and workspace import. **Export workspace** saves a backup.
2. **Pick a variant.**
   - The four arms are fixed: Friendly (the default, no arm = Friendly), Balanced, Aggressive A
     (`aggressive`, the cheap No Ads pack) and Aggressive B (`very_aggressive`, the expensive one).
   - **Duplicate as experiment** copies the selected variant's songs **and** rules under a new id
     (lower case, starting with a letter). The copy keeps that variant's arm, so its exported
     `mon_pkg.variant` is an arm the app runs; its card reads e.g. "Experiment A · Aggressive
     rules". Experiments can be deleted; the four arms cannot.
   - **Copy rules from device** takes the phone's running rules into its arm.
3. **Ad rules.** The rows of `mon_pkg` (interstitials, Learn, FSN, App Open, rewarded video, Shop and
   No Ads), read with the app's `mon_pkg` parser and arm defaults. Grey "Default" is what the arm
   does on its own; a changed value is an override, with **Use default** per row and **Clear rule
   overrides** for the variant. Lifetime bonus songs must be in this variant's song list.
4. **Song list.** The selected variant's songs, in its order:
   - Visible, Premium, Ads unlock, IAP, Public domain and Learn Mode are inline switches. FALSE is an
     explicit override; turning Learn Mode off removes both Learn links from the export. Changed
     switches are marked, each with a reset arrow; a row arrow resets the song, and **Reset songs to
     sheet** drops every song change of the variant.
   - Drag any row into place (switches still click), or hover for ↑ ↓. While dragging, the dragged
     row dims and the row under the pointer shows a full-width line on the edge the song lands on.
     Moving renumbers only this variant's `sortOrder`. Reordering is off while a filter is on.
   - Song identity, difficulty and every MIDI / audio link come from the sheet and are read-only.
   - **Chart** shows the sheet's level and the tempo of the song's MIDI (the sheet has no tempo
     column): the first tempo, or the range when it changes, "no MIDI" for a song without one.
     After each fetch the server reads the MIDI of each exported song (its full MIDI, else its first
     part) with the game's parser: only links from its last export, four at a time, each once per
     run. Songs it cannot read are named in a warning; tempos are kept with the workspace.
5. **What the player sees.** Game/Learn, VIP, owned IDs and watched videos → each song's gate, from
   this variant's own songs and rules, including the first-three-row `rv2` rule.
6. **Remote Config values.** Per variant, copy or save `mon_pkg` (JSON), `song_catalog` (the app's
   envelope: `version`, `songs` — no app-version gate: target builds with the Firebase condition) and `fs_logic` (the bare `0` / `1`), and paste each
   into that variant's Firebase condition. The JSON preview switches between effective rules and
   the selected variant's full `song_catalog` payload; changing variants updates that preview.
   Copying the catalog from its preview or the export button reserves a fresh version; saving it
   also refreshes the version.
   **Save all variants** writes every variant's values in
   one review file. `song_catalog` versions increase across exports, even within one second; an
   empty song list cannot be exported; exports omit the checksum rather than reuse the sheet's.
   Malformed rules or a missing bonus song block the `mon_pkg` / `fs_logic` export and Apply.
   Publication remains manual.

**Apply rules to device** sends the selected variant's `mon_pkg` (its arm, no song pools) and
`fs_logic` through the paired relay; the phone's song list stays as its Remote Config has it.
Only desktop-tools builds mount the provider. Overrides live in memory for the app session; **Back
to Remote Config** clears them. Apply / clear during Play or Learn waits until that screen is left.
The device line shows pending / error / active and the running arm. Older builds time out with an
unsupported / offline message. Rozenite remains the place for runtime counters, ad decision traces
and parser debugging.

**Storage.** The workspace (sheet snapshot, per-variant song overrides and rules, tempos) saves in
the renderer's localStorage under `piano-variant-workspace-v2`. On the first open it is built from
the two older saves, which stay untouched: songs from `piano-catalog-workspace-v1`, rules per arm
from `piano-monetization-v2`. Song pools and "no arm" rules are dropped and a custom catalog variant
starts from Friendly's rules, each with a note. **Import workspace** takes a workspace backup, or an
older Catalog backup (merged under the current rules); invalid files leave the workspace intact.
Re-fetching keeps overrides by song id, warns about changed songs and removed songs with overrides,
and leaves removed songs out of exports. A failed fetch keeps the previous workspace.

- Fetch API: `POST /api/catalog/export` `{ sheetUrl? }`, `GET /api/catalog/defaults`,
  `POST /api/catalog/chart-bpm` `{ ids }` → `{ songs: { [id]: { url, bpm, min, max } | null } }`.
  Only Google Sheets HTTPS URLs are fetched for the sheet. Repo checkouts keep bundled file names;
  packaged builds derive them from the sheet. Malformed rows are skipped with warnings.
- Layers: `renderer/variants/model.ts` (the workspace: variants, rules, exports, tempos) and
  `migrate.ts` are pure, over `renderer/catalog/model.ts` (song inheritance, order, refresh) and
  `renderer/monetization/model.ts` (rule rows, preview, validation); `variants/store.ts` holds the
  flows and display selectors; `variants/service.ts` does API, storage and file I/O;
  `server/chart-bpm.ts` reads tempos.

Full publishing workflow and limits: [features/catalog.md](/docs/features/catalog.md#publishing-a-remote-catalog-po-workflow).

## Sound tab (realtime audio tuning)

A Music Specialist tunes the app's piano sound while it plays. Edits are **live on the device**; nothing is
written into the repo until a developer bakes an approved sound into the defaults.

**The model.** The sound is the [instrument-sampler prototype](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/network/src/devtool-protocol/sound-model.ts)'s, one
piano group, in its units: `envelope` (attack / hold / decay / sustain dB / release; `null` = the SoundFont's own),
`tone` (filter, filter envelope, vibrato, spread, tune, drift — each block switches between the SoundFont's own and
custom), `velocity` (soft / linear / hard curve + 1…127 range), `mix` (volume dB, pan, mute, solo), `sends` (auto balance
or manual dry / reverb / delay), `inserts` (compressor → amp → EQ → modulation), the shared `reverb` and `delay` buses
(room type, pre-delay, decay, damping, size, diffusion, cuts, return; ping-pong, tempo sync, feedback, cuts, wobble,
return) `master` (volume dB, 3-band EQ, limiter on / off with ceiling, look-ahead and release) `levels` (SFX / preview / music output level in dB: SFX and
preview cut only, music −60…+6; the bottom of a fader is silent) and `limiters` (a look-ahead limiter per SFX /
backing / preview bus: on, input dB, ceiling dB, look-ahead ms, release ms). Defaults, every range and the clamping live there once
(`DEFAULT_SOUND`, `SOUND_RANGES`, `mergeSound`); the DevTool sliders and the app's clamp read the same table.

**Messages** (`packages/network/src/devtool-protocol/audio.ts`, validated with valibot on both ends):

| Direction | Message                 | Purpose                                                                                                                                                                                                                                            |
| --------- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| UI → app  | `request_audio_state`   | Ask for the full state (sent on selecting a device).                                                                                                                                                                                               |
| UI → app  | `set_audio`             | Deep-partial patch of the sound, plus `soundFont?` and `autoPlay?` (gameplay auto play). Values are clamped by `mergeSound`. A `soundFont` patch decodes on the device (async — expect extra `audio_state` pushes while `loading`).                |
| UI → app  | `audio_action`          | `test_phrase_start`, `test_phrase_stop`, `reset_defaults`, `all_notes_off`.                                                                                                                                                                        |
| UI → app  | `audio_meter_subscribe` | Start / stop the 100 ms meter stream.                                                                                                                                                                                                              |
| app → UI  | `audio_state`           | The full sound, the loaded SF2's own envelope (`soundFontEnvelope`, the starting point of the envelope sliders), active **soundfont**, load status, the **choice list**, test phrase state, `autoPlay` / `autoPlayAvailable`. Coalesced at 120 ms. |
| app → UI  | `audio_meter`           | Peak, RMS, CPU load, active voices, clipping (a metric the backend cannot measure is `null`).                                                                                                                                                      |
| app → UI  | `audio_error`           | A rejected or failed request.                                                                                                                                                                                                                      |

The relay forwards the four UI → app messages to the sync socket of the chosen `deviceId` (anything
that fails `ServerToAppSchema` is dropped), broadcasts the app → UI frames tagged with the `deviceId`, and
turns meters off on the phone when the last UI client disconnects.

**App side.** `audio-control-port.ts` (the port), `audio-sound-state.ts` (the session-only Sound being edited),
`audio-sound.ts` (the Sound → engine config / mixer conversion), `audio-test-phrase.ts` (looping phrase) and
`src/bootstrap/devtool-audio.ts` (composition with the real stores) — details in
[audio-engine.md](/docs/audio-engine.md#tuning-the-sound). The Sound is session-only: a launch starts from `DEFAULT_SOUND`
and **Reset to app defaults** returns to it.

**Auto play.** Gameplay auto play (`usePianoUiStore.autoPlayMode`) is switched from the Sound tab's **Auto play** checkbox only — the AUTO pill on the song list is gone. It rides `set_audio` / `audio_state`, is session-only (a relaunch starts off) and stays on if the desktop disconnects. Remote Config `auto_play` still gates it on release builds (`autoPlayAvailable`; dev builds always allow it).

**UI.** Laid out like the prototype's screen: the **Soundfont** dropdown at the top, then collapsible sections —
**Piano** (page tabs **Mix & sends** / **Inserts** / **Sound**; the Sound page has **Envelope** / **Filter** /
**Pitch & stereo** / **Velocity** chips, and a one-line summary shows while a section is closed), **Effect buses
(shared)** (reverb with room-type chips, delay with ping-pong / note-value chips), **Master** (a boost above 0 dB is real: it rides the limiter's input gain) and
**App levels & limiters** (SFX, Preview, Music faders and a limiter card per bus). Sections start
collapsed except Piano and are remembered in `localStorage`. Sliders send at most one patch per 40 ms; after a local
edit the device echo is ignored for 500 ms so a slider never jumps back. Readouts and snapping (−∞ at the bottom of
a fader, "off" near zero, 20 kHz = open) follow the prototype. A dot marks controls that differ from the baseline.

**Export.** **Copy as TS defaults** copies the whole sound as a literal for `SOUND_DEFAULTS` in `sound-model.ts`; the
engine and mixer defaults are then updated to match (the parity test in `audio-sound.test.ts` lists what differs).
**Set baseline here** marks the reference for the “changed” dots.

**Presets · import / export.** The **Presets** card (`SoundPresets.tsx`) keeps named sounds in `audio-presets.json` on
the Mac (≤ 100, names unique case-insensitively): **Save current** (name + optional note), **Load** (sends the whole
sound to the phone as one `set_audio` patch), **Delete**. **Export current** / per-row **Export** / **Export all**
download a `.json` file; **Import** (drop or choose a file) merges it into the bank through `POST
/api/audio-presets/import`, replacing same-named presets and reporting how many were added / replaced. The file is one
format, `{ version: 1, presets: [{ name, updatedAt, note?, sound }] }` (a single config is a bank of one); import also
accepts a lone preset object or a bare `sound`, named after the file. Only the shape is validated on import — the app
clamps every value (`mergeSound`) when the sound is loaded. The SoundFont choice is not part of a preset. Pure helpers
and tests: `lib/sound-presets-io.ts`, `tests/sound-presets-io.test.ts`.

**Not in the Sound tab (prototype only).** The prototype's guitar groups, song player / BGM, tap-velocity source,
BGM ducking, "Clear tails" and compressor GR meter have no counterpart in the app (no guitars, no recorded backing,
no native tail clear / GR read-out), so they are not offered.

## Adaptive tempo tab

Live view and tuning of [adaptive tempo](/docs/adaptive-tempo.md) on a connected phone: a gauge and a chart of `m` / target over the play (song tempo 1.0 as the reference, decision dots), a tap-offset meter with the lag gate drawn on it, and a **Tune live** panel — dev mode (`rc` / `off` / `default`), presets and a slider per threshold. A threshold change reaches the running play at once; mode and profile apply from the next play. Tuning is honoured by a development build and by any build with the desktop tools compiled in (`EXPO_PUBLIC_ENABLE_DESKTOP_TOOLS=1`, e.g. an internal release build; `dev.honoured`), never by a store build and is persisted on the phone (MMKV `adaptive-tempo-dev`).

| Direction | Message                        | Purpose                                                                                                                                                                                                                                                                                                                                                                                                                              |
| --------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| UI → app  | `request_adaptive_tempo_state` | Ask for the state (sent when the tab opens or the device changes).                                                                                                                                                                                                                                                                                                                                                                   |
| UI → app  | `set_adaptive_tempo` (v9)      | `patch`: `devMode`, `thresholds` (merged into the live tuning), `clear` (keys back to profile / Remote Config), `reset` (drop all tuning first). `forceM` (one-shot: jump the running play's multiplier now with a 1 s ramp, clamped 0.3–1; a fresh watch window starts). The app answers with a fresh `adaptive_tempo_state`.                                                                                                       |
| app → UI  | `adaptive_tempo_state`         | `remote` (Remote Config `enabled` / `profile` / threshold overrides, live), `dev` (override mode, `honoured` in a development or desktop-tools build), `effective` (outcome of both), `config` (the policy numbers in force), `tuning` (the thresholds set from the DevTool) and `play` (`null` until a normal-song play mounted; v11 adds `song`, `bars` and the musical context of each decision, see below). Coalesced at 250 ms. |

`play` carries the song, whether the policy ran (`active`, else `inactiveReason`: `off (rc)`, `off (dev)`, `not a normal song`, `no wait mode`), `playing` (false once left — the last play stays visible), the live `m` / target / floor, `lagMs` (median tap offset), the running stats (min / mean `m`, floor hits, auto-pauses, median pause wait, notes, strays, play time) and the last 40 decisions (bar tick, target `m`, reason). The tab also keeps a per-device **Changes** log (Remote Config or dev override flips, effective ON/OFF, play started / ended) with timestamps — that is the answer to "when did it turn on".

**Zones wording (tempo logic).** Perfect+ / Perfect / Great are **± zones** around the hit line — the late side mirrors the early one below it (× `pauseZoneScale`: _Perfect late_, _Great late_) — and only **Early** (before the line) and **Late** (after it) are one-sided, with **Late = a pause** (no tap by the Great-late edge). The Zones card of the simulation and the tuning group _Zones · Late = pause_ use these words.

**Simulation (desktop only, no protocol).** The tab's left card runs the REAL policy (`createAdaptiveTempo` + the engine's tempo-ramp maths, imported from `@rhythm/engine`) against a synthetic song and a model player the way the app's adapter drives it in wait mode: bar lines are evaluated before the notes on them, a late tap inside the mirrored pause zone is a late Perfect / Great, a longer freeze is an auto-pause (and may snap the tempo), and the windows come from the Timing tab. It reads the numbers being edited — the device's `config` over the sliders' local drafts — so a threshold change reshapes the curve at once, and can be compared with the profile's own numbers (no tuning) for the same player. Shown: the multiplier over the bars (floor / ceiling / the player's comfort tempo, a dot per decision with its reason), the auto-pauses, a stats table (final / min / max / mean tempo, settled-from bar, decisions, direction changes, pauses, Perfect share, time frozen) and the decision list. The **player** is a model: a comfort tempo (× the song's), a late habit, jitter, blank rate and an optional hard stretch; pressure = tempo in force / comfort, and above 1 the player gets later, jitterier and blanks more. A **Scenario** picker replaces the constant skill with a player whose skill changes during the song (bad start then recovers, tires, swings, taps late…; the dotted purple line is then the comfort curve). The tab's **Presets** include _Smooth_ and _Calm_ (simulator-tuned, see [adaptive-tempo.md §12](/docs/adaptive-tempo.md)). Deterministic per seed. It checks the policy's logic and sensitivity, not real input latency or audio. Code: `lib/adaptive-sim.ts` (pure, `tests/adaptive-sim.test.ts`), `components/adaptive-simulator.tsx`.

**Play report (v11).** The **Play report** card exports what a music specialist needs without the build:

- `adaptive-tempo-report-<time>.md` — song (authored BPM, time signature, bars, length), summary (min / mean `m` and the BPM that means, accuracy, auto-pauses), every **tempo decision** in words (bar, song time, `m` and BPM before → after, why, lag, recent pauses), a **bar-by-bar** table (BPM, `m`, Perfect / Great / Early / Late / Miss, auto-pauses, strays, median tap offset), a **note-by-note** table (bar, beat in the bar, song time, pitch, judgement, tap offset, pause wait, strays, `m`, BPM), the policy numbers in force and a short "how to read this".
- `adaptive-tempo-bars-<time>.csv` — one row per bar for a spreadsheet; the bar where the tempo was decided also carries the decision (reason code, new `m` / BPM, signals).
- `adaptive-tempo-notes-<time>.csv` — one row per judged note (MIDI key + pitch name, beat, judgement, offset, pause, `m`, BPM); an empty offset is a miss. Notes can be exported **while playing**: a live push carries only the notes the desktop has not seen (`play.notesFrom` = index of `notes[0]`; the sync client keeps the cursor per connection, a `request_adaptive_tempo_state` or a reconnect resends all), the desktop appends them (`mergeNoteDelta`) and asks for the full state when a delta does not continue what it holds. Up to 1500 notes are kept.

The Changes log gets one `Decision — Bar 12 (0:34.2): 1.00 → 0.90 (120 → 108 BPM) — slow down — …` line per decision, and the development console line (`[adaptive-tempo] … decision bar=12 t=34.3s m=1.00→0.90 bpm=120.0→108.0 lag=+82ms pauses=2 …`) carries the same fields. Bars and decisions use the song time without the intro padding, so they line up with the audio; bar `n` is the n-th bar from the song start, a decision at its line applies from that bar on. At most 400 bars and 200 decisions are kept per play. The new wire fields are optional, so an older app simply produces a report without bar data.

**App side.** `features/piano/adaptive-tempo/recorder.ts` records the play (fed by `useAdaptiveTempo` only in a development build or when `EXPO_PUBLIC_ENABLE_DESKTOP_TOOLS=1`; a store build records nothing), `devtool-port.ts` composes it with the live Remote Config and dev stores into `core/devtool-sync/adaptive-tempo-control.ts`, wired in `bootstrap/devtool-sync.ts`.

## Timing tab

Live editing of the hit windows on a connected phone, in musical units. A zone is a **subdivision per beat** (`sub`): its length is `60000 / (BPM × sub)` ms — the same maths as the [delay-time table](https://anotherproducer.com/online-tools-for-musicians/delay-reverb-time-calculator/). At the reference 120 BPM `sub 1` = 1/4 = 500 ms, `sub 2` = 1/8 = 250 ms, `sub 4` = 1/16 = 125 ms, `sub 16` = 1/64 = 31.25 ms; dotted is `sub × 2/3`, triplet `sub × 3/2`. A bigger `sub` is a **shorter** window.

Factory ladder (`BASE_TIMING_SUBDIVISIONS`, [`judgement-window-scaling.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/piano/judgement-window-scaling.ts)):

| Zone               | sub | note | ms @ 120 |
| ------------------ | --- | ---- | -------- |
| Perfect+           | 8   | 1/32 | 62.5     |
| Perfect late grace | 4   | 1/16 | 125      |
| Perfect            | 4   | 1/16 | 125      |
| Great late grace   | 2   | 1/8  | 250      |
| Great              | 2   | 1/8  | 250      |
| Too early          | 1   | 1/4  | 500      |
| Audio quantize     | 4   | 1/16 | 125      |

Live window for a song at `bpm`: `clamp(ms@120 × (120 / bpm) ^ bpmScale)`. `bpmScale` 1 (default) is exactly `60000 / (bpm × sub)` — beat-proportional, so a fast song has shorter windows in ms but the same musical length; 0 keeps the same ms at every tempo; in between blends. Audio quantize is always beat-proportional. The app clamps every value (`TIMING_WINDOW_MS_CLAMPS`, ordering Perfect+ \< Perfect \< Great \< Too early) and answers with what it holds.

**Simulation (left, pinned while you edit).** A ruler of the zones on a time axis against the song's beat grid, a lane drawn like the in-app timing layer (hit line, Perfect / Perfect+ bands, Great and Too-early lines, the audio-quantize band, beat / bar lines) with falling notes, and a table of each zone's edge in ms, lane px and note value at the preview BPM. An **auto player** taps every note at a chosen offset ± jitter (or **Manual**: Space / Tap) and the judgement counts show what a tapper at that offset would get. It reads the draft values, so a slider reshapes the zones before the device has answered. Pure model: `lib/timing-visual.ts` (`liveWindows`, `classifyOffsetMs` — parity-tested against the engine's `classifyHit`).

The controls: a number box (sub/beat) + slider (ms @ 120, bounded by the app's clamps) + "snap to note" per zone, with the note name, ms @ 120, ms and lane px at a **preview BPM**; a BPM-scale slider; presets (Factory, Ladder A tight, Dotted / triplet, Legacy ms = the pre-subdivision 32 / 190 / 25 / 465 / 692 at every tempo for an A/B); **Export… / Import…** a `.json` (`{ kind: "piano-timing-config", version: 1, subdivisions, quantizeSubdivision, bpmScale, msAt120Bpm }`; an import also accepts a bare map of subdivisions or ms @ 120 and replaces the whole config). Moving a slider writes the app's persisted hit-window / quantize stores (the ones the in-app TimingPanel edits), so the next tap of the running song uses it and it survives a relaunch.

| Direction | Message                | Purpose                                                                                                                                                                                                                                                                                                                                                                              |
| --------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| UI → app  | `request_timing_state` | Ask for the state (sent when the tab opens or the device changes).                                                                                                                                                                                                                                                                                                                   |
| UI → app  | `set_timing` (v12)     | `patch`: `subdivisions` (any of `perfectPlus` / `perfect` / `perfectLate` / `great` / `early`, plus the optional `greatLate` — extra Great grace past `perfectLate`, `0` = off; "Great late grace" row in the Timing tab), `quantizeSubdivision`, `bpmScale`, `reset` (factory first). One zone cascades its neighbours like a TimingPanel drag; several zones are applied as a set. |
| app → UI  | `timing_state`         | `config` (what the app scores with), `factory`, `referenceBpm` (120) and `limits` (ms @ 120 per zone, quantize, `bpmScale`). Coalesced at 120 ms.                                                                                                                                                                                                                                    |

App side: [`timing-devtool-model.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/piano/timing-devtool-model.ts) (pure: ms @ 120 ↔ sub, patch → clamped snapshot), [`timing-devtool-port.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/piano/timing-devtool-port.ts) (the stores) behind `TimingControlPort` ([`timing-control.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/devtool-sync/timing-control.ts)). Desktop: `tabs/TimingTab.tsx`, `lib/timing.ts`.

## Haptics tab

Live tuning of the gameplay haptics on a connected phone (physical device only — the simulator has no Taptic Engine). Changes apply to the next haptic of the running song and persist on the phone **in a build with `EXPO_PUBLIC_ENABLE_DESKTOP_TOOLS=1`**; any other build boots on the factory numbers, so a tuned value can never reach a store build.

- **Strength — Light / Medium / Strong.** One click switches the Perfect tap and hold-complete to a `tone` of that strength and sets the hold rumble (Medium ≈ today's Perfect tap). The badge shows which bundle the phone matches (`factory presets` / `custom` otherwise).
- **Factory numbers** (`FACTORY_HAPTIC_CONFIG`, tuned by the PO from this tab on 23/10/2026; what every build plays until the DevTool changes it): Perfect tap and Hold complete as tones (0.5 / 0.35 and 0.5 / 0.3), hold rumble 0.32 / 0.22 (progressive: start 0.4 × over the first 0.5 of the tail), Miss off, rush limiter 9 taps/s · burst 3 · min gap 40 ms · softest 0.5 · window 450 ms. A build whose native module lacks `playDiscrete` falls back to each event's `preset` (`heavyTap`, `warning`, `noteMiss`).
- **Per event** (Perfect tap, Hold complete, Miss): enable, and either a **Tone** — one tap at an exact _Strength_ and _Sharpness_, played with Pulsar's `RealtimeComposer_playDiscrete` — or a **Preset pattern** (a fixed Pulsar pattern picked by its app-level intent; Pulsar has no intensity knob for these, so the limiter cannot soften them). _Play on phone_ fires the event as configured, skipping the limiter. Miss is off by default (Game Mode has no miss haptic today).
- **Hold rumble.** Enable, strength and sharpness of the sustained rumble (`Haptics.startGameHold`). Keep sharpness low — a sharp sustained event makes the Taptic Engine buzz audibly. **Progressive ramp** (factory on, 29/10/2026): the rumble starts at _Start level_ × _Strength_ (0.4) and rises linearly to _Strength_ (the max) over _Ramp length_ of the tail (0.5 = the first half), then stays at the max; a short tail ends mid-ramp. _Flat_ plays _Strength_ for the whole hold. _Play 1 s_ previews it as a 1.2 s hold. Pure math in [`hold-ramp.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/services/haptics/hold-ramp.ts), driven by [`hold-ramp-driver.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/services/haptics/hold-ramp-driver.ts) (re-sets the realtime composer every 50 ms only while a ramp climbs; a chord plays its strongest ramp). The controls are hidden for an app build that does not send the fields.
- **Rush limiter** ([`rush-limiter.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/packages/network/src/haptics/rush-limiter.ts), in `@piano/network/haptics` so the app and the tab's chart run the same code). On a rush chart (Rush E) the old fixed 30 ms window still allowed \~33 native calls/s, which smear into a buzz and cost JS-thread time. The limiter keeps ordinary play untouched and thins only sustained density: a **min gap** (also merges a chord into one haptic), a **token bucket** (`burst` taps back to back, then refilled at `targetRatePerSec`), and **softening** of the surviving tone taps by `target / density` (floored at `minGain`). Density is measured at run time over `windowMs` — no per-song BPM. Hold-complete is never density-limited; a miss is dropped right after a fired tap. Dropped taps never reach the native engine. Presets: Off (only the 30 ms floor), Balanced (the factory limiter), Calm.
- **Limiter preview chart.** Under the engine sliders, a chart runs the same limiter code over a synthetic stream (BPM × subdivision, seconds, chord size — `simulateRush` in `@piano/network/haptics`) and redraws as a slider is dragged: one row shows every note asked (grey = played, red = dropped), the other the haptics played, with bar height = strength. It shows which notes would play and how strong, not how it feels. The first 3 s are drawn; the totals (asked / played per second, dropped share, softest strength) cover the whole stream.
- **Rush test & live stats.** Feeds a synthetic `BPM × subdivision` stream (optionally chords) through the real limiter and the Taptic Engine, so a rush chart can be felt without playing it; the stats show asked vs played rate and the dropped share, and a live chart plots the phone's last 20 s of asked vs played rate against the target (from the test or from real play; it falls to zero when the phone goes quiet).

| Direction | Message                 | Purpose                                                                                                                                                                                                                                                                                                                                                        |
| --------- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| UI → app  | `request_haptics_state` | Ask for the state (sent when the tab opens or the device changes).                                                                                                                                                                                                                                                                                             |
| UI → app  | `set_haptics` (v14)     | `patch`: any of `tap` / `holdComplete` / `miss` (`enabled`, `mode` `tone`\|`preset`, `amplitude`, `sharpness`, `preset`), `hold` (`enabled`, `amplitude`, `sharpness`), `rush` (`enabled`, `targetRatePerSec`, `burst`, `minGapMs`, `minGain`, `windowMs`); `reset: true` first returns to the factory numbers. The app clamps and answers with what it holds. |
| UI → app  | `play_haptic`           | `event`: `tap` \| `holdComplete` \| `miss` \| `hold` (about a second) — plays it now, ignoring the limiter.                                                                                                                                                                                                                                                    |
| UI → app  | `haptic_rush_test`      | `run`, and for a start `bpm`, `subdivision`, `seconds`, `chord` (clamped by the app).                                                                                                                                                                                                                                                                          |
| app → UI  | `haptics_state`         | `config`, `factory`, `limits`, the `presets` an event can pick, limiter `stats` (requested / fired / dropped, rates) and `rushTestRunning`. Coalesced at 150 ms.                                                                                                                                                                                               |

App side: [`gameplay-config.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/services/haptics/gameplay-config.ts) (pure config, factory, clamps), [`gameplay-config-state.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/services/haptics/gameplay-config-state.ts) (live holder), [`gameplay-config-persist.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/services/haptics/gameplay-config-persist.ts) (MMKV, desktop-tools builds only), `Haptics.playGameEvent("tap" | "holdComplete" | "miss")` / `startGameHold()` in [`engine.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/services/haptics/engine.ts) (the gameplay call sites in `useMagicJudgement` and `tap-decorations-defer`), and [`haptics-control.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/devtool-sync/haptics-control.ts) (the port + rush-test runner [`rush-test.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/services/haptics/rush-test.ts)). `Haptics.play(intent)` is unchanged for UI, Learn and tutorial haptics. Desktop: [`HapticsTab.tsx`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/tools/piano-devtool-desktop/src/renderer/tabs/HapticsTab.tsx), [`lib/haptics.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/tools/piano-devtool-desktop/src/renderer/lib/haptics.ts) (bundles, presets, export / import `piano-haptics-config`).

**Device-unverified:** how `RealtimeComposer_playDiscrete` behaves while a hold's `RealtimeComposer_set` rumble is active (shared native composer — the source is in the Pulsar pod binary). If it ducks the hold, fall back to a cached `PatternComposer` single-tap pattern per quantized (strength, sharpness).

## Settings

With the flag on, Settings shows **DEV SYNC**: connection, aggregate status (e.g. **Syncing 42%**), per-file
**MIDI** / **SoundFont** rows with download percent while syncing, library counts, last sync, the last error,
**Retry sync** and **Clear synced data**. On the desktop, **Devices** shows the same per-item percent and
progress bars; **Library** upload shows percent while pushing MIDI or SF2 to the relay.

The same flag (or a development build) also shows **ADS QA**: QA: Drop FS close, QA: FSN Off and QA: FSN
No-fill, with a reminder line at the top of the screen while any is on — see
[admob-integration.md §9](/docs/admob-integration.md#9-qa--admob-ad-inspector).

## TestFlight / physical device (no Metro)

- The phone must reach the Mac over **LAN** (same Wi‑Fi, or Mac joined to the iPhone **Personal Hotspot**).
  **4G alone cannot open** `ws://172.16.x` / `192.168.x` on your Mac. If Safari on the phone cannot load
  `http://<mac-lan-ip>:7799`, fix network/firewall/AP isolation before debugging QR or deeplinks.
- Pairing uses the QR deeplink (`magicpiano://analytics-bridge?url=ws://…`) — TestFlight never auto-connects
  via Metro. Scan once; the app persists the endpoint in MMKV.
- Internal iOS builds with `EXPO_PUBLIC_ENABLE_DESKTOP_TOOLS=1` add **`NSLocalNetworkUsageDescription`** (`plugins/withDevtoolLocalNetwork.ts`).
  After install, allow **Settings → Privacy & Security → Local Network → Magic Piano** if iOS prompts or blocks the socket.

## Known limitations

- Backing tracks (BGM) are intentionally not synced.
- Downloads retry from scratch; there is no HTTP `Range` resume.
- sha256 verification is skipped above 32 MB (hashing needs the file in memory); a size check still applies.
- **Clear dev data** is undone by the next reconnect, because the relay re-pushes the manifest on hello.
  Remove the SF2 from **On relay** under the SF2 upload card, or a dev song via **App song list → Remove**, to make it permanent.

## Tests

- Tool: `bun test --isolate tools/piano-devtool-desktop` (`bun run test:app:tools`) — includes `tests/audio.test.ts` (relay routing, presets), `tests/audio-control.test.ts` (ranges, patch batching, TS export) and `tests/sound-format.test.ts` (readouts), `tests/catalog-export.test.ts` + `tests/catalog-export-lib.test.ts` (sheet → catalog export), `tests/catalog-chart-bpm.test.ts` (tempos from MIDI), `tests/catalog-editor.test.ts` (song inheritance, order, drop edge) and `tests/variants/*.test.ts` (Monetization tab workspace, migration, store flows).
- Protocol: `packages/network/tests/haptics-protocol.test.ts`, `packages/network/tests/devtool-protocol.test.ts`, `packages/network/tests/audio-protocol.test.ts`, `packages/network/tests/sound-model.test.ts`.
- App: `src/core/devtool-sync/__tests__` (incl. `haptics-control.test.ts`), `src/core/services/haptics/__tests__` (rush limiter, config, game events, rush test), `src/bootstrap/__tests__`, `src/features/catalog/__tests__`, `src/features/settings`.

***

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