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

# Feature — Cross Promotion

This app is the **destination** of cross promotion. A player taps a promo in another Amanotes
app (the source app) and arrives here through an AppsFlyer OneLink. The app then:

1. reads the link's `xp_uid` (the source app's click id) and keeps the first one for good, as the
   user property `xp_uid`;
2. brings the promoted song or genre up on the Song List, once the player is past the first run,
   and sends `crosspromo_deeplink_open`;
3. sends `map_user_id` at every session start, which joins the AppsFlyer id to this install's
   Firebase ids, so BigQuery can match a player across apps.

Both events are Firebase only. Params and timing: [analytics-events.md § Cross
Promotion](/docs/analytics-events.md#cross-promotion). iOS only. The rules follow MagicPad's
implementation of the same Amanotes spec, except where noted below.

## Flow

```mermaid
flowchart LR
  af["AppsFlyer SDK<br/>deep link (UDL) +<br/>conversion data"] --> intake["Intake<br/>CrossPromoDeepLinkFlow"]
  intake -->|"open with a real xp_uid"| record["Record<br/>keep first xp_uid,<br/>set user property"]
  record --> store["useCrossPromoStore<br/>pendingOpen (MMKV)"]
  store --> gate["Gate<br/>CrossPromoRouteHost"]
  gate -->|"first run done,<br/>tutorial's song opened,<br/>nothing covering, App Open over,<br/>on the tab shell,<br/>catalog loaded"| route["Route<br/>song → genre → Song List"]
  route --> event["crosspromo_deeplink_open"]
```

### 1. Intake

- **Listeners.** The AppsFlyer service registers the deep-link listener **before** `init()` (the
  7.x startup rule: a result that lands before a listener is attached is lost) and the
  conversion-data listener right after it. If iOS rejects the early deep-link registration, it is
  made again, once, after `init()` resolved
  ([`register-before-init.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/attribution/register-before-init.ts)). `start()`
  runs on session ready, once that retry has settled, and resolves both. Results that arrive before anyone subscribes wait in a
  replay channel (up to 10) and go to the first subscriber
  ([`replay-channel.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/attribution/replay-channel.ts)). A failed registration,
  failed conversion data or a throwing subscriber is a non-fatal (`reportNonFatal`, area
  `attribution`).
- **Subscribe.** Boot calls `startCrossPromoDeepLinks()` after the splash intro, before
  AppsFlyer's init ([`start-app-bootstrap.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/bootstrap/start-app-bootstrap.ts)).
- **Payload.** iOS can nest the click's params under `click_event`; they are lifted to the top
  level, and a top-level value wins
  ([`appsflyer-deep-link.pure.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/attribution/adapters/appsflyer-deep-link.pure.ts)).
- **Parse** ([`cross-promo-link.pure.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/cross-promo/logic/cross-promo-link.pure.ts)):
  - `deep_link_sub1..4` → `xp_uid`, `placement`, `song_genre`, `experiment_group`.
  - Fallback: the same `deep_link_sub*` keys in the click URL's query (`link`, `af_dp`,
    `original_link`, `referrer`, `click_http_referrer`).
  - `af_sub1..4` are never read, at the top level or in a click URL: a paid UA campaign fills them
    too, and its install must not count as a cross-promo open.
  - Values are decoded (`Hip-Hop%2FRap` → `Hip-Hop/Rap`, `+` → space). Blanks and OneLink
    template placeholders (`xp_uid`, `deep_link_sub1`, `{…}`, …) count as missing.
  - No real `xp_uid` = not cross promotion: ignored. An organic install sends nothing.
- **`match_type`.** AppsFlyer's `probabilistic` stays `probabilistic`; any other found link is
  `deterministic`; a link recovered from conversion data is `not_found`.
- **`open_type`.** AppsFlyer's deferred flag → `deferred`, else `direct`. Conversion data is
  always `deferred`.
