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

# Maestro E2E Testing

End-to-end flows for Magic Piano's logic, run against the **Release simulator app** (JS bundled) — the same
artifact CI builds on every merge to `dev` and publishes to the package registry. One runner for everything:
[`run-release.sh`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/.maestro/run-release.sh) (`bun run e2e:release`). Full guide: [docs/runtime-provider.md](/docs/runtime-provider.md#e2e-with-maestro).

> Flows are run by a developer or CI. AI agents run them only when the user asks (see
> [testing-and-quality.mdc](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/.cursor/rules/testing-and-quality.mdc)).

## Layout

```
.maestro/
├── run-release.sh                   # prepare simulator -> install Release app clean -> maestro test (JUnit + screenshots)
├── e2e.env                          # the build env the flows assume (sim variant, no film, mock catalog, ...)
├── flows/                           # the suite (run in CI); all play against the MOCK catalog, nothing is shortcut
│   ├── 00-first-run.yaml            # whole first run: intro -> tutorial welcome -> choose a song -> guided first song
│   │                                #   -> its result -> song list -> cold restart
│   ├── 00-smoke.yaml                # clean install -> home with the catalog + tabs
│   ├── 01-navigation-flows.yaml     # tabs, keyboard screen, back stack
│   ├── 02-keyboard-sampler.yaml     # free-play keyboard: zoom, minimap, sustain
│   ├── 03-gameplay-perfect-run.yaml # real run: wrong key ignored, 3 single notes + 1 hold -> Score 58, 3 stars
│   ├── 04-songs-catalog.yaml        # mock catalog listing, search (no match / match), difficulty filter
│   ├── 05-profile.yaml              # edit name, settings, name survives a restart
│   ├── 06-progress.yaml             # a played song shows in the profile (recent song, play count), survives a restart
│   ├── 07-gameplay-pause-replay.yaml # pause menu, replay, resume, leave
│   ├── 08-adaptive-tempo.yaml       # gameplay with the hidden tempo multiplier forced on: stray taps + a wait, score still 58 / 3 stars
│   ├── 09-adaptive-tempo-devtool.yaml  # simulator ↔ desktop DevTool realtime (run via run-adaptive-tempo-devtool.sh)
│   └── 10-adaptive-tempo-snap.yaml  # wait-mode pause snaps the tempo to 0.90 at once (run via run-adaptive-tempo-snap.sh)
├── subflows/                        # launch-app / launch-fresh / connect-dev-client, bootstrap-app, first-run-intro + first-run-tutorial,
│                                    #   open-profile-paywall, expect-paywall-trial, play-mock-song, sleep
├── subscriptions/                   # one folder per monetization arm, several logic flows each (run by run-variants.sh)
│   ├── friendly/                    #   02-user-opened-paywall, 03-launch-paywall
│   ├── balance/  aggressive/  very_aggressive/   # same flows, each states what ITS arm shows (EXPECT_*)
├── run-all-variants.sh              # every arm in turn (writes each arm's env, asks you to restart Metro if needed)
├── run-variants.sh                  # one arm's flows against the Metro you started; set-variant-env.sh writes the arm's env file
├── shop/<arm>/                      # 01-shop-entry (tab + promo row + its row), 02-shop-screen (trial text, tier packs)
├── noads/<arm>/  (area.env: e2e ads) # 01-banner, 02-noads-popup (after the Nth interstitial, buy), 03-buy-from-promo
├── tutorial/<arm>/ (app.env: its tutorial_song) # 01-free-songs: reward picker (2 free songs) or none (3)
├── console/<scenario>/  (area.env: e2e ads) # mon-pkg.json (the console's mon_pkg) + shop / noads flows for what it gives
└── catalog/                         # song-catalog e2e against a local CDN (Debug dev client; `bun run e2e:catalog`)
```

## Running

```bash
bun run e2e:release                                      # newest build published by CI, installed clean
bash .maestro/run-release.sh .maestro/flows/05-profile.yaml     # only some flows
LOCAL=1 bash .maestro/run-release.sh                     # your own build (fastlane ios release_simulator)
SKIP_INSTALL=1 bash .maestro/run-release.sh <flow>       # fast loop: reuse the installed app
RECORD_VIDEO=1 bash .maestro/run-release.sh              # also record build/e2e/video/e2e-run.mp4 (always on CI)
```

Every run writes `build/e2e/`: `report.xml` (JUnit), `artifacts/` (a screenshot + command log of a failing flow) and, with
`RECORD_VIDEO=1` / on CI, `video/e2e-run.mp4` — the whole run at a constant 60 fps (the raw simulator recording is
variable-frame-rate: it only writes frames when the screen changes, so static screens look "low fps" until it is re-encoded).
The folder is git-ignored. On merge requests the suite (`e2e_mr`) is a manual job: play it on the MR pipeline to run the flows and link the video from the MR. It does not start on its own.

Prerequisites: Maestro CLI (`curl -fsSL https://get.maestro.mobile.dev | bash`), Xcode with an iOS simulator, and
for the registry path a `GITLAB_TOKEN` (`read_package_registry`). Building your own app: see the docs link above.

## Per-variant runs (monetization arms): `subscriptions/<arm>/`

**You start Metro; the scripts only run the flows.** The arm is whatever the Metro you run carries, so one arm at a time:

```bash
bun run e2e:env friendly                      # writes .env.development.local for the arm (starts nothing)
bunx expo start --dev-client --clear          # you, in your own terminal (--clear: EXPO_PUBLIC_* is inlined at bundle time)
bun run e2e:subscriptions:friendly            # the arm's flows (02, 03); before the first it checks the bundle carries the arm
FLOW='02-*' bun run e2e:subscriptions:friendly   # one flow of the arm (02 user-opened, 03 launch)
bun run e2e:env clear                         # when you are done: back to ordinary development
```

All arms, one after the other: `bun run e2e:subscriptions` (writes each arm's env file, runs its flows, and when Metro does not
serve the new arm yet it stops and asks you to restart Metro with `--clear`; it removes the env file at the end, `KEEP_ENV=1` keeps it).
Per arm: `e2e:subscriptions:friendly | :balance | :aggressive | :very-aggressive`. To switch arm: `bun run e2e:env <arm>`, restart
Metro with `--clear`. Extra knobs: `RETRIES` (a flow that ends on the XCTest 500 runs again, default 3), `METRO_PORT`, `UDID`,
`SKIP_ARM_CHECK=1`. Reports: `build/e2e/report-subscriptions-<arm>-<flow>.xml`.

Each arm has its own folder and several flows. A flow file is a thin wrapper: it calls a shared subflow
(`subflows/user-opened-paywall`, `launch-paywall`) with what THIS arm shows
(`EXPECT_TRIAL` / `EXPECT_PAYWALL`: `"1"` or `"0"`), so reading one arm's folder tells what it promises.
`src/domain/__tests__/e2e-subscription-expectations.test.ts` checks every value against the arm's real
config. A new topic for the same arms is a new numbered flow per folder (plus its subflow); a new arm is a folder.

**Balance's paywall counts (`subscriptions/balance/04`–`09`, QC checklist G1–G8).** Balance alone also walks the counts behind
each automatic offer: 04 launches 1–4 (paywall from launch 2, the 50%-off offer at launch 3, the paywall again at 4), 05 the offer
at exactly the 15th paywall closed, 06 the VIP press offer (2nd press of a session, once a session; the mock catalog's VIP row
`e2e-vip`), 07 the default paywall at the 6th song start, 08 the home-return paywall after 3 songs, 09 the replay paywall at the 3rd
replay. Every offer looks the same, so the screen names what opened it: `paywall-screen-<screen>` (`selectPaywallMarker`) and
`sale-off-50-screen-<screen>` (`selectDiscountMarker`). Each flow's header states the counts it walks; the expectations test checks
them against the arm. 07–09 play the mock song several times: about 3–6 minutes each. `noads/balance/04-banner-placements` checks
the banner on the pause panel and in Free Mode (Learn's banners stay a device check).

**Why `.env.development.local`:** in a development bundle Expo merges the `.env*` files OVER the shell's env, so your own
`.env.local` (`APP_VARIANT=store`, a `MON_PKG`) beats anything exported before `expo start`: the app would run real ads and the
wrong arm. `.env.development.local` is merged last (git-ignored). It holds `EXPO_PUBLIC_RC_MON_PKG` (the arm; a development-build
switch, hence the dev client), `EXPO_PUBLIC_E2E_IAP=1` (the e2e IAP backend, `src/core/iap/adapters/e2e-iap-service.ts`: a free
player, only the `default` offering has the 3-day trial; the ordinary sim build is AlwaysPremium and keeps every paywall shut),
the sim switches of `e2e.env`, and `EXPO_PUBLIC_ADS_DEBUG=1` (the app's `[ads:paywall]` line in Metro shows the offering and `armTrial`).
Ads are NoAds in this area; `noads/` and `console/` turn on the e2e ads (below).

**Flaky by nature:** right after the app starts, iOS UI automation can fail to read the screen (a 500, `kAXErrorInvalidUIElement`);
Maestro ends the flow as `Unknown error` and does not retry it, so the runner runs such a flow again. Any other failure (an
assertion) is not repeated. The pauses right after launch use `subflows/pause.yaml` (no screen read), not `sleep.yaml`.

### Release build: one app, any arm (`MODE=release`)

No Metro: the script starts a headless DevTool relay (`tools/piano-devtool-desktop/scripts/web.ts`) whose launch default is the
arm (`PIANO_DEVTOOL_LAUNCH_VARIANT`). The relay pushes it (`set_monetization`) to every app that connects, i.e. on each launch, so
a flow's cold restarts keep the arm. The desktop DevTool does the same by hand: **Apply** in the Monetization tab becomes the
default for that phone until you **Clear** it (or restart the relay).

```bash
MODE=release bash .maestro/run-variants.sh friendly     # + LOCAL=1 for your own build, SKIP_INSTALL=1 to reuse the installed app
MODE=release bun run e2e:subscriptions                  # every arm, one after the other
```

The Release app for it is built with `.maestro/e2e.env` plus `EXPO_PUBLIC_ENABLE_DESKTOP_TOOLS=1` (joins the relay),
`EXPO_PUBLIC_E2E_IAP=1` (a free player: the ordinary e2e build is premium and keeps every paywall shut, so this is a separate build
from the one the other flows use).

## Monetization areas: Shop, No Ads, tutorial, Console

The same runner, for more areas: `AREA=<area>` picks the folder under `.maestro/`. As for subscriptions, **you start Metro**;
`e2e:env` writes the folder's env (its area's `area.env` / `app.env`, a console scenario's `mon-pkg.json`).

```bash
bun run e2e:shop        # .maestro/shop/<arm>/      Shop tab, promo row + its row, Shop trial text, tier packs
bun run e2e:noads       # .maestro/noads/<arm>/     e2e banner, Remove Ads popup after the Nth interstitial, buying No Ads
bun run e2e:tutorial    # .maestro/tutorial/<arm>/  the tutorial's free songs
bun run e2e:console     # .maestro/console/<scenario>/  Remote Config values on top of an arm
bun run e2e:monetization   # every area above + subscriptions, one after another
VARIANTS="aggressive" bun run e2e:noads                    # one arm (or one scenario)

# one folder by hand:
AREA=noads bun run e2e:env aggressive                      # its env file
bunx expo start --dev-client --clear                       # you
AREA=noads FLOW='02-*' bash .maestro/run-variants.sh aggressive
```

`MODE=release` carries the arm only (the relay's launch default): the e2e ads, its `app.env` and
a console scenario's extra fields need the dev client + Metro.

What each arm must show, per the arm table (`src/domain/policies/mon-arms/`):

|                                               | friendly     | balance   | aggressive            | very_aggressive       |
| --------------------------------------------- | ------------ | --------- | --------------------- | --------------------- |
| Shop tab + promo row (row 3)                  | no           | no        | yes                   | yes                   |
| Shop "3-Day Free Trial"                       | –            | –         | hidden                | hidden                |
| No Ads tier (lifetime price in the e2e store) | t1 ($9.99)   | t1        | t1                    | t2 ($14.99)           |
| Remove Ads popup                              | never        | never     | after interstitial #3 | after interstitial #3 |
| Banner on a result (free player)              | yes          | yes       | yes                   | yes                   |
| Tutorial free songs                           | 3: no picker | 2: picker | 2: picker             | 2: picker             |

Every flow file is a thin wrapper that hands a shared subflow its arm's `KEY: "value"` expectations, and
[`src/data/__tests__/e2e-monetization-flows.test.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/data/__tests__/e2e-monetization-flows.test.ts) checks
each value against the real config, and which files an arm must or must not have (no `02-shop-screen` without a Shop).
A changed arm or mapper fails `bun test` before it fails a device run.

**Per-area env** (read by `set-variant-env.sh`): `<area>/area.env` — `AREA_E2E_ADS=1` (noads/, console/); a caller's `E2E_ADS=` wins — and `<area>/app.env`
(`EXPO_PUBLIC_*` lines added as they are). The env file also blanks every other `EXPO_PUBLIC_*` switch of your `.env.local`
(a `tutorial_song`, a test pass length, the DevTool): they reach the device the same way, and an empty value reads as unset.
`run-variants.sh` checks the bundle carries the folder's arm, the e2e IAP and, for an area with ads, `EXPO_PUBLIC_E2E_ADS=1`.
The app also logs `[ads:e2e] build appVariant=… ads=… iap=… arm=…` at boot (in your Metro terminal).

### E2E ads (`EXPO_PUBLIC_E2E_ADS=1`)

The e2e ads backend (`src/core/ads/adapters/e2e-ads-service.ts`) draws ads as plain app views a flow can see, count and close —
no SDK, no network, always filled, so a flow tests the app's own ad rules, never an ad network's fill:

| What                    | testID                                    | Notes                                                                             |
| ----------------------- | ----------------------------------------- | --------------------------------------------------------------------------------- |
| Interstitial / rewarded | `e2e-ad-interstitial` / `e2e-ad-rewarded` | full screen over everything; label `E2E <kind> #<n>` (n = since launch)           |
| Close                   | `e2e-ad-close`                            | a rewarded closed here is earned                                                  |
| Banner                  | `e2e-banner`                              | drawn by `BannerHost` where AdMob's would be; slots are `banner-slot-<placement>` |

The entitlement gate applies as in production: a No Ads player gets no interstitial and no banner, and keeps rewarded
(only VIP drops it). App Open and the FSN stay off. Off unless the area turns it on, so the `subscriptions/` flows, written
for an ad-free build, never meet an ad they do not close.

**How the popup is proven** (`subflows/noads-popup.yaml`): the install starts with 5 finished songs
(`launchApp` argument `e2eSongEnds`, `src/bootstrap/e2e-song-ends.ts`), so the first-interstitial gate is open (and
"Learn Mode unlocked!" opens at launch: `to-song-list.yaml` keeps closing it). Songs are played until the popup is up (at most
8\); every interstitial before its turn (`E2E interstitial #1`, `#2`) must close without it. An arm without the popup plays
until the 3rd interstitial and asserts it never opened. Aggressive also shows an interstitial on a song-row tap
(`fs.home_song_click`), and a song-end interstitial opens before the result; the cycle handles both. With the popup up (its
inside fades in: the flow waits for the buy button), the button must show the pack's price in the arm's tier; the flow buys
it (the e2e store's No Ads purchase succeeds) and checks that no interstitial, no banner and no promo row follow.

**The e2e store** (`src/core/iap/adapters/e2e-iap-service.ts`) sells the six No Ads products under `noads_low`
(t1: $1.99 / $4.99 / $9.99) and `noads_high` (t2: $2.99 / $6.99 / $14.99). A No Ads purchase succeeds (owned, dated);
a subscription purchase is still cancelled. In memory only: a fresh install is a free player again.

### Console layer (`console/`)

The three layers a running arm's config comes from: the **baseline** (`mon-arm.ts`), the **arm's overrides**
(`mon-arms/*.ts`) and the **console's** `mon_pkg` fields on top (`src/data/mappers/mon-pkg-mapper.ts`). A console
scenario is a folder with a `mon-pkg.json` — sent as `EXPO_PUBLIC_RC_MON_PKG`, which replaces the console's `mon_pkg`
in a development build and goes through the same mapper — and the shop / noads flows of what it gives. No real
Firebase console is used: it is shared, throttled and not the same from one run to the next.

| Scenario                      | `mon-pkg.json`                              | Checks                                                  |
| ----------------------------- | ------------------------------------------- | ------------------------------------------------------- |
| `friendly-shop-on`            | friendly + `shop.enabled: true`             | Shop + promo show; trial text shown (friendly sells it) |
| `aggressive-shop-off`         | aggressive + `shop.enabled: false`          | no Shop, no promo                                       |
| `aggressive-popup-1d-after-1` | `noads_popup: {after_fs: 1, product: "1d"}` | popup after interstitial #1, 1-day price                |
| `aggressive-banner-row-1`     | `shop.noads_banner.position: 1`             | promo above the first song                              |
| `aggressive-tier-t2`          | `noads.tier: "t2"`                          | Shop packs at t2 prices                                 |
| `aggressive-invalid`          | wrong types / out-of-range values           | exactly plain aggressive                                |
| `friendly-popup-on`           | friendly + `noads_popup.after_fs: 3`        | popup after #3 on an arm that has it off                |

The full matrix (each field, each arm, both ways, invalid values, the fields the console cannot change:
`tutorial.free_songs`, the Shop's trial text) is unit-tested in
[`src/data/__tests__/mon-pkg-console-layer.test.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/data/__tests__/mon-pkg-console-layer.test.ts).

### Tutorial (`tutorial/`)

The first run (Start, welcome, choose one of three songs, the guided first song) with its own console `tutorial_song` (`tutorial/app.env`): a slot plays its song only
when the song is in the catalog and its MIDI is a shipped excerpt, else the Twinkle stand-in — and three stand-ins are one card,
so every arm would end "single", without the picker. The value names the three mock songs on the bundled Twinkle excerpt;
`src/features/tutorial/__tests__/e2e-tutorial-offer.test.ts` proves it offers three. The area runs a free player (the e2e IAP
backend), so the video paywall opens over the song's result (`paywall-screen-intro`) and the flow closes it. The mock songs are all free, so the flow checks the reward picker (2 free songs) or
its absence (3: the full result, left by "Open songs list"), not locked songs.

## The mock catalog and how a song is played for real

In an e2e build (`e2e.env`) the catalog is `src/core/e2e/e2e-mock-catalog.pure.ts`: **E2E Play Song** (easy), **E2E Hard
Song** and **Twinkle Twinkle Little Star** (the tutorial's song), all on one hand-authored chart at 60 BPM:
**C4 single, E4 single, G4 hold (2 s), D4 single**. No remote catalog can override it, and the tutorial's own excerpt
chart is replaced by it. There is no "finish" shortcut: a flow plays the song with real taps.

The game waits on the hit line for each tile (auto-pause), and a tap within 2 s of the tile freezing there is Perfect+,
so a flow needs no clock sync (`subflows/play-mock-song.yaml`): wait for the first tile, then tap the keys in order,
long-pressing the hold. A clean run is 4 x Perfect+ (12) + the hold bonus = **Score 58, 3 stars**. Keys sit at fixed
positions in landscape percentages (A3..C5 at 5%, 15% ... 95% of the width, white-key faces at \~92% of the height).

## How the flows cope with iOS UI automation (read before writing a flow)

- **Build switches** (`e2e.env`): `EXPO_PUBLIC_E2E=1` (no intro film, which would redraw every frame),
  `EXPO_PUBLIC_E2E_MOCK_CATALOG=1`. A flow launches **with** `arguments: { e2eSkipFtue: "1" }` to start past onboarding +
  tutorial (`subflows/launch-app.yaml`; every flow but the first-run one), or without it to walk the first run.
- **Reduce Motion**: `run-release.sh` boots the simulator with iOS Reduce Motion on (`sim:prepare`) so looping animations settle.
- **Orientation (the big one)**: the intro is portrait, everything after it landscape. On a headless simulator iOS UI
  automation takes the device for whatever orientation was last set, so with the wrong one the tree is empty (portrait
  screen, landscape device) or taps land at rotated positions (landscape screen, portrait device). The setting persists
  across runs: every flow sets it explicitly (`setOrientation: LANDSCAPE_LEFT` in `launch-app.yaml`; `PORTRAIT`
  for the intro in `00-first-run.yaml`, then `LANDSCAPE_LEFT`).
- **Not exposed to automation**: some modal controls (name dialog field, settings close X) have no accessibility id.
  Flows type into the focused field + press Enter, or tap by position (`point: "96%,9%"`, landscape percentages).
- **Waits**: always `extendedWaitUntil` after navigation; `subflows/sleep.yaml` for a fixed delay (Maestro has no sleep).

***

## 📦 Automated CI/CD iOS Simulator Builds & Artifacts

### 1. Build Pipeline (currently disabled)

> The simulator build workflow was already disabled on GitHub Actions and was **not** ported when CI moved to GitLab ([`.gitlab-ci.yml`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/.gitlab-ci.yml), see [docs/ci-cd.md](/docs/ci-cd.md)). Build the simulator `.app` locally (`xcodebuild -sdk iphonesimulator`) until a GitLab job (e.g. `artifacts:` + `expire_in: 7 days`) is added; `bun run e2e:download` still targets the old GitHub artifact and will not work.

### 1b. Release simulator app from the GitLab registry (current)

> CI job `sim_release_publish` builds the Release simulator app (JS bundled) when run manually (Run pipeline → `PIPELINE_TARGET=sim-release`) and publishes it to the package registry. `bun run e2e:release` (`.maestro/run-release.sh`) downloads the newest one, boots a simulator, installs it clean and runs `.maestro/flows` with a JUnit report in `build/e2e/`; CI job `e2e_maestro` does the same only when you **Run pipeline → `PIPELINE_TARGET=e2e`**, against the newest published build. A push to `dev` does not start it. Details and Maestro MCP setup: [docs/runtime-provider.md](/docs/runtime-provider.md#release-simulator-build-merge-to-dev).

### 2. Downloading & Installing Artifacts Locally

Legacy flow (needs a pipeline that publishes the `ios-simulator-app-*` GitHub artifact; not available after the GitLab migration):

```bash
# 1. Tải và giải nén artifact iOS simulator mới nhất
bun run e2e:download

# 2. Cài đặt vào simulator đang chạy
xcrun simctl install booted ./artifacts/MagicPiano.app

# 3. Chạy bộ test Maestro
bun run e2e:test
```

***

## 🎵 Song catalog end-to-end (`.maestro/catalog/`)

Drives the real app on a simulator against a local CDN: bundled catalog by default, a newer remote catalog overrides it, a song with no bundled chart downloads its MIDI on demand, and a cold restart (server up or down) serves everything from disk.

```bash
bun run e2e:catalog            # = bash .maestro/catalog/run.sh  (needs a booted simulator with the dev-client build)
```

`run.sh` starts the CDN (`scripts/catalog-e2e-server.ts`) and its own Metro (port 8097, `EXPO_PUBLIC_CATALOG_URL` pointing at the CDN), wipes the catalog's MMKV/media state between scenarios, runs the five flows and asserts what the server saw (request counts). Notes: the sidebar mounts under the loading splash, so `launch.yaml` waits for the splash to disappear; Maestro env defaults (`${APP_ID:-…}`) are not supported by Maestro — pass `-e APP_ID=…`.

***

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