- **Conversion-data fallback** (AppsFlyer's deep link did not resolve). Only on the install's
  first launch, and not once a deep link with a real `xp_uid` has resolved. It is held at once,
  as `not_found`, in the persisted store, so a player who kills the app seconds after the install
  keeps it. A deep link that resolves later for the same click replaces it (see One open per
  click below); the open waits for routing until the first run is over anyway. At most once per
  process
  ([`cross-promo-deep-link-flow.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/cross-promo/cross-promo-deep-link-flow.ts)).

### 2. Record and store

- [`recordCrossPromoOpen`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/cross-promo/cross-promo-open-recorder.ts) keeps the
  install's first `xp_uid`, sets the user property `xp_uid` to that kept value, then hands the
  open over. The property comes first, so every row from the event on carries it. A later link
  never moves it.
- [`useCrossPromoStore`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/cross-promo/store.ts) (MMKV key `cross-promo`):
  - `xpUid`: the first `xp_uid` ever received; null for an install that never had one.
  - `pendingOpen`: the open waiting for routing. It survives relaunches.
  - `lastOpenXpUid`: the click of the last open taken.
- **One open per click** ([`pending-open.pure.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/cross-promo/logic/pending-open.pure.ts)):
  - the same `xp_uid` again is dropped;
  - except: a waiting `not_found` open is replaced by AppsFlyer's own match of the same click;
  - another click while an open still waits is dropped: the first keeps its place.

### 3. Gate

[`CrossPromoRouteHost`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/cross-promo/components/CrossPromoRouteHost.tsx) is
mounted in the root layout and renders nothing. It routes when
([`shouldRouteCrossPromoOpen`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/cross-promo/logic/cross-promo-route-gate.pure.ts)):

- an open is waiting;
- the onboarding and the tutorial are done;
- the tutorial has no song left to open (`selectHasPendingPlay`): the song claimed on the reward
  picker or picked on the exit opens over the Song List the moment the app reaches it, so an open
  routed then would be spent behind it and its focus dropped as the player left for the song;
- nothing covers the screen (`isScreenCovered`): a paywall, a popup, a full-screen ad, the cover
  of a song being launched;
- this launch's App Open step is over (`useAppOpenLaunchStore` phase `done`): it starts once the
  Song List stands uncovered and may wait 5 s for the ad to load, so the song shows after the ad
  instead of under it. A launch that shows no App Open (the first launch, FTUE, too few finished
  songs, premium / No Ads) marks it done at once;
- the screen is on the tab shell: `/songs`, `/profile`, `/mission`, `/leagues` or `/shop`.

Anywhere else (gameplay, Learn, a result, the keyboard) the open keeps waiting, so a song is
never cut short. A deferred open from a fresh install waits out the whole first run and the song
it ends on, across a relaunch. The routing then waits for the catalog to have songs (`runOnceCatalogLoaded`), so
`route_result` is never a lookup in an empty catalog.

### 4. Route

[`resolveCrossPromoRoute`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/cross-promo/logic/cross-promo-route.pure.ts)
matches `song_genre` against what the Song List offers now
([`readSongListOffer`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/songs/song-list-flow-store.ts): release gates applied,
the player's filters ignored).

- **Split** at the last `-`: `Fur_Elise-Classical` → song `Fur_Elise`, genre `Classical`.
  `-Phonk` is genre only. A value without a dash is tried as a song, then as a genre. The whole
  value is tried after its parts, so a dash inside a name or a genre still matches.
- **Song** → `matched_song`. By catalog id, then by name. Both sides compare by a key: accents
  dropped, lower case, letters and digits only (`Fur_Elise` = `fur-elise` = `Für Elise`). The
  Song List brings the song into view and marks it once nothing covers it, however long that
  takes; the mark's 2.5 s count only while nothing covers the list, so an ad or a popup landing
  on it (an App Open on a return from the background) does not use them up. Leaving the tab
  shell first (a song, Learn, the keyboard, a result) drops the ask and ends a mark still showing
  ([songs.md § Focus a song from outside](/docs/features/songs.md#focus-a-song-from-outside-cross-promotion)).
- **Genre** → `matched_genre`. The catalog's genre of that name first (`Folk`, `Hip Hop`), else
  the source app's genre token through its group. The list is filtered to it (`showCategory`:
  search and difficulty cleared, so the genre never lands on an empty list; no `filter_click`).
- **Nothing matched**, or no `song_genre` → `fallback_default`: the Song List as it is.
- **A failure on the way** → `fallback_error`: the Song List as it is.
- From another tab the Song List is brought up (`router.dismissTo("/songs")`). On the Song List
  only the song or the genre changes.
- **Lock rules are unchanged.** Nothing opens, plays or unlocks.
- The open is taken from the store first, then `crosspromo_deeplink_open` is sent: one open, one
  event.

Source genre tokens (MagicPad's sheet) → this app's genre:

| Group     | Tokens                                                                                                        | Genre here               |
| --------- | ------------------------------------------------------------------------------------------------------------- | ------------------------ |
| classical | classical, folk, Classical/Opera/Orchestra, Religious, Soundtracks, Traditional/Folk, World                   | Classical                |
| pop       | pop, rock, country, indie, ballad, Alternative/Indie, Korean Song                                             | Pop                      |
| phonk     | Hip-Hop/Rap, latin, r\&b, soul, Reggae/Ska, Funk, Beat Music                                                  | Phonk                    |
| dance     | dance, edm, house, electronic, Disco, Club/Club Dance                                                         | none: `fallback_default` |
| (none)    | favorite, battleonline, history, get3crown, jazz, blues, chill, acoustic, Children, Holiday, Chill-out, other | none: `fallback_default` |

A `/` compound also stands for each of its parts. `folk` finds the catalog's own `Folk` first.

**Differs from MagicPad:** a `name-genre` value is split at its last `-` (MagicPad does not
split). The conversion-data fallback is held at once (MagicPad waits 5 s for the deep link
first). MagicPad's gift song for a new install is not in
this app.

## `map_user_id`

[`MapUserIdFlow`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/cross-promo/map-user-id-flow.ts), started at boot right after
AppsFlyer's init ([`map-user-id-runtime.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/cross-promo/map-user-id-runtime.ts)):

- **Session start:** the cold start, or a return to the foreground after 30 min or more in the
  background (Firebase's session timeout, `SESSION_TIMEOUT_MS`). It reads the ids fresh and
  sends, even when nothing changed.
- **Within a session:** a return to the foreground (any length) and the ATT answer read the ids
  again. It sends only when the row changed since the last one sent in this session.
- **No AppsFlyer id:** nothing is sent. The next check that finds one sends.
- `inactive` (Control Center, a system alert) is not a trip to the background.
- Checks run one after another, so two that land together send a change once.
- The ATT answer comes from `requestAttForAds` (boot) or the tutorial's `requestAttGuarded`
  (a new player's first answer) → [`notifyAttAnswered`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/sdk/att-answered.ts).
- Rules (pure, tested): [`map-user-id.pure.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/features/cross-promo/logic/map-user-id.pure.ts).

**Differs from MagicPad:** MagicPad waits up to 15 s for the AppsFlyer id and then sends anyway.
Here the spec makes `appsflyer_id` required, and the row goes out at every session start.

## Device ids

[`src/core/device-ids`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/device-ids/device-ids-service.ts) is a port with an iOS
adapter, a fake and a registry. Every read is fresh, and a read that fails, or has not settled
within `DEVICE_ID_READ_TIMEOUT_MS` (5 s), is `null` (never thrown), so one stuck SDK never holds
up `map_user_id`:

| Id                | Source                                                                                                                                                                                                                                                                                            |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| IDFA              | `expo-tracking-transparency`. The all-zero IDFA (no consent) counts as none.                                                                                                                                                                                                                      |
| IDFV              | `expo-application`                                                                                                                                                                                                                                                                                |
| `pseudo_id`       | Firebase Analytics app instance id (`user_pseudo_id` in BigQuery)                                                                                                                                                                                                                                 |
| `installation_id` | `@react-native-firebase/installations`                                                                                                                                                                                                                                                            |
| AppsFlyer id      | the attribution service                                                                                                                                                                                                                                                                           |
| ATT status        | local module [`modules/tracking-authorization`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/modules/tracking-authorization/index.ts): `ATTrackingManager.trackingAuthorizationStatus`, read without prompting, `restricted` kept apart from `denied` |

`ama_device_id` = `ios_` + the IDFV, dashes removed, lower case (MagicPad's rule). Boot reads the
IDFV once (`warmUp`), so `ad_impression` / `ad_impression_ama` carry `ama_device_id` from the
first paid ad (`getCachedAmaDeviceId`).

## Deep-link URLs and the router

[`app/+native-intent.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/app/%2Bnative-intent.ts) keeps an AppsFlyer link away from Expo
Router's "Unmatched Route". An AppsFlyer link
([`isAppsFlyerLinkUrl`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/src/core/attribution/appsflyer-link-url.pure.ts)) is a
`*.onelink.me` URL, or one whose query carries `deep_link_value` or `deep_link_sub*`, on any host
or the app's own scheme. `pid` or `af_*` alone do not make one, so other links with those params
still reach their route.

- **Cold start** (the link launched the app): the router lands on the Song List
  (`/(app)/(tabs)/songs`).
- **App already running:** the router does not navigate (`redirectSystemPath` returns `null`), so
  a song in play is never popped. The open waits in the store, and `CrossPromoRouteHost` routes it
  once the player is on a tab.

AppsFlyer's callback reads the link either way. The DevTool link (`analytics-bridge`) keeps its
own landing. The app's OneLink domain (`iosinapp-event.onelink.me`) is a `*.onelink.me` host, so a
Universal Link open lands the same way. A branded domain (not `*.onelink.me`) without those params
is not recognised.

## Universal Links (direct opens)

A OneLink tapped while the app is installed opens the app directly when three things hold:

1. **The entitlement.** `applinks:iosinapp-event.onelink.me`
   ([`config/associated-domains.ts`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/config/associated-domains.ts), wired into
   `ios.associatedDomains` in `app.config.ts`). The AppDelegate hands the link to AppsFlyer
   (`plugins/withAppsFlyerAttributionFallback.ts` + the AppsFlyer Expo plugin), and the router
   lands as above.
2. **Signing.** The App ID has the Associated Domains capability, and every profile that signs
   the build carries it. CI signs with `match` (read-only): its profiles must be regenerated (or
   the new one imported) before a TestFlight build with this entitlement, or signing fails.
3. **The domain's file.** AppsFlyer lists the app (`<Team ID>.<bundle id>`, paths `/Ko5W/*`) in
   `https://iosinapp-event.onelink.me/.well-known/apple-app-site-association` once template Ko5W
   has the Team ID. iOS reads it when the app is installed or updated (through Apple's CDN, which
   can lag), so a device that installed the app before the file listed it needs a reinstall.

Until all three hold, a tapped OneLink opens the browser or the App Store instead. Deferred opens
(an install from the link) need none of them.

## Files

```text
src/features/cross-promo/
  types.ts                              link params, a resolved open
  store.ts                              xp_uid, waiting open, last click (MMKV)
  cross-promo-deep-link-flow.ts         intake: deep link + conversion-data fallback
  cross-promo-deep-link-runtime.ts      boot wiring: AppsFlyer → flow → recorder → store
  cross-promo-open-recorder.ts          first xp_uid, user property, hold the open
  cross-promo-route-flow.ts             route the waiting open, send the event; catalog wait;
                                        drop a song focus once the player leaves the tab shell
  cross-promo-route-runtime.ts          route wiring: catalog, songs store, router, analytics
  components/CrossPromoRouteHost.tsx    root-mounted gate, renders nothing
  map-user-id-flow.ts                   map_user_id sessions and re-checks
  map-user-id-runtime.ts                boot wiring: AppState, ATT answer, analytics
  logic/                                pure rules, each with a test: link parsing, pending
                                        open, route gate, route, event params, map_user_id
src/core/device-ids/                    device ids port, iOS adapter, fake, registry
src/core/attribution/                   deep-link + conversion listeners, replay channel,
                                        AppsFlyer link URL check
src/core/sdk/att-answered.ts            ATT answer notification
modules/tracking-authorization/         raw ATT status (local Expo module)
app/+native-intent.ts                   AppsFlyer links: Song List on a cold start, no navigation
                                        in a running app
config/associated-domains.ts            Universal Links domain (iOS entitlement)
```

Tests sit in each folder's `__tests__/`. The analytics contract is in
`packages/analytics/tests/cross-promotion-schema.test.ts`.

## Not done yet

- **Universal Links on a device.** Not checked yet: it needs the domain's file to list the app
  and a build signed with a profile that has the capability (see
  [Universal Links](#universal-links-direct-opens)).
- **Deferred payload on a real device.** The deep-link and conversion-data payloads of a real
  install from a OneLink have not been checked on a device yet. The parser follows AppsFlyer's
  documented shapes and MagicPad's parser.
- **`user_subscription` `token_1` / `token_2`** are not in the app. App Store Server
  Notification ids reach the server, never the client. `price` stays text, with `price_value` and
  `currency` beside it.

***

